| 1 | """Core data model for the v3.0.0 last30days pipeline.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import copy |
| 6 | from dataclasses import asdict, dataclass, field, is_dataclass |
| 7 | from datetime import datetime, timezone |
| 8 | from decimal import Decimal, InvalidOperation |
| 9 | import re |
| 10 | import sys |
| 11 | from typing import Any, Literal |
| 12 | |
| 13 | from . import dates, health |
| 14 | |
| 15 | |
| 16 | def _drop_none(value: Any) -> Any: |
| 17 | """Recursively remove None values from dataclass-derived structures.""" |
| 18 | if is_dataclass(value): |
| 19 | return _drop_none(asdict(value)) |
| 20 | if isinstance(value, dict): |
| 21 | return { |
| 22 | key: _drop_none(item) |
| 23 | for key, item in value.items() |
| 24 | if item is not None |
| 25 | } |
| 26 | if isinstance(value, list): |
| 27 | return [_drop_none(item) for item in value] |
| 28 | return value |
| 29 | |
| 30 | |
| 31 | def _first_non_none(*values: Any) -> Any: |
| 32 | for value in values: |
| 33 | if value is not None: |
| 34 | return value |
| 35 | return None |
| 36 | |
| 37 | |
| 38 | @dataclass(frozen=True) |
| 39 | class ProviderRuntime: |
| 40 | """Resolved runtime provider selection.""" |
| 41 | |
| 42 | reasoning_provider: Literal["gemini", "openai", "xai", "local"] |
| 43 | planner_model: str |
| 44 | rerank_model: str |
| 45 | x_search_backend: Literal["xai", "grok", "bird", "xurl", "xquik", "xapi"] | None = None |
| 46 | |
| 47 | |
| 48 | @dataclass(frozen=True) |
| 49 | class SubQuery: |
| 50 | """Planner-emitted retrieval unit.""" |
| 51 | |
| 52 | label: str |
| 53 | search_query: str |
| 54 | ranking_query: str |
| 55 | sources: list[str] |
| 56 | weight: float = 1.0 |
| 57 | |
| 58 | def __post_init__(self) -> None: |
| 59 | if not self.sources: |
| 60 | raise ValueError("SubQuery must have at least one source") |
| 61 | if self.weight <= 0: |
| 62 | raise ValueError(f"SubQuery weight must be positive, got {self.weight}") |
| 63 | |
| 64 | |
| 65 | @dataclass |
| 66 | class QueryPlan: |
| 67 | """Planner output.""" |
| 68 | |
| 69 | intent: str |
| 70 | freshness_mode: str |
| 71 | cluster_mode: str |
| 72 | raw_topic: str |
| 73 | subqueries: list[SubQuery] |
| 74 | source_weights: dict[str, float] |
| 75 | notes: list[str] = field(default_factory=list) |
| 76 | person_identity_anchors: list[str] = field(default_factory=list) |
| 77 | # The host's Polymarket subject hints: {kind, aliases, related[{name, relation}]}. |
| 78 | polymarket_hints: dict[str, Any] | None = None |
| 79 | # The run's own stories, which the jobs lane searches each board for. |
| 80 | jobs_queries: list[str] = field(default_factory=list) |
| 81 | # A person run: the identity gate fails closed even with no anchors. |
| 82 | person_run: bool = False |
| 83 | |
| 84 | |
| 85 | @dataclass |
| 86 | class SourceItem: |
| 87 | """Generic normalized evidence item.""" |
| 88 | |
| 89 | item_id: str |
| 90 | source: str |
| 91 | title: str |
| 92 | body: str |
| 93 | url: str |
| 94 | author: str | None = None |
| 95 | container: str | None = None |
| 96 | published_at: str | None = None |
| 97 | date_confidence: Literal["high", "med", "low"] = "low" |
| 98 | engagement: dict[str, float | int] = field(default_factory=dict) |
| 99 | relevance_hint: float = 0.5 |
| 100 | why_relevant: str = "" |
| 101 | snippet: str = "" |
| 102 | metadata: dict[str, Any] = field(default_factory=dict) |
| 103 | # Signal fields populated by signals.annotate_stream (after construction) |
| 104 | local_relevance: float | None = None |
| 105 | freshness: int | None = None |
| 106 | engagement_score: float | None = None |
| 107 | source_quality: float | None = None |
| 108 | local_rank_score: float | None = None |
| 109 | |
| 110 | |
| 111 | def github_repo_count_time(item: SourceItem) -> datetime | None: |
| 112 | """UTC time of the GitHub metadata response, including older day-only receipts.""" |
| 113 | metadata = item.metadata or {} |
| 114 | return (dates.parse_date(metadata.get("repo_counts_observed_at")) |
| 115 | or dates.parse_date(metadata.get("repo_counts_observed_on"))) |
| 116 | |
| 117 | |
| 118 | def github_repository_page(item: SourceItem) -> bool | None: |
| 119 | """True for a repository root, False for other pages, None for an unrecognized GitHub-source URL.""" |
| 120 | if item.source != "github" or (item.metadata or {}).get("is_pr"): |
| 121 | return False |
| 122 | page = re.fullmatch(r"https?://(?:www\.)?github\.com(?:/([^?#]*))?(?:[?#][^\s]*)?", item.url or "", re.I) |
| 123 | if page is None: |
| 124 | return None |
| 125 | return re.fullmatch(r"[\w-]+/[\w.-]+/?", page[1] or "", re.ASCII) is not None |
| 126 | |
| 127 | |
| 128 | def github_repo_counter_fields(item: SourceItem) -> tuple[str, ...]: |
| 129 | """The counters requested for this kind of repository card.""" |
| 130 | labels = (item.metadata or {}).get("labels") |
| 131 | if not isinstance(labels, (list, tuple)) or not github_repository_page(item): |
| 132 | return () |
| 133 | if any(label in labels for label in ("project-mode", "own-repo", "recent-push")): |
| 134 | return ("stars", "open_issues") |
| 135 | return ("stars",) if "external-repo" in labels else () |
| 136 | |
| 137 | |
| 138 | @dataclass |
| 139 | class Candidate: |
| 140 | """Global candidate after fusion and reranking.""" |
| 141 | |
| 142 | candidate_id: str |
| 143 | item_id: str |
| 144 | source: str |
| 145 | title: str |
| 146 | url: str |
| 147 | snippet: str |
| 148 | subquery_labels: list[str] |
| 149 | native_ranks: dict[str, int] |
| 150 | local_relevance: float |
| 151 | freshness: int |
| 152 | engagement: int | float | None |
| 153 | source_quality: float |
| 154 | rrf_score: float |
| 155 | sources: list[str] = field(default_factory=list) |
| 156 | source_items: list[SourceItem] = field(default_factory=list) |
| 157 | rerank_score: float | None = None |
| 158 | final_score: float = 0.0 |
| 159 | explanation: str | None = None |
| 160 | fun_score: float | None = None |
| 161 | fun_explanation: str | None = None |
| 162 | cluster_id: str | None = None |
| 163 | metadata: dict[str, Any] = field(default_factory=dict) |
| 164 | |
| 165 | |
| 166 | @dataclass |
| 167 | class Cluster: |
| 168 | """Ranked cluster of related candidates.""" |
| 169 | |
| 170 | cluster_id: str |
| 171 | title: str |
| 172 | candidate_ids: list[str] |
| 173 | representative_ids: list[str] |
| 174 | sources: list[str] |
| 175 | score: float |
| 176 | uncertainty: Literal["single-source", "thin-evidence"] | None = None |
| 177 | |
| 178 | def __post_init__(self) -> None: |
| 179 | if not set(self.representative_ids) <= set(self.candidate_ids): |
| 180 | raise ValueError("representative_ids must be a subset of candidate_ids") |
| 181 | |
| 182 | |
| 183 | RunOutcomeState = Literal[ |
| 184 | "ok", |
| 185 | "no-results", |
| 186 | "partial", |
| 187 | "rate-limited", |
| 188 | "auth-failed", |
| 189 | "payment-required", |
| 190 | "unreachable", |
| 191 | "timeout", |
| 192 | "schema-drift", |
| 193 | "skipped-unconfigured", |
| 194 | "error", |
| 195 | ] |
| 196 | |
| 197 | FreshnessVerdictState = Literal[ |
| 198 | "current", |
| 199 | "stale", |
| 200 | "contradicted", |
| 201 | "unsupported", |
| 202 | ] |
| 203 | |
| 204 | NO_RESULTS = health.NO_RESULTS |
| 205 | PARTIAL = health.PARTIAL |
| 206 | RATE_LIMITED = health.RATE_LIMITED |
| 207 | AUTH_FAILED = health.AUTH_FAILED |
| 208 | PAYMENT_REQUIRED = health.PAYMENT_REQUIRED |
| 209 | UNREACHABLE = health.UNREACHABLE |
| 210 | SCHEMA_DRIFT = health.SCHEMA_DRIFT |
| 211 | SKIPPED_UNCONFIGURED = health.SKIPPED_UNCONFIGURED |
| 212 | |
| 213 | |
| 214 | def _utc_now() -> str: |
| 215 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 216 | |
| 217 | |
| 218 | @dataclass |
| 219 | class SourceOutcome: |
| 220 | """What happened to one source during this run. |
| 221 | |
| 222 | Doctor predicts whether a source is configured and healthy before a run; |
| 223 | this records the observed retrieval result. Shared states reuse |
| 224 | ``health.py`` values (``ok``, ``timeout``, ``error``), while the remaining |
| 225 | states describe run-only outcomes. |
| 226 | """ |
| 227 | |
| 228 | source: str |
| 229 | state: RunOutcomeState |
| 230 | items_returned: int = 0 |
| 231 | attempted: bool = True |
| 232 | detail: str | None = None |
| 233 | at: str = field(default_factory=_utc_now) |
| 234 | # Most specific state among sub-request failures the adapter swallowed |
| 235 | # while still delivering items. Stays informational while items exist; |
| 236 | # becomes the outcome state if post-retrieval filtering empties the source. |
| 237 | lane_failure_state: RunOutcomeState | None = None |
| 238 | fix_hint: str | None = None |
| 239 | |
| 240 | def __post_init__(self) -> None: |
| 241 | valid_states = { |
| 242 | health.OK, |
| 243 | health.TIMEOUT, |
| 244 | health.ERROR, |
| 245 | NO_RESULTS, |
| 246 | PARTIAL, |
| 247 | RATE_LIMITED, |
| 248 | AUTH_FAILED, |
| 249 | PAYMENT_REQUIRED, |
| 250 | UNREACHABLE, |
| 251 | SCHEMA_DRIFT, |
| 252 | SKIPPED_UNCONFIGURED, |
| 253 | } |
| 254 | if self.state not in valid_states: |
| 255 | raise ValueError(f"Unknown source outcome state: {self.state}") |
| 256 | if self.items_returned < 0: |
| 257 | raise ValueError("items_returned cannot be negative") |
| 258 | |
| 259 | |
| 260 | @dataclass(frozen=True) |
| 261 | class FreshnessVerdict: |
| 262 | """Act-time verification result for one source-grounded claim.""" |
| 263 | |
| 264 | claim_id: str |
| 265 | candidate_id: str |
| 266 | claim: str |
| 267 | source: str |
| 268 | source_item_id: str |
| 269 | verdict: FreshnessVerdictState |
| 270 | checked_at: str |
| 271 | source_url: str = "" |
| 272 | source_timestamp: str | None = None |
| 273 | evidence_url: str = "" |
| 274 | evidence_timestamp: str | None = None |
| 275 | original_value: Any = None |
| 276 | current_value: Any = None |
| 277 | detail: str | None = None |
| 278 | |
| 279 | |
| 280 | @dataclass(frozen=True) |
| 281 | class LibraryContext: |
| 282 | """One prior research run relevant to the current report.""" |
| 283 | |
| 284 | topic: str |
| 285 | published_date: str |
| 286 | headline: str |
| 287 | summary: str |
| 288 | source_kind: Literal["brief", "store"] |
| 289 | |
| 290 | |
| 291 | @dataclass |
| 292 | class Report: |
| 293 | """Final pipeline output.""" |
| 294 | |
| 295 | topic: str |
| 296 | range_from: str |
| 297 | range_to: str |
| 298 | generated_at: str |
| 299 | provider_runtime: ProviderRuntime |
| 300 | query_plan: QueryPlan |
| 301 | clusters: list[Cluster] |
| 302 | ranked_candidates: list[Candidate] |
| 303 | items_by_source: dict[str, list[SourceItem]] |
| 304 | errors_by_source: dict[str, str] |
| 305 | source_status: dict[str, SourceOutcome] = field(default_factory=dict) |
| 306 | freshness_verdicts: list[FreshnessVerdict] = field(default_factory=list) |
| 307 | warnings: list[str] = field(default_factory=list) |
| 308 | artifacts: dict[str, Any] = field(default_factory=dict) |
| 309 | library_context: list[LibraryContext] = field(default_factory=list) |
| 310 | drill_of: str | None = None |
| 311 | |
| 312 | |
| 313 | @dataclass(frozen=True) |
| 314 | class DiscoveryPlan: |
| 315 | """Topic-less listing feeds selected for a domain sweep.""" |
| 316 | |
| 317 | domain: str |
| 318 | category: str | None |
| 319 | subreddits: list[str] |
| 320 | sources: list[str] |
| 321 | |
| 322 | |
| 323 | @dataclass(frozen=True) |
| 324 | class DiscoveryTopic: |
| 325 | """One engagement-ranked topic produced by a discovery sweep. |
| 326 | |
| 327 | ``top_comment`` is the strongest verbatim community comment from the |
| 328 | topic's enriched corpus (with attribution), present only on enriched runs. |
| 329 | ``corroboration_count`` is the number of distinct sources confirming the |
| 330 | topic - the floor's cross-source signal, surfaced for readers. |
| 331 | |
| 332 | ``podcast_angle`` and ``x_article_angle`` are engine-generated content |
| 333 | hooks; ``None`` when no reasoning provider produced them. |
| 334 | ``previously_surfaced_count``, ``last_surfaced``, and ``covered`` are |
| 335 | topic-queue annotations; they keep their defaults when the queue is off. |
| 336 | """ |
| 337 | |
| 338 | rank: int |
| 339 | name: str |
| 340 | why_spiking: str |
| 341 | momentum: Literal["new-this-week", "building"] |
| 342 | velocity_score: float |
| 343 | sources: list[str] |
| 344 | engagement_by_source: dict[str, dict[str, float | int]] |
| 345 | command: str |
| 346 | evidence_urls: list[str] = field(default_factory=list) |
| 347 | top_comment: str | None = None |
| 348 | corroboration_count: int = 0 |
| 349 | podcast_angle: str | None = None |
| 350 | x_article_angle: str | None = None |
| 351 | previously_surfaced_count: int = 0 |
| 352 | last_surfaced: str | None = None |
| 353 | covered: bool = False |
| 354 | |
| 355 | |
| 356 | @dataclass |
| 357 | class DiscoveryReport: |
| 358 | """Versioned result of a domain-level listing sweep. |
| 359 | |
| 360 | ``outcome`` is "ok" when at least one topic cleared the confidence floor, |
| 361 | "nothing-solid" when the window's evidence was all sub-floor - an honest |
| 362 | empty result instead of ranked noise. ``weak_signal`` optionally names the |
| 363 | strongest sub-floor topic so a nothing-solid brief can still say what came |
| 364 | closest. |
| 365 | """ |
| 366 | |
| 367 | domain: str |
| 368 | range_from: str |
| 369 | range_to: str |
| 370 | generated_at: str |
| 371 | plan: DiscoveryPlan |
| 372 | topics: list[DiscoveryTopic] |
| 373 | source_status: dict[str, SourceOutcome] = field(default_factory=dict) |
| 374 | warnings: list[str] = field(default_factory=list) |
| 375 | outcome: str = "ok" |
| 376 | weak_signal: str | None = None |
| 377 | |
| 378 | |
| 379 | @dataclass |
| 380 | class RetrievalBundle: |
| 381 | """Structured retrieval output before global ranking.""" |
| 382 | |
| 383 | items_by_source_and_query: dict[tuple[str, str], list[SourceItem]] = field(default_factory=dict) |
| 384 | items_by_source: dict[str, list[SourceItem]] = field(default_factory=dict) |
| 385 | errors_by_source: dict[str, str] = field(default_factory=dict) |
| 386 | source_status: dict[str, SourceOutcome] = field(default_factory=dict) |
| 387 | artifacts: dict[str, Any] = field(default_factory=dict) |
| 388 | # Swallowed sub-request failures on a source that still delivered items. |
| 389 | # These never change the outcome state (the source succeeded); they ride |
| 390 | # along as ``SourceOutcome.detail`` so ``doctor --postmortem`` can show |
| 391 | # what a healthy-looking run lost without branding the source partial. |
| 392 | detail_by_source: dict[str, str] = field(default_factory=dict) |
| 393 | lane_state_by_source: dict[str, RunOutcomeState] = field(default_factory=dict) |
| 394 | # Hard failures recorded via record_failure, kept separate from promoted |
| 395 | # lane_state_by_source entries so a sibling stream delivering items can |
| 396 | # revert a promoted lane state back to OK while hard failures stick. |
| 397 | failed_sources: set[str] = field(default_factory=set) |
| 398 | # Most specific raw failure state recorded via record_failure per source, |
| 399 | # preserved even when items_by_source causes source_status to show PARTIAL. |
| 400 | failure_state_by_source: dict[str, RunOutcomeState] = field(default_factory=dict) |
| 401 | # The raw rows of the company's job board, kept until ranking is done so |
| 402 | # the Jobs Digest can add the roles the run ranked highest. Never rendered. |
| 403 | jobs_board_rows: list[dict[str, Any]] = field(default_factory=list) |
| 404 | |
| 405 | def mark_attempted(self, source: str) -> None: |
| 406 | """Register a planned source before its first retrieval starts.""" |
| 407 | self.source_status.setdefault( |
| 408 | source, |
| 409 | SourceOutcome(source=source, state=NO_RESULTS), |
| 410 | ) |
| 411 | |
| 412 | def record_failure( |
| 413 | self, |
| 414 | source: str, |
| 415 | state: RunOutcomeState, |
| 416 | detail: str, |
| 417 | *, |
| 418 | attempted: bool = True, |
| 419 | ) -> None: |
| 420 | """Record a failure, preserving already-returned items as partial. |
| 421 | |
| 422 | AUTH_FAILED is preserved even when items exist, since the re-login |
| 423 | signal shouldn't be downgraded to generic PARTIAL guidance. Repeat |
| 424 | calls never downgrade an existing AUTH_FAILED or more-specific failure |
| 425 | state per ``health.FAILURE_SPECIFICITY``. |
| 426 | """ |
| 427 | count = len(self.items_by_source.get(source, [])) |
| 428 | previous = self.source_status.get(source) |
| 429 | prev_is_hard = ( |
| 430 | source in self.failed_sources |
| 431 | or ( |
| 432 | previous is not None |
| 433 | and previous.state not in (health.OK, NO_RESULTS) |
| 434 | and previous.fix_hint is not None |
| 435 | ) |
| 436 | ) |
| 437 | prev_raw = self.failure_state_by_source.get(source) |
| 438 | if prev_raw is None and prev_is_hard and previous is not None: |
| 439 | prev_raw = previous.state |
| 440 | |
| 441 | if prev_is_hard and prev_raw is not None: |
| 442 | prev_rank = health.FAILURE_SPECIFICITY.get(prev_raw, 9) |
| 443 | new_rank = health.FAILURE_SPECIFICITY.get(state, 9) |
| 444 | if prev_raw == AUTH_FAILED or prev_rank <= new_rank: |
| 445 | winning_raw = prev_raw |
| 446 | winning_detail = ( |
| 447 | (previous.detail if previous and previous.detail else None) |
| 448 | or detail |
| 449 | ) |
| 450 | winning_attempted = ( |
| 451 | (previous.attempted if previous is not None else False) |
| 452 | or attempted |
| 453 | ) |
| 454 | else: |
| 455 | winning_raw = state |
| 456 | winning_detail = detail |
| 457 | winning_attempted = attempted |
| 458 | else: |
| 459 | winning_raw = state |
| 460 | winning_detail = detail |
| 461 | winning_attempted = attempted |
| 462 | |
| 463 | self.failed_sources.add(source) |
| 464 | self.failure_state_by_source[source] = winning_raw |
| 465 | # Preserve AUTH_FAILED even when items exist: it's an actionable signal |
| 466 | # (re-login needed) that shouldn't be downgraded to PARTIAL. |
| 467 | if winning_raw == AUTH_FAILED: |
| 468 | outcome_state: RunOutcomeState = AUTH_FAILED |
| 469 | else: |
| 470 | outcome_state = PARTIAL if count else winning_raw |
| 471 | if prev_is_hard: |
| 472 | self.errors_by_source[source] = winning_detail |
| 473 | else: |
| 474 | self.errors_by_source.setdefault(source, winning_detail) |
| 475 | self.source_status[source] = SourceOutcome( |
| 476 | source=source, |
| 477 | state=outcome_state, |
| 478 | items_returned=count, |
| 479 | attempted=winning_attempted, |
| 480 | detail=winning_detail, |
| 481 | fix_hint="doctor", |
| 482 | ) |
| 483 | |
| 484 | def record_detail( |
| 485 | self, |
| 486 | source: str, |
| 487 | detail: str, |
| 488 | state: RunOutcomeState | None = None, |
| 489 | ) -> None: |
| 490 | """Note a swallowed lane failure on a source that still delivered items. |
| 491 | |
| 492 | Unlike :meth:`record_failure`, this never changes the outcome state and |
| 493 | sets no ``fix_hint``. The note is merged into the ``ok`` outcome on the |
| 494 | next :meth:`add_items` and survives later clean subqueries. |
| 495 | """ |
| 496 | detail = " ".join((detail or "").split()) |
| 497 | if not detail: |
| 498 | return |
| 499 | existing = self.detail_by_source.get(source) |
| 500 | if existing: |
| 501 | existing_clauses = [clause.strip() for clause in existing.split(";") if clause.strip()] |
| 502 | incoming_clauses = [clause.strip() for clause in detail.split(";") if clause.strip()] |
| 503 | if set(incoming_clauses).issubset(existing_clauses): |
| 504 | detail = existing |
| 505 | elif set(existing_clauses).issubset(incoming_clauses): |
| 506 | detail = "; ".join(dict.fromkeys(incoming_clauses)) |
| 507 | else: |
| 508 | # Order merged clauses longest-first (Python's stable sort |
| 509 | # preserves arrival order on ties) so concurrent subqueries |
| 510 | # produce a deterministic leading detail regardless of finish order. |
| 511 | detail = "; ".join( |
| 512 | sorted( |
| 513 | dict.fromkeys(existing_clauses + incoming_clauses), |
| 514 | key=lambda clause: -len(clause), |
| 515 | ) |
| 516 | ) |
| 517 | self.detail_by_source[source] = detail |
| 518 | if state: |
| 519 | prev_lane_state = self.lane_state_by_source.get(source) |
| 520 | if ( |
| 521 | prev_lane_state is None |
| 522 | or health.FAILURE_SPECIFICITY.get(state, 9) |
| 523 | < health.FAILURE_SPECIFICITY.get(prev_lane_state, 9) |
| 524 | ): |
| 525 | self.lane_state_by_source[source] = state |
| 526 | current = self.source_status.get(source) |
| 527 | if current and ( |
| 528 | current.state in (health.OK, NO_RESULTS) |
| 529 | or source not in self.failed_sources |
| 530 | ): |
| 531 | current.detail = detail |
| 532 | current.lane_failure_state = self.lane_state_by_source.get(source) |
| 533 | |
| 534 | def add_items(self, label: str, source: str, items: list[SourceItem]) -> None: |
| 535 | """Atomically append items to both items_by_source_and_query and items_by_source.""" |
| 536 | self.items_by_source_and_query.setdefault((label, source), []).extend(items) |
| 537 | self.items_by_source.setdefault(source, []).extend(items) |
| 538 | previous = self.source_status.get(source) |
| 539 | has_items = bool(self.items_by_source[source]) |
| 540 | state: RunOutcomeState = health.OK if (items or has_items) else NO_RESULTS |
| 541 | detail = None |
| 542 | fix_hint = None |
| 543 | if previous and previous.state == health.OK and not items: |
| 544 | # A later empty subquery must not downgrade a source that already |
| 545 | # delivered items to no-results. |
| 546 | state = health.OK |
| 547 | lane_state = None |
| 548 | if state in (health.OK, NO_RESULTS): |
| 549 | detail = self.detail_by_source.get(source) |
| 550 | lane_state = self.lane_state_by_source.get(source) |
| 551 | if state == NO_RESULTS and lane_state and not has_items: |
| 552 | # Nothing delivered and sub-requests failed: that is the |
| 553 | # failure, not a clean empty result. |
| 554 | state = lane_state |
| 555 | prev_is_hard = ( |
| 556 | source in self.failed_sources |
| 557 | or ( |
| 558 | previous is not None |
| 559 | and previous.state not in (health.OK, NO_RESULTS) |
| 560 | and previous.fix_hint is not None |
| 561 | ) |
| 562 | ) |
| 563 | if prev_is_hard and previous is not None and previous.state not in (health.OK, NO_RESULTS): |
| 564 | # Preserve AUTH_FAILED state even when items are added: it's an |
| 565 | # actionable signal (re-login needed) that shouldn't be downgraded |
| 566 | # to PARTIAL. Other hard failure states become PARTIAL when items |
| 567 | # exist. Promoted lane_state values are not hard failures and |
| 568 | # revert to OK as soon as any sibling stream delivers items. |
| 569 | if previous.state == AUTH_FAILED: |
| 570 | state = AUTH_FAILED |
| 571 | else: |
| 572 | state = PARTIAL if has_items else previous.state |
| 573 | detail = previous.detail |
| 574 | fix_hint = previous.fix_hint |
| 575 | self.source_status[source] = SourceOutcome( |
| 576 | source=source, |
| 577 | state=state, |
| 578 | items_returned=len(self.items_by_source[source]), |
| 579 | attempted=True, |
| 580 | detail=detail, |
| 581 | fix_hint=fix_hint, |
| 582 | lane_failure_state=lane_state, |
| 583 | ) |
| 584 | |
| 585 | |
| 586 | def to_dict(value: Any) -> Any: |
| 587 | """Serialize dataclasses and nested containers.""" |
| 588 | return _drop_none(value) |
| 589 | |
| 590 | |
| 591 | def provider_runtime_from_dict(payload: dict[str, Any]) -> ProviderRuntime: |
| 592 | return ProviderRuntime( |
| 593 | reasoning_provider=payload["reasoning_provider"], |
| 594 | planner_model=payload["planner_model"], |
| 595 | rerank_model=payload["rerank_model"], |
| 596 | x_search_backend=payload.get("x_search_backend"), |
| 597 | ) |
| 598 | |
| 599 | |
| 600 | def subquery_from_dict(payload: dict[str, Any]) -> SubQuery: |
| 601 | return SubQuery( |
| 602 | label=payload["label"], |
| 603 | search_query=payload["search_query"], |
| 604 | ranking_query=payload["ranking_query"], |
| 605 | sources=list(payload.get("sources") or []), |
| 606 | weight=float(payload.get("weight") or 1.0), |
| 607 | ) |
| 608 | |
| 609 | |
| 610 | def query_plan_from_dict(payload: dict[str, Any]) -> QueryPlan: |
| 611 | return QueryPlan( |
| 612 | intent=payload["intent"], |
| 613 | freshness_mode=payload["freshness_mode"], |
| 614 | cluster_mode=payload["cluster_mode"], |
| 615 | raw_topic=payload["raw_topic"], |
| 616 | subqueries=[subquery_from_dict(item) for item in payload.get("subqueries") or []], |
| 617 | source_weights=dict(payload.get("source_weights") or {}), |
| 618 | notes=list(payload.get("notes") or []), |
| 619 | person_identity_anchors=list(payload.get("person_identity_anchors") or []), |
| 620 | polymarket_hints=copy.deepcopy(payload.get("polymarket_hints")), |
| 621 | jobs_queries=list(payload.get("jobs_queries") or []), |
| 622 | person_run=bool(payload.get("person_run", False)), |
| 623 | ) |
| 624 | |
| 625 | |
| 626 | GITHUB_REPO_COUNTERS = frozenset({"stars", "open_issues"}) |
| 627 | _MAX_REPORT_COUNT = int(sys.float_info.max) |
| 628 | |
| 629 | |
| 630 | def _saved_repo_count(value: object) -> int | Decimal | None: |
| 631 | """Parse a whole count without rounding older string or float encodings.""" |
| 632 | if type(value) is int: |
| 633 | return value if value >= 0 else None |
| 634 | if isinstance(value, float): |
| 635 | return int(value) if value >= 0 and value.is_integer() else None |
| 636 | if not isinstance(value, str): |
| 637 | return None |
| 638 | try: |
| 639 | count = Decimal(value) |
| 640 | except InvalidOperation: |
| 641 | return None |
| 642 | if count.is_finite() and count >= 0 and count == count.to_integral_value(): |
| 643 | return count |
| 644 | return None |
| 645 | |
| 646 | |
| 647 | def github_repo_count(value: object) -> int | None: |
| 648 | """Return an exact count within the range supported by numeric report consumers.""" |
| 649 | count = _saved_repo_count(value) |
| 650 | if count is None or count > _MAX_REPORT_COUNT: |
| 651 | return None |
| 652 | return int(count) |
| 653 | |
| 654 | |
| 655 | def engagement_value(item: SourceItem, field: str) -> Any: |
| 656 | """Read a metric for reporting while preserving its original archive representation.""" |
| 657 | value = item.engagement.get(field) if isinstance(item.engagement, dict) else None |
| 658 | if item.source == "github" and field in GITHUB_REPO_COUNTERS: |
| 659 | return github_repo_count(value) |
| 660 | return value |
| 661 | |
| 662 | |
| 663 | def source_item_from_dict(payload: dict[str, Any]) -> SourceItem: |
| 664 | meta = dict(payload.get("metadata") or {}) |
| 665 | engagement = dict(payload.get("engagement") or {}) |
| 666 | if payload["source"] == "github": |
| 667 | for key in GITHUB_REPO_COUNTERS.intersection(engagement): |
| 668 | if _saved_repo_count(engagement[key]) is None: |
| 669 | del engagement[key] |
| 670 | if GITHUB_REPO_COUNTERS.isdisjoint(engagement): |
| 671 | meta.pop("repo_counts_observed_at", None) |
| 672 | meta.pop("repo_counts_observed_on", None) |
| 673 | return SourceItem( |
| 674 | item_id=payload["item_id"], |
| 675 | source=payload["source"], |
| 676 | title=payload["title"], |
| 677 | body=payload.get("body") or "", |
| 678 | url=payload.get("url") or "", |
| 679 | author=payload.get("author"), |
| 680 | container=payload.get("container"), |
| 681 | published_at=payload.get("published_at"), |
| 682 | date_confidence=payload.get("date_confidence") or "low", |
| 683 | engagement=engagement, |
| 684 | relevance_hint=float(_first_non_none(payload.get("relevance_hint"), 0.5)), |
| 685 | why_relevant=payload.get("why_relevant") or "", |
| 686 | snippet=payload.get("snippet") or "", |
| 687 | metadata=meta, |
| 688 | local_relevance=_first_non_none(payload.get("local_relevance"), meta.get("local_relevance")), |
| 689 | freshness=_first_non_none(payload.get("freshness"), meta.get("freshness")), |
| 690 | engagement_score=_first_non_none(payload.get("engagement_score"), meta.get("engagement_score")), |
| 691 | source_quality=_first_non_none(payload.get("source_quality"), meta.get("source_quality")), |
| 692 | local_rank_score=_first_non_none(payload.get("local_rank_score"), meta.get("local_rank_score")), |
| 693 | ) |
| 694 | |
| 695 | |
| 696 | def candidate_from_dict(payload: dict[str, Any]) -> Candidate: |
| 697 | meta = dict(payload.get("metadata") or {}) |
| 698 | stars = meta.get("github_stars") |
| 699 | if isinstance(stars, dict): |
| 700 | meta["github_stars"] = { |
| 701 | repo: count for repo, count in stars.items() if _saved_repo_count(count) is not None |
| 702 | } |
| 703 | return Candidate( |
| 704 | candidate_id=payload["candidate_id"], |
| 705 | item_id=payload["item_id"], |
| 706 | source=payload["source"], |
| 707 | title=payload["title"], |
| 708 | url=payload.get("url") or "", |
| 709 | snippet=payload.get("snippet") or "", |
| 710 | subquery_labels=list(payload.get("subquery_labels") or []), |
| 711 | native_ranks={key: int(value) for key, value in (payload.get("native_ranks") or {}).items()}, |
| 712 | local_relevance=float(_first_non_none(payload.get("local_relevance"), 0.0)), |
| 713 | freshness=int(_first_non_none(payload.get("freshness"), 0)), |
| 714 | engagement=payload.get("engagement"), |
| 715 | source_quality=float(_first_non_none(payload.get("source_quality"), 0.0)), |
| 716 | rrf_score=float(_first_non_none(payload.get("rrf_score"), 0.0)), |
| 717 | sources=list(payload.get("sources") or []), |
| 718 | source_items=[source_item_from_dict(item) for item in payload.get("source_items") or []], |
| 719 | rerank_score=float(payload["rerank_score"]) if payload.get("rerank_score") is not None else None, |
| 720 | final_score=float(_first_non_none(payload.get("final_score"), 0.0)), |
| 721 | explanation=payload.get("explanation"), |
| 722 | fun_score=float(payload["fun_score"]) if payload.get("fun_score") is not None else None, |
| 723 | fun_explanation=payload.get("fun_explanation"), |
| 724 | cluster_id=payload.get("cluster_id"), |
| 725 | metadata=meta, |
| 726 | ) |
| 727 | |
| 728 | |
| 729 | def cluster_from_dict(payload: dict[str, Any]) -> Cluster: |
| 730 | return Cluster( |
| 731 | cluster_id=payload["cluster_id"], |
| 732 | title=payload["title"], |
| 733 | candidate_ids=list(payload.get("candidate_ids") or []), |
| 734 | representative_ids=list(payload.get("representative_ids") or []), |
| 735 | sources=list(payload.get("sources") or []), |
| 736 | score=float(_first_non_none(payload.get("score"), 0.0)), |
| 737 | uncertainty=payload.get("uncertainty"), |
| 738 | ) |
| 739 | |
| 740 | |
| 741 | def _source_status_from_dict(payload: dict[str, Any]) -> dict[str, "SourceOutcome"]: |
| 742 | """Rebuild the per-source outcome map shared by every report |
| 743 | deserializer, so the SourceOutcome reconstruction cannot drift between |
| 744 | them.""" |
| 745 | return { |
| 746 | source: SourceOutcome( |
| 747 | source=outcome.get("source") or source, |
| 748 | state=outcome["state"], |
| 749 | items_returned=int(outcome.get("items_returned") or 0), |
| 750 | attempted=bool(outcome.get("attempted", True)), |
| 751 | detail=outcome.get("detail"), |
| 752 | lane_failure_state=outcome.get("lane_failure_state"), |
| 753 | at=outcome.get("at") or _utc_now(), |
| 754 | fix_hint=outcome.get("fix_hint"), |
| 755 | ) |
| 756 | for source, outcome in (payload.get("source_status") or {}).items() |
| 757 | } |
| 758 | |
| 759 | |
| 760 | def report_from_dict(payload: dict[str, Any]) -> Report: |
| 761 | return Report( |
| 762 | topic=payload["topic"], |
| 763 | range_from=payload["range_from"], |
| 764 | range_to=payload["range_to"], |
| 765 | generated_at=payload["generated_at"], |
| 766 | provider_runtime=provider_runtime_from_dict(payload["provider_runtime"]), |
| 767 | query_plan=query_plan_from_dict(payload["query_plan"]), |
| 768 | clusters=[cluster_from_dict(item) for item in payload.get("clusters") or []], |
| 769 | ranked_candidates=[candidate_from_dict(item) for item in payload.get("ranked_candidates") or []], |
| 770 | items_by_source={ |
| 771 | source: [source_item_from_dict(item) for item in items] |
| 772 | for source, items in (payload.get("items_by_source") or {}).items() |
| 773 | }, |
| 774 | errors_by_source=dict(payload.get("errors_by_source") or {}), |
| 775 | source_status=_source_status_from_dict(payload), |
| 776 | freshness_verdicts=[ |
| 777 | FreshnessVerdict( |
| 778 | claim_id=item["claim_id"], |
| 779 | candidate_id=item["candidate_id"], |
| 780 | claim=item["claim"], |
| 781 | source=item["source"], |
| 782 | source_item_id=item["source_item_id"], |
| 783 | verdict=item["verdict"], |
| 784 | checked_at=item["checked_at"], |
| 785 | source_url=item.get("source_url") or "", |
| 786 | source_timestamp=item.get("source_timestamp"), |
| 787 | evidence_url=item.get("evidence_url") or "", |
| 788 | evidence_timestamp=item.get("evidence_timestamp"), |
| 789 | original_value=item.get("original_value"), |
| 790 | current_value=item.get("current_value"), |
| 791 | detail=item.get("detail"), |
| 792 | ) |
| 793 | for item in (payload.get("freshness_verdicts") or []) |
| 794 | if isinstance(item, dict) |
| 795 | ], |
| 796 | warnings=list(payload.get("warnings") or []), |
| 797 | artifacts=dict(payload.get("artifacts") or {}), |
| 798 | library_context=[ |
| 799 | LibraryContext( |
| 800 | topic=str(item.get("topic") or ""), |
| 801 | published_date=str(item.get("published_date") or ""), |
| 802 | headline=str(item.get("headline") or ""), |
| 803 | summary=str(item.get("summary") or ""), |
| 804 | source_kind=( |
| 805 | "store" if item.get("source_kind") == "store" else "brief" |
| 806 | ), |
| 807 | ) |
| 808 | for item in (payload.get("library_context") or []) |
| 809 | if isinstance(item, dict) |
| 810 | ], |
| 811 | drill_of=payload.get("drill_of"), |
| 812 | ) |
| 813 | |
| 814 | |
| 815 | def candidate_sources(candidate: Candidate) -> list[str]: |
| 816 | if candidate.sources: |
| 817 | return candidate.sources |
| 818 | return [candidate.source] if candidate.source else [] |
| 819 | |
| 820 | |
| 821 | def candidate_has_corpus(candidate: Candidate) -> bool: |
| 822 | return ( |
| 823 | candidate.source == "corpus" |
| 824 | or "corpus" in candidate.sources |
| 825 | or any(item.source == "corpus" for item in candidate.source_items) |
| 826 | ) |
| 827 | |
| 828 | |
| 829 | def report_has_corpus(report: Report) -> bool: |
| 830 | return ( |
| 831 | "corpus" in report.source_status |
| 832 | or bool(report.items_by_source.get("corpus")) |
| 833 | or any(candidate_has_corpus(candidate) for candidate in report.ranked_candidates) |
| 834 | or any("corpus" in cluster.sources for cluster in report.clusters) |
| 835 | or bool(partition_freshness_verdicts(report, {"corpus"})[1]) |
| 836 | ) |
| 837 | |
| 838 | |
| 839 | def drill_has_corpus_context(report: Report) -> bool: |
| 840 | return bool( |
| 841 | (report.drill_of or "drill_context" in report.artifacts or "drill_history" in report.artifacts) |
| 842 | and report_has_corpus(report) |
| 843 | ) |
| 844 | |
| 845 | |
| 846 | def candidate_source_label(candidate: Candidate) -> str: |
| 847 | sources = candidate_sources(candidate) |
| 848 | return ", ".join(sources) if sources else "unknown" |
| 849 | |
| 850 | |
| 851 | def candidate_out_of_window(candidate: Candidate) -> bool: |
| 852 | """True when every dated item behind this candidate falls outside the window. |
| 853 | |
| 854 | Window membership is derived from the actual ``published_at`` date compared |
| 855 | to the run's ``range_from``/``range_to`` (stored in candidate.metadata by |
| 856 | fusion.weighted_rrf). Some adapters provide ``date_confidence="high"`` for |
| 857 | old dates, so relying solely on adapter-provided confidence is insufficient. |
| 858 | |
| 859 | Candidates with no dated item at all are not treated as out of window — an |
| 860 | unknown date is a coverage gap, not a stale item. |
| 861 | """ |
| 862 | start = dates.parse_date(candidate.metadata.get("range_from")) |
| 863 | end = dates.parse_date(candidate.metadata.get("range_to")) |
| 864 | if start is not None and end is not None: |
| 865 | start_day, end_day = start.date(), end.date() |
| 866 | has_dated_evidence = False |
| 867 | for item in candidate.source_items: |
| 868 | # Comment search can date the evidence even when the thread has no date. |
| 869 | for value in (item.published_at, (item.metadata or {}).get("matched_comment_date")): |
| 870 | parsed = dates.parse_date(value) |
| 871 | if parsed is not None: |
| 872 | has_dated_evidence = True |
| 873 | if start_day <= parsed.date() <= end_day: |
| 874 | return False |
| 875 | return has_dated_evidence |
| 876 | |
| 877 | dated = [item for item in candidate.source_items if item.published_at] |
| 878 | return bool(dated) and all(item.date_confidence != "high" for item in dated) |
| 879 | |
| 880 | |
| 881 | def candidate_best_published_at(candidate: Candidate) -> str | None: |
| 882 | return max( |
| 883 | (item.published_at for item in candidate.source_items if item.published_at), |
| 884 | default=None, |
| 885 | ) |
| 886 | |
| 887 | |
| 888 | def candidate_primary_item(candidate: Candidate) -> SourceItem | None: |
| 889 | if not candidate.source_items: |
| 890 | return None |
| 891 | for item in candidate.source_items: |
| 892 | if item.source == candidate.source: |
| 893 | return item |
| 894 | return candidate.source_items[0] |
| 895 | |
| 896 | |
| 897 | AGENT_EXPORT_SCHEMA_VERSION = "1.4" |
| 898 | |
| 899 | |
| 900 | def partition_freshness_verdicts( |
| 901 | report: Report, excluded: set[str], |
| 902 | ) -> tuple[list[FreshnessVerdict], list[FreshnessVerdict]]: |
| 903 | if not report.freshness_verdicts: |
| 904 | return [], [] |
| 905 | excluded_urls = { |
| 906 | item.url |
| 907 | for items in report.items_by_source.values() |
| 908 | for item in items |
| 909 | if item.url and item.source.lower() in excluded |
| 910 | } |
| 911 | excluded_urls.update( |
| 912 | item.url |
| 913 | for candidate in report.ranked_candidates |
| 914 | for item in candidate.source_items |
| 915 | if item.url and item.source.lower() in excluded |
| 916 | ) |
| 917 | public, private = [], [] |
| 918 | for verdict in report.freshness_verdicts: |
| 919 | urls = (verdict.source_url, verdict.evidence_url) |
| 920 | if verdict.source.lower() in excluded or any(url in excluded_urls for url in urls): |
| 921 | private.append(verdict) |
| 922 | elif "corpus" in excluded and ( |
| 923 | any(url.lower().startswith("corpus://") for url in urls) |
| 924 | or verdict.detail == "Newer corpus item disagrees" |
| 925 | ): |
| 926 | private.append(verdict) |
| 927 | else: |
| 928 | public.append(verdict) |
| 929 | return public, private |
| 930 | |
| 931 | |
| 932 | def _artifact_matches_source(key: str, source: str) -> bool: |
| 933 | """Match artifact keys by exact name or delimiter-bounded token segment.""" |
| 934 | return re.search(rf"(?:^|[_\-]){re.escape(source)}(?:$|[_\-])", key.lower()) is not None |
| 935 | |
| 936 | |
| 937 | def without_sources(report: Report, excluded_sources: set[str]) -> Report: |
| 938 | """Return a deep-copied report with private source evidence removed. |
| 939 | |
| 940 | This is the publication boundary used by agent JSON, hosted HTML, and |
| 941 | future outbound surfaces. Cluster titles are rebuilt when a removed item |
| 942 | participated so text derived from a private representative cannot survive |
| 943 | after its candidate is gone. |
| 944 | """ |
| 945 | excluded = {source.lower() for source in excluded_sources} |
| 946 | if not excluded: |
| 947 | return copy.deepcopy(report) |
| 948 | private_drill = "corpus" in excluded and drill_has_corpus_context(report) |
| 949 | clean = copy.deepcopy(report) |
| 950 | public_verdicts, _ = partition_freshness_verdicts(clean, excluded) |
| 951 | clean.items_by_source = { |
| 952 | source: items |
| 953 | for source, items in clean.items_by_source.items() |
| 954 | if source.lower() not in excluded |
| 955 | } |
| 956 | clean.errors_by_source = { |
| 957 | source: detail |
| 958 | for source, detail in clean.errors_by_source.items() |
| 959 | if source.lower() not in excluded |
| 960 | } |
| 961 | clean.source_status = { |
| 962 | source: outcome |
| 963 | for source, outcome in clean.source_status.items() |
| 964 | if source.lower() not in excluded |
| 965 | } |
| 966 | clean.query_plan.source_weights = { |
| 967 | source: weight |
| 968 | for source, weight in clean.query_plan.source_weights.items() |
| 969 | if source.lower() not in excluded |
| 970 | } |
| 971 | rebuilt_subqueries: list[SubQuery] = [] |
| 972 | for subquery in clean.query_plan.subqueries: |
| 973 | remaining_sources = [ |
| 974 | source for source in subquery.sources if source.lower() not in excluded |
| 975 | ] |
| 976 | if remaining_sources: |
| 977 | rebuilt_subqueries.append( |
| 978 | SubQuery( |
| 979 | label=subquery.label, |
| 980 | search_query=subquery.search_query, |
| 981 | ranking_query=subquery.ranking_query, |
| 982 | sources=remaining_sources, |
| 983 | weight=subquery.weight, |
| 984 | ) |
| 985 | ) |
| 986 | clean.query_plan.subqueries = rebuilt_subqueries |
| 987 | |
| 988 | kept_candidates: list[Candidate] = [] |
| 989 | removed_candidate_ids: set[str] = set() |
| 990 | rehomed_candidate_ids: set[str] = set() |
| 991 | for candidate in clean.ranked_candidates: |
| 992 | had_source_items = bool(candidate.source_items) |
| 993 | removed_items = [ |
| 994 | item for item in candidate.source_items if item.source.lower() in excluded |
| 995 | ] |
| 996 | surviving_items = [ |
| 997 | item for item in candidate.source_items if item.source.lower() not in excluded |
| 998 | ] |
| 999 | if (had_source_items and not surviving_items) or ( |
| 1000 | not had_source_items and candidate.source.lower() in excluded |
| 1001 | ): |
| 1002 | removed_candidate_ids.add(candidate.candidate_id) |
| 1003 | continue |
| 1004 | |
| 1005 | candidate.source_items = surviving_items |
| 1006 | if candidate.source.lower() in excluded: |
| 1007 | primary = surviving_items[0] |
| 1008 | candidate.item_id = primary.item_id |
| 1009 | candidate.source = primary.source |
| 1010 | candidate.title = primary.title |
| 1011 | candidate.url = primary.url |
| 1012 | candidate.snippet = primary.snippet or primary.body |
| 1013 | candidate.explanation = None |
| 1014 | candidate.fun_explanation = None |
| 1015 | rehomed_candidate_ids.add(candidate.candidate_id) |
| 1016 | elif removed_items and surviving_items and candidate.snippet: |
| 1017 | removed_texts = { |
| 1018 | text |
| 1019 | for item in removed_items |
| 1020 | for text in (item.snippet, item.body) |
| 1021 | if text |
| 1022 | } |
| 1023 | if candidate.snippet in removed_texts: |
| 1024 | primary = candidate_primary_item(candidate) |
| 1025 | candidate.snippet = (primary.snippet or primary.body) if primary else "" |
| 1026 | |
| 1027 | filtered_sources = [ |
| 1028 | source for source in candidate.sources if source.lower() not in excluded |
| 1029 | ] |
| 1030 | if not filtered_sources and surviving_items: |
| 1031 | filtered_sources = list(dict.fromkeys(item.source for item in surviving_items)) |
| 1032 | elif ( |
| 1033 | (surviving_items or candidate.sources) |
| 1034 | and candidate.source |
| 1035 | and candidate.source.lower() not in {s.lower() for s in filtered_sources} |
| 1036 | ): |
| 1037 | filtered_sources = [candidate.source, *filtered_sources] |
| 1038 | candidate.sources = filtered_sources |
| 1039 | candidate.native_ranks = { |
| 1040 | key: rank |
| 1041 | for key, rank in candidate.native_ranks.items() |
| 1042 | if key.rsplit(":", 1)[-1].lower() not in excluded |
| 1043 | } |
| 1044 | provenance = candidate.metadata.get("provenance") |
| 1045 | if isinstance(provenance, list): |
| 1046 | candidate.metadata["provenance"] = [ |
| 1047 | entry |
| 1048 | for entry in provenance |
| 1049 | if not ( |
| 1050 | isinstance(entry, dict) |
| 1051 | and str(entry.get("source") or "").lower() in excluded |
| 1052 | ) |
| 1053 | ] |
| 1054 | kept_candidates.append(candidate) |
| 1055 | clean.ranked_candidates = kept_candidates |
| 1056 | candidate_by_id = { |
| 1057 | candidate.candidate_id: candidate for candidate in clean.ranked_candidates |
| 1058 | } |
| 1059 | |
| 1060 | kept_clusters: list[Cluster] = [] |
| 1061 | title_invalidated_ids = removed_candidate_ids | rehomed_candidate_ids |
| 1062 | for cluster in clean.clusters: |
| 1063 | original_ids = list(cluster.candidate_ids) |
| 1064 | cluster.candidate_ids = [ |
| 1065 | candidate_id for candidate_id in original_ids if candidate_id in candidate_by_id |
| 1066 | ] |
| 1067 | if not cluster.candidate_ids: |
| 1068 | continue |
| 1069 | cluster.representative_ids = [ |
| 1070 | candidate_id |
| 1071 | for candidate_id in cluster.representative_ids |
| 1072 | if candidate_id in candidate_by_id |
| 1073 | ] or [cluster.candidate_ids[0]] |
| 1074 | cluster.sources = sorted({ |
| 1075 | source |
| 1076 | for candidate_id in cluster.candidate_ids |
| 1077 | for source in candidate_sources(candidate_by_id[candidate_id]) |
| 1078 | if source.lower() not in excluded |
| 1079 | }) |
| 1080 | if private_drill or any(candidate_id in title_invalidated_ids for candidate_id in original_ids): |
| 1081 | cluster.title = candidate_by_id[cluster.representative_ids[0]].title |
| 1082 | kept_clusters.append(cluster) |
| 1083 | clean.clusters = kept_clusters |
| 1084 | clean.freshness_verdicts = [ |
| 1085 | verdict |
| 1086 | for verdict in public_verdicts |
| 1087 | if verdict.candidate_id in candidate_by_id |
| 1088 | ] |
| 1089 | for key in list(clean.artifacts): |
| 1090 | if any(_artifact_matches_source(key, source) for source in excluded): |
| 1091 | del clean.artifacts[key] |
| 1092 | if private_drill: |
| 1093 | clean.drill_of = None |
| 1094 | clean.artifacts.pop("drill_context", None) |
| 1095 | clean.artifacts.pop("drill_history", None) |
| 1096 | # Older cached drill plans can mix private titles into public queries. |
| 1097 | clean.query_plan.subqueries = [] |
| 1098 | return clean |
| 1099 | |
| 1100 | |
| 1101 | DISCOVERY_EXPORT_SCHEMA_VERSION = "1.1" |
| 1102 | |
| 1103 | |
| 1104 | def _agent_summary(candidate: Candidate) -> str: |
| 1105 | primary = candidate_primary_item(candidate) |
| 1106 | return ( |
| 1107 | candidate.snippet |
| 1108 | or (primary.snippet if primary else "") |
| 1109 | or candidate.explanation |
| 1110 | or (primary.body if primary else "") |
| 1111 | ) |
| 1112 | |
| 1113 | |
| 1114 | def _agent_engagement(candidate: Candidate) -> dict[str, float | int]: |
| 1115 | primary = candidate_primary_item(candidate) |
| 1116 | if primary is None: |
| 1117 | return {} |
| 1118 | engagement = dict(primary.engagement) |
| 1119 | if primary.source == "github": |
| 1120 | for field in GITHUB_REPO_COUNTERS.intersection(engagement): |
| 1121 | count = github_repo_count(engagement[field]) |
| 1122 | if count is None: |
| 1123 | del engagement[field] |
| 1124 | else: |
| 1125 | engagement[field] = count |
| 1126 | return engagement |
| 1127 | |
| 1128 | |
| 1129 | _HEADLINE_ENGAGEMENT_FIELDS_BY_SOURCE = { |
| 1130 | "digg": ("postCount",), |
| 1131 | "reddit": ("score",), |
| 1132 | "stocktwits": ("likes", "reshares"), |
| 1133 | } |
| 1134 | |
| 1135 | |
| 1136 | def is_summable_engagement_field(source: str, field: str) -> bool: |
| 1137 | """True when ``field`` may be added up across a source's items. |
| 1138 | |
| 1139 | Counters are additive; a score or rank says something about one item |
| 1140 | and is not, except where it is the source's headline counter (Reddit's |
| 1141 | ``score`` is its upvote count). |
| 1142 | """ |
| 1143 | return _is_counter_field(field) or field in _HEADLINE_ENGAGEMENT_FIELDS_BY_SOURCE.get(source, ()) |
| 1144 | |
| 1145 | |
| 1146 | def _is_counter_field(field: str) -> bool: |
| 1147 | normalized = field.lower() |
| 1148 | return not ( |
| 1149 | # Author-reach and position/score metadata, not per-item engagement. |
| 1150 | normalized in {"rank", "rating", "score", "trustscore", "followers", "subscribers"} |
| 1151 | or normalized.endswith(("_rank", "_score", "_ratio", "_rate", "_followers")) |
| 1152 | ) |
| 1153 | |
| 1154 | |
| 1155 | def _headline_engagement(candidate: Candidate) -> int | float: |
| 1156 | """Return the primary item's largest native engagement counter.""" |
| 1157 | engagement = _agent_engagement(candidate) |
| 1158 | preferred_fields = _HEADLINE_ENGAGEMENT_FIELDS_BY_SOURCE.get(candidate.source, ()) |
| 1159 | preferred_values = [ |
| 1160 | engagement[field] |
| 1161 | for field in preferred_fields |
| 1162 | if isinstance(engagement.get(field), (int, float)) |
| 1163 | and not isinstance(engagement[field], bool) |
| 1164 | ] |
| 1165 | if preferred_values: |
| 1166 | return max(preferred_values) |
| 1167 | |
| 1168 | values = [ |
| 1169 | value |
| 1170 | for field, value in engagement.items() |
| 1171 | if _is_counter_field(field) |
| 1172 | and isinstance(value, (int, float)) |
| 1173 | and not isinstance(value, bool) |
| 1174 | ] |
| 1175 | return max(values, default=0) |
| 1176 | |
| 1177 | |
| 1178 | def _window_days(report: Report) -> int: |
| 1179 | start = datetime.fromisoformat(report.range_from).date() |
| 1180 | end = datetime.fromisoformat(report.range_to).date() |
| 1181 | return max(0, (end - start).days) |
| 1182 | |
| 1183 | |
| 1184 | def _agent_generated_at(value: str) -> str: |
| 1185 | parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 1186 | if parsed.tzinfo is None: |
| 1187 | return value |
| 1188 | return parsed.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") |
| 1189 | |
| 1190 | |
| 1191 | def to_agent_export( |
| 1192 | report: Report, |
| 1193 | *, |
| 1194 | corpus_in_export: bool | None = None, |
| 1195 | ) -> dict[str, Any]: |
| 1196 | """Serialize a report to the stable, versioned agent JSON contract. |
| 1197 | |
| 1198 | Local corpus evidence is private by default. Callers must opt in explicitly |
| 1199 | either with ``corpus_in_export=True`` or the CLI-populated report artifact. |
| 1200 | """ |
| 1201 | if corpus_in_export is None: |
| 1202 | corpus_in_export = bool(report.artifacts.get("corpus_in_export")) |
| 1203 | if not corpus_in_export: |
| 1204 | report = without_sources(report, {"corpus"}) |
| 1205 | candidates = {candidate.candidate_id: candidate for candidate in report.ranked_candidates} |
| 1206 | cluster_by_candidate: dict[str, int] = {} |
| 1207 | cluster_by_id: dict[str, int] = {} |
| 1208 | exported_clusters: list[dict[str, Any]] = [] |
| 1209 | |
| 1210 | for index, cluster in enumerate(report.clusters): |
| 1211 | cluster_by_id[cluster.cluster_id] = index |
| 1212 | for candidate_id in cluster.candidate_ids: |
| 1213 | cluster_by_candidate.setdefault(candidate_id, index) |
| 1214 | representative = next( |
| 1215 | (candidates[candidate_id] for candidate_id in cluster.representative_ids if candidate_id in candidates), |
| 1216 | None, |
| 1217 | ) |
| 1218 | engagement_total = sum( |
| 1219 | _headline_engagement(candidates[candidate_id]) |
| 1220 | for candidate_id in cluster.candidate_ids |
| 1221 | if candidate_id in candidates |
| 1222 | ) |
| 1223 | exported_clusters.append( |
| 1224 | { |
| 1225 | "title": cluster.title, |
| 1226 | "summary": _agent_summary(representative) if representative else "", |
| 1227 | "sources": list(cluster.sources), |
| 1228 | "engagement_total": ( |
| 1229 | int(engagement_total) |
| 1230 | if isinstance(engagement_total, float) and engagement_total.is_integer() |
| 1231 | else engagement_total |
| 1232 | ), |
| 1233 | } |
| 1234 | ) |
| 1235 | |
| 1236 | results: list[dict[str, Any]] = [] |
| 1237 | for candidate in report.ranked_candidates: |
| 1238 | primary = candidate_primary_item(candidate) |
| 1239 | cluster_index = cluster_by_id.get(candidate.cluster_id or "") |
| 1240 | if cluster_index is None: |
| 1241 | cluster_index = cluster_by_candidate.get(candidate.candidate_id) |
| 1242 | results.append( |
| 1243 | _drop_none( |
| 1244 | { |
| 1245 | "candidate_id": candidate.candidate_id, |
| 1246 | "title": candidate.title, |
| 1247 | "source": candidate.source, |
| 1248 | "url": candidate.url, |
| 1249 | "published_at": primary.published_at if primary else None, |
| 1250 | "summary": _agent_summary(candidate), |
| 1251 | "engagement": _agent_engagement(candidate), |
| 1252 | "relevance_score": round( |
| 1253 | max(0.0, min(1.0, candidate.final_score / 100.0)), |
| 1254 | 4, |
| 1255 | ), |
| 1256 | "cluster": cluster_index, |
| 1257 | } |
| 1258 | ) |
| 1259 | ) |
| 1260 | |
| 1261 | return { |
| 1262 | "schema_version": AGENT_EXPORT_SCHEMA_VERSION, |
| 1263 | "query": report.topic, |
| 1264 | "generated_at": _agent_generated_at(report.generated_at), |
| 1265 | "window_days": _window_days(report), |
| 1266 | "source_status": { |
| 1267 | source: outcome.state |
| 1268 | for source, outcome in sorted(report.source_status.items()) |
| 1269 | }, |
| 1270 | "freshness_verdicts": [ |
| 1271 | _drop_none(asdict(verdict)) for verdict in report.freshness_verdicts |
| 1272 | ], |
| 1273 | "clusters": exported_clusters, |
| 1274 | "results": results, |
| 1275 | "usage": report.artifacts.get("usage"), |
| 1276 | } |
| 1277 | |
| 1278 | |
| 1279 | # Discovery nominations handoff bundle (leg 1 of the three-command |
| 1280 | # host-judged protocol). The bundle serializes the FULL judge pool losslessly |
| 1281 | # so leg 2 can recompute floor/velocity/entity-token disambiguation exactly |
| 1282 | # as an in-memory run would. Bump the version on any incompatible change to |
| 1283 | # the bundle shape; the handoff reader rejects other versions outright. |
| 1284 | DISCOVERY_NOMINATIONS_SCHEMA_VERSION = "1.0" |
| 1285 | DISCOVERY_NOMINATIONS_KIND = "discovery-nominations" |
| 1286 | |
| 1287 | # Pending-report contract (leg 2 -> leg 3 of the host-judged protocol). Leg 2 |
| 1288 | # persists the floored/folded/ranked report plus the per-topic angle inputs; |
| 1289 | # leg 3 rebuilds the report from it and never re-runs anything. Bump the |
| 1290 | # version on any incompatible change; the handoff reader rejects others. |
| 1291 | DISCOVERY_PENDING_SCHEMA_VERSION = "1.0" |
| 1292 | DISCOVERY_PENDING_KIND = "discovery-pending" |
| 1293 | |
| 1294 | |
| 1295 | def discovery_topic_from_dict(payload: dict[str, Any]) -> DiscoveryTopic: |
| 1296 | """Parse one serialized DiscoveryTopic back (to_dict drops None fields, |
| 1297 | so every optional field restores through its dataclass default).""" |
| 1298 | return DiscoveryTopic( |
| 1299 | rank=int(payload["rank"]), |
| 1300 | name=payload["name"], |
| 1301 | why_spiking=payload.get("why_spiking") or "", |
| 1302 | momentum=payload.get("momentum") or "building", |
| 1303 | velocity_score=float(_first_non_none(payload.get("velocity_score"), 0.0)), |
| 1304 | sources=list(payload.get("sources") or []), |
| 1305 | engagement_by_source={ |
| 1306 | str(source): dict(metrics) |
| 1307 | for source, metrics in (payload.get("engagement_by_source") or {}).items() |
| 1308 | if isinstance(metrics, dict) |
| 1309 | }, |
| 1310 | command=payload.get("command") or "", |
| 1311 | evidence_urls=list(payload.get("evidence_urls") or []), |
| 1312 | top_comment=payload.get("top_comment"), |
| 1313 | corroboration_count=int(payload.get("corroboration_count") or 0), |
| 1314 | podcast_angle=payload.get("podcast_angle"), |
| 1315 | x_article_angle=payload.get("x_article_angle"), |
| 1316 | previously_surfaced_count=int(payload.get("previously_surfaced_count") or 0), |
| 1317 | last_surfaced=payload.get("last_surfaced"), |
| 1318 | covered=bool(payload.get("covered")), |
| 1319 | ) |
| 1320 | |
| 1321 | |
| 1322 | def discovery_report_from_dict(payload: dict[str, Any]) -> DiscoveryReport: |
| 1323 | """Rebuild a DiscoveryReport from its ``to_dict`` form (the pending-report |
| 1324 | round trip the finalize leg performs; mirrors ``report_from_dict``).""" |
| 1325 | plan = payload.get("plan") or {} |
| 1326 | return DiscoveryReport( |
| 1327 | domain=payload.get("domain") or "", |
| 1328 | range_from=payload["range_from"], |
| 1329 | range_to=payload["range_to"], |
| 1330 | generated_at=payload["generated_at"], |
| 1331 | plan=DiscoveryPlan( |
| 1332 | domain=plan.get("domain") or "", |
| 1333 | category=plan.get("category"), |
| 1334 | subreddits=list(plan.get("subreddits") or []), |
| 1335 | sources=list(plan.get("sources") or []), |
| 1336 | ), |
| 1337 | topics=[ |
| 1338 | discovery_topic_from_dict(topic) |
| 1339 | for topic in payload.get("topics") or [] |
| 1340 | ], |
| 1341 | source_status=_source_status_from_dict(payload), |
| 1342 | warnings=list(payload.get("warnings") or []), |
| 1343 | outcome=payload.get("outcome") or "ok", |
| 1344 | weak_signal=payload.get("weak_signal"), |
| 1345 | ) |
| 1346 | |
| 1347 | |
| 1348 | def nomination_to_dict(nomination: Any) -> dict[str, Any]: |
| 1349 | """Serialize a nominate-stage Nomination to a plain dict. |
| 1350 | |
| 1351 | Duck-typed on the Nomination fields (name, seed_score, items, summary, |
| 1352 | junk_shape, worthiness) because the dataclass lives in ``pipeline``, |
| 1353 | which this module must not import. Seed items serialize through |
| 1354 | ``to_dict`` so the full evidence set round-trips losslessly. |
| 1355 | """ |
| 1356 | return { |
| 1357 | "name": nomination.name, |
| 1358 | "seed_score": nomination.seed_score, |
| 1359 | "summary": nomination.summary, |
| 1360 | "junk_shape": bool(nomination.junk_shape), |
| 1361 | "worthiness": nomination.worthiness, |
| 1362 | "items": [to_dict(item) for item in nomination.items], |
| 1363 | } |
| 1364 | |
| 1365 | |
| 1366 | def nomination_kwargs_from_dict(payload: dict[str, Any]) -> dict[str, Any]: |
| 1367 | """Parse a serialized nomination back to Nomination constructor kwargs. |
| 1368 | |
| 1369 | Returns kwargs rather than an instance because the Nomination dataclass |
| 1370 | lives in ``pipeline``, which this module must not import; the caller |
| 1371 | (``discovery_handoff``) constructs ``pipeline.Nomination(**kwargs)``. |
| 1372 | """ |
| 1373 | return { |
| 1374 | "name": payload["name"], |
| 1375 | "seed_score": float(_first_non_none(payload.get("seed_score"), 0.0)), |
| 1376 | "items": [source_item_from_dict(item) for item in payload.get("items") or []], |
| 1377 | "summary": payload.get("summary") or "", |
| 1378 | "junk_shape": bool(payload.get("junk_shape")), |
| 1379 | "worthiness": ( |
| 1380 | float(payload["worthiness"]) |
| 1381 | if payload.get("worthiness") is not None |
| 1382 | else None |
| 1383 | ), |
| 1384 | } |
| 1385 | |
| 1386 | |
| 1387 | def to_discovery_export(report: DiscoveryReport) -> dict[str, Any]: |
| 1388 | """Serialize discovery output without changing the normal agent contract.""" |
| 1389 | start = datetime.fromisoformat(report.range_from).date() |
| 1390 | end = datetime.fromisoformat(report.range_to).date() |
| 1391 | return { |
| 1392 | "schema_version": DISCOVERY_EXPORT_SCHEMA_VERSION, |
| 1393 | "kind": "discovery", |
| 1394 | "domain": report.domain, |
| 1395 | "generated_at": _agent_generated_at(report.generated_at), |
| 1396 | "window_days": max(0, (end - start).days), |
| 1397 | "source_status": { |
| 1398 | source: outcome.state |
| 1399 | for source, outcome in sorted(report.source_status.items()) |
| 1400 | }, |
| 1401 | "feeds": { |
| 1402 | "category": report.plan.category, |
| 1403 | "subreddits": list(report.plan.subreddits), |
| 1404 | "sources": list(report.plan.sources), |
| 1405 | }, |
| 1406 | "results": [ |
| 1407 | { |
| 1408 | "rank": topic.rank, |
| 1409 | "topic": topic.name, |
| 1410 | "why_spiking": topic.why_spiking, |
| 1411 | "momentum": topic.momentum, |
| 1412 | "velocity_score": topic.velocity_score, |
| 1413 | "sources": list(topic.sources), |
| 1414 | "engagement": topic.engagement_by_source, |
| 1415 | "command": topic.command, |
| 1416 | "evidence_urls": list(topic.evidence_urls), |
| 1417 | "top_comment": topic.top_comment, |
| 1418 | "corroboration_count": topic.corroboration_count, |
| 1419 | "podcast_angle": topic.podcast_angle, |
| 1420 | "x_article_angle": topic.x_article_angle, |
| 1421 | "previously_surfaced_count": topic.previously_surfaced_count, |
| 1422 | "last_surfaced": topic.last_surfaced, |
| 1423 | "covered": topic.covered, |
| 1424 | } |
| 1425 | for topic in report.topics |
| 1426 | ], |
| 1427 | "warnings": list(report.warnings), |
| 1428 | "outcome": report.outcome, |
| 1429 | "weak_signal": report.weak_signal, |
| 1430 | } |
| 1431 |