返回 last30days-skill
discovery_handoff.py
根目录 / skills / last30days / scripts / lib / discovery_handoff.py
1 """File contracts for the three-command host-judged discovery protocol.
2
3 Leg 1 (``--discover --nominate-only``) writes the nominations bundle: the
4 FULL judge pool, each nomination with its complete seed item set, serialized
5 losslessly so leg 2 can recompute floor/velocity/entity-token disambiguation
6 exactly as an in-memory run would. Leg 2 (``--discover --judgments <file>``)
7 reads host judgments (names/junk/worthiness) bound to the bundle by
8 bundle_id. Leg 3 (``--discover --finalize [--angles <file>]``) applies
9 host-written content angles.
10
11 This module owns the handoff contracts - bundle writer/reader, judgments
12 reader, pending-report reader (the leg-2 output leg 3 finalizes from),
13 angles reader - plus the host-facing digest and the post-judgment
14 name-collision resolver. Readers are strict at the top level (typed
15 ``HandoffContractError``, mapped to exit 2 by the CLI layer) and lenient per
16 row: a malformed or omitted row falls back to the bundle's heuristics rather
17 than failing the run.
18 """
19
20 from __future__ import annotations
21
22 import json
23 import math
24 import secrets
25 from collections import Counter
26 from dataclasses import dataclass, field
27 from pathlib import Path
28 from typing import Any, Callable, Iterator, Sequence
29
30 from . import env, log, pipeline, rerank, schema
31
32
33 # How long a nominations bundle stays valid. Deliberately a module constant
34 # and NOT the LAST30DAYS_REPORT_CACHE_TTL_SECONDS env knob: a user who
35 # lowered the report-cache TTL for drill freshness must not shrink the
36 # window a host has to author judgments.
37 DISCOVERY_HANDOFF_TTL_SECONDS = 3600.0
38
39 NOMINATIONS_BUNDLE_FILENAME = "discover-nominations.json"
40 PENDING_REPORT_FILENAME = "discover-pending.json"
41
42 _VALID_TIERS = ("deep", "shallow")
43 MAX_LOOKBACK_DAYS = 3650
44 _MAX_LOOKBACK_DAYS = MAX_LOOKBACK_DAYS
45
46 _RESWEEP_REMEDY = "Run a fresh `--discover --nominate-only` re-sweep."
47
48 # Leg-3 remedy: the pending report is leg-2 output, so the first fix is to
49 # re-run the resume leg; only when the bundle itself has also gone stale does
50 # the whole protocol restart.
51 _RESUME_REMEDY = (
52 "Re-run the resume leg (`--discover --judgments <file>`), or the full "
53 "protocol from `--discover --nominate-only` if the bundle is stale too."
54 )
55
56 # Defensive caps on host-supplied text, ported from the retired engine-judge
57 # pass: names become search queries and the /last30days handoff, angles
58 # render verbatim on trend cards, so a runaway (or adversarial) value never
59 # yields an unbounded string.
60 _NAME_MAX_CHARS = 96
61 _ANGLE_MAX_CHARS = 200
62
63 # Unified trailing-punctuation charset for word-boundary truncation: names
64 # and angle sentences share it so the strip sets cannot drift.
65 _TRUNCATE_STRIP_CHARS = " \"'`.,;:!?-"
66
67 # Digest evidence caps: the surface the engine judge used to see per
68 # nomination (leader title, leader snippet, strongest community comment).
69 _DIGEST_TITLE_MAX_CHARS = 220
70 _DIGEST_SNIPPET_MAX_CHARS = 420
71 _DIGEST_COMMENT_MAX_CHARS = 340
72
73
74 class HandoffContractError(Exception):
75 """A handoff file failed its contract: unreadable, invalid JSON, wrong
76 shape or schema version, stale, or not bound to the current bundle.
77 The CLI layer maps this to exit code 2."""
78
79 def __init__(self, message: str) -> None:
80 super().__init__(message)
81 self.message = message
82
83
84 @dataclass(frozen=True)
85 class PoolEntry:
86 """One judge-pool nomination as handed to the bundle writer (leg 1).
87
88 ``heuristic_name`` and ``heuristic_junk`` are the deterministic
89 topic_shape fallbacks, kept alongside the nomination so leg 2 can fill
90 any row the host omitted without re-deriving them.
91 """
92
93 nomination: pipeline.Nomination
94 cluster_id: str
95 heuristic_name: str
96 heuristic_junk: bool
97
98
99 @dataclass(frozen=True)
100 class BundleNomination:
101 """One nomination read back from a bundle, with its stable id."""
102
103 nomination_id: str
104 nomination: pipeline.Nomination
105 cluster_id: str
106 heuristic_name: str
107 heuristic_junk: bool
108 sources: list[str]
109 engagement_by_source: dict[str, dict[str, float | int]] = field(
110 default_factory=dict
111 )
112
113
114 @dataclass(frozen=True)
115 class NominationsBundle:
116 """A parsed leg-1 nominations bundle (also returned by the writer).
117
118 ``source_status`` is the leg-1 sweep's finalized per-source outcome map:
119 legs 2 and 3 restore it so degraded sweep coverage survives the protocol
120 instead of silently reading as clean. ``mock`` is the writing run's
121 provenance - mock-born state must never be finalized by a real run (and
122 vice versa); files written before either field existed read as an empty
123 map and a real run. ``warnings`` retains informational sweep coverage
124 separately from source outcomes; older files read with no warnings."""
125
126 schema_version: str
127 bundle_id: str
128 generated_at: str
129 from_date: str
130 to_date: str
131 domain: str
132 tier: str
133 enrichment_source_boundary: list[str] | None
134 requested_sources: list[str] | None
135 lookback_days: int
136 nominations: list[BundleNomination]
137 source_status: dict[str, schema.SourceOutcome] = field(default_factory=dict)
138 mock: bool = False
139 path: Path | None = None
140 warnings: list[str] = field(default_factory=list)
141
142
143 @dataclass(frozen=True)
144 class HostJudgment:
145 """One host verdict row. ``None`` on any field means the host left it
146 absent for that row and the caller falls back to the bundle's heuristic
147 value (name/junk) or to no worthiness signal."""
148
149 name: str | None
150 junk: bool | None
151 worthiness: int | None
152
153
154 # The per-row-absent marker: what ``judgment_for`` returns for a nomination
155 # the host omitted entirely. Every field falls back to the bundle heuristics.
156 ROW_ABSENT = HostJudgment(name=None, junk=None, worthiness=None)
157
158
159 @dataclass(frozen=True)
160 class HostAngles:
161 """One host-written angle row; either field may be absent."""
162
163 podcast: str | None
164 x_article: str | None
165
166
167 @dataclass(frozen=True)
168 class PendingReport:
169 """A parsed leg-2 pending report: the floored/folded/ranked discovery
170 report (as its raw ``schema.to_dict`` payload - leg 3 rebuilds it via
171 ``schema.discovery_report_from_dict``) plus the angle inputs keyed by
172 surviving nomination id. ``run_ref`` is the leg-2 run identity the
173 finalize leg replays into the topic queue so retries stay idempotent."""
174
175 schema_version: str
176 bundle_id: str
177 generated_at: str
178 run_ref: str
179 report: dict[str, Any]
180 angle_inputs: dict[str, dict[str, str]]
181 # Leg-2 provenance: True when a --mock resume wrote this file. Files
182 # written before the flag existed read as real (False).
183 mock: bool = False
184 path: Path | None = None
185
186
187 def _warn(message: str) -> None:
188 log.source_log("Discover", message, tty_only=False)
189
190
191 def handoff_state_dir(
192 save_dir: str | Path | None,
193 config_dir: Path | None,
194 ) -> Path | None:
195 """Resolve the handoff state directory: ``save_dir`` when provided, else
196 the config dir (mirrors the report-cache convention in last30days.py).
197 Both are accepted as arguments so this module never imports the CLI
198 layer above it. Returns None when neither location is available."""
199 if save_dir:
200 return Path(save_dir).expanduser().resolve()
201 if config_dir is not None:
202 return Path(config_dir)
203 return None
204
205
206 def nominations_bundle_path(state_dir: str | Path) -> Path:
207 """The nominations bundle file inside a handoff state directory."""
208 return Path(state_dir) / NOMINATIONS_BUNDLE_FILENAME
209
210
211 def pending_report_path(state_dir: str | Path) -> Path:
212 """The leg-2 pending-report file inside a handoff state directory."""
213 return Path(state_dir) / PENDING_REPORT_FILENAME
214
215
216 def _search_paths(
217 save_dir: str | Path | None,
218 config_dir: Path | None,
219 path_fn: Callable[[Path], Path],
220 ) -> list[Path]:
221 """Candidate handoff-file locations: ONLY the save dir when one was
222 supplied, else the config dir. An explicit save dir is the protocol's
223 single handoff store (mirroring ``_scoped_store_db`` and SKILL.md's "a
224 different or missing save dir on a later leg means the leg cannot find
225 them" contract), so a handoff file in the config dir must never silently
226 satisfy a save-dir run. ``path_fn`` picks which handoff file (bundle vs
227 pending)."""
228 if save_dir:
229 return [path_fn(Path(save_dir).expanduser().resolve())]
230 if config_dir is not None:
231 return [path_fn(Path(config_dir))]
232 return []
233
234
235 def _searched_lines(searched: list[Path]) -> str:
236 if not searched:
237 return " (no --save-dir and no config directory available)"
238 return "\n".join(f" - {path}" for path in searched)
239
240
241 def validate_lookback_days(
242 value: object,
243 *,
244 field_name: str = "lookback_days",
245 source_desc: str | None = None,
246 remedy: str = "",
247 ) -> int:
248 """Validate a discovery handoff lookback window (integer in 1..MAX_LOOKBACK_DAYS).
249
250 Shared across leg-1 pre-sweep CLI entry, bundle writing, and leg-2 bundle
251 reading so leg 1 can never sweep or write a bundle that leg 2 rejects.
252 """
253 if (
254 isinstance(value, bool)
255 or not isinstance(value, int)
256 or value < 1
257 or value > MAX_LOOKBACK_DAYS
258 ):
259 prefix = f"{source_desc} has invalid {field_name}" if source_desc else f"Invalid {field_name}"
260 suffix = f" {remedy}" if remedy else ""
261 raise HandoffContractError(
262 f"{prefix} (expected integer in 1..{MAX_LOOKBACK_DAYS}).{suffix}"
263 )
264 return value
265
266
267 def write_nominations_bundle(
268 entries: Sequence[PoolEntry],
269 *,
270 domain: str,
271 tier: str,
272 from_date: str,
273 to_date: str,
274 lookback_days: int,
275 enrichment_source_boundary: list[str] | None,
276 requested_sources: list[str] | None,
277 source_status: dict[str, schema.SourceOutcome] | None = None,
278 warnings: Sequence[str] | None = None,
279 mock: bool = False,
280 save_dir: str | Path | None = None,
281 config_dir: Path | None = None,
282 ) -> NominationsBundle:
283 """Write the leg-1 nominations bundle and return its parsed form.
284
285 Nomination ids are assigned ``n1, n2, ...`` in pool order. The leg-1
286 invocation context (enrichment source boundary, requested discovery
287 sources, lookback days) rides along so leg 2 resumes with identical
288 settings. ``None`` boundaries are preserved as null - "no boundary" and
289 "empty boundary" are different contracts. ``source_status`` is the
290 sweep's finalized per-source outcome map (serialized via the same
291 ``schema.to_dict`` round trip every report uses) so degraded coverage
292 survives into legs 2-3; ``warnings`` preserves informational coverage
293 receipts, and ``mock`` stamps the writing run's provenance.
294 """
295 if tier not in _VALID_TIERS:
296 raise ValueError(f"tier must be one of {_VALID_TIERS}, got {tier!r}")
297 lookback_days = validate_lookback_days(lookback_days)
298 state_dir = handoff_state_dir(save_dir, config_dir)
299 if state_dir is None:
300 raise HandoffContractError(
301 "No handoff location available to write the nominations bundle: "
302 "pass --save-dir or configure ~/.config/last30days/."
303 )
304 bundle_id = secrets.token_hex(8)
305 generated_at = schema._utc_now()
306
307 rows: list[dict[str, Any]] = []
308 nominations: list[BundleNomination] = []
309 for index, entry in enumerate(entries, start=1):
310 nomination_id = f"n{index}"
311 sources = sorted({item.source for item in entry.nomination.items})
312 engagement = pipeline._discovery_engagement(entry.nomination.items)
313 rows.append({
314 "id": nomination_id,
315 "cluster_id": entry.cluster_id,
316 "heuristic_name": entry.heuristic_name,
317 "heuristic_junk": bool(entry.heuristic_junk),
318 "sources": sources,
319 "engagement_by_source": engagement,
320 "nomination": schema.nomination_to_dict(entry.nomination),
321 })
322 nominations.append(BundleNomination(
323 nomination_id=nomination_id,
324 nomination=entry.nomination,
325 cluster_id=entry.cluster_id,
326 heuristic_name=entry.heuristic_name,
327 heuristic_junk=bool(entry.heuristic_junk),
328 sources=sources,
329 engagement_by_source=engagement,
330 ))
331
332 payload = {
333 "schema_version": schema.DISCOVERY_NOMINATIONS_SCHEMA_VERSION,
334 "kind": schema.DISCOVERY_NOMINATIONS_KIND,
335 "bundle_id": bundle_id,
336 "generated_at": generated_at,
337 "from_date": from_date,
338 "to_date": to_date,
339 "domain": domain,
340 "tier": tier,
341 "mock": bool(mock),
342 "warnings": list(warnings or []),
343 "source_status": {
344 source: schema.to_dict(outcome)
345 for source, outcome in (source_status or {}).items()
346 },
347 "context": {
348 "enrichment_source_boundary": (
349 list(enrichment_source_boundary)
350 if enrichment_source_boundary is not None
351 else None
352 ),
353 "requested_sources": (
354 list(requested_sources) if requested_sources is not None else None
355 ),
356 "lookback_days": int(lookback_days),
357 },
358 "nominations": rows,
359 }
360 path = nominations_bundle_path(state_dir)
361 try:
362 state_dir.mkdir(parents=True, exist_ok=True)
363 path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
364 except OSError as exc:
365 # A locked/read-only/full disk is the protocol's clean exit-2 path,
366 # never a traceback.
367 raise HandoffContractError(
368 f"Could not write nominations bundle {path}: {exc}"
369 ) from exc
370 return NominationsBundle(
371 schema_version=schema.DISCOVERY_NOMINATIONS_SCHEMA_VERSION,
372 bundle_id=bundle_id,
373 generated_at=generated_at,
374 from_date=from_date,
375 to_date=to_date,
376 domain=domain,
377 tier=tier,
378 enrichment_source_boundary=(
379 list(enrichment_source_boundary)
380 if enrichment_source_boundary is not None
381 else None
382 ),
383 requested_sources=(
384 list(requested_sources) if requested_sources is not None else None
385 ),
386 lookback_days=int(lookback_days),
387 nominations=nominations,
388 source_status=dict(source_status or {}),
389 mock=bool(mock),
390 path=path,
391 warnings=list(warnings or []),
392 )
393
394
395 def read_nominations_bundle(
396 *,
397 save_dir: str | Path | None = None,
398 config_dir: Path | None = None,
399 ) -> NominationsBundle:
400 """Locate and parse the nominations bundle for legs 2 and 3.
401
402 The bundle lives in the save dir when one was supplied, else the config
403 dir - never both (no cross-store fallback). Raises HandoffContractError
404 (naming the searched location and the re-sweep remedy) when no bundle
405 exists, and for any top-level contract violation in the file found.
406 """
407 searched = _search_paths(save_dir, config_dir, nominations_bundle_path)
408 path = next((candidate for candidate in searched if candidate.exists()), None)
409 if path is None:
410 raise HandoffContractError(
411 "No discovery nominations bundle found. Searched:\n"
412 f"{_searched_lines(searched)}\n{_RESWEEP_REMEDY}"
413 )
414 return _parse_bundle_file(path)
415
416
417 def _parse_handoff_envelope(
418 path: Path,
419 *,
420 label: str,
421 kind: str,
422 schema_version: str,
423 remedy: str,
424 missing_id_context: str,
425 stale_context: str,
426 ) -> tuple[dict[str, Any], str, Any]:
427 """Shared strict top-level validation for the two engine-written handoff
428 files (nominations bundle, pending report): readable, valid JSON object,
429 right kind and schema version, bundle_id present, within TTL. Returns
430 (payload, bundle_id, generated_at)."""
431 try:
432 raw = path.read_text(encoding="utf-8")
433 except (OSError, UnicodeDecodeError) as exc:
434 raise HandoffContractError(
435 f"Could not read {label.lower()} {path}: {exc}"
436 ) from exc
437 try:
438 payload = json.loads(raw)
439 except (json.JSONDecodeError, ValueError) as exc:
440 raise HandoffContractError(
441 f"{label} {path} is not valid JSON: {exc}"
442 ) from exc
443 if not isinstance(payload, dict):
444 raise HandoffContractError(
445 f"{label} {path} must be a top-level JSON object, "
446 f"got {type(payload).__name__}."
447 )
448 version = payload.get("schema_version")
449 if version != schema_version:
450 raise HandoffContractError(
451 f"{label} {path} has schema version {version!r}; this "
452 f"build reads {schema_version!r}. {remedy}"
453 )
454 file_kind = payload.get("kind")
455 if file_kind != kind:
456 raise HandoffContractError(
457 f"{label} {path} has kind {file_kind!r}; expected "
458 f"{kind!r}. {remedy}"
459 )
460 raw_bundle_id = payload.get("bundle_id")
461 bundle_id = raw_bundle_id.strip() if isinstance(raw_bundle_id, str) else ""
462 if not bundle_id:
463 raise HandoffContractError(
464 f"{label} {path} is missing its bundle_id; "
465 f"{missing_id_context}. {remedy}"
466 )
467 generated_at = payload.get("generated_at")
468 if not env.is_timestamp_fresh(generated_at, DISCOVERY_HANDOFF_TTL_SECONDS):
469 raise HandoffContractError(
470 f"{label} {path} is stale (generated_at="
471 f"{generated_at!r}, TTL {int(DISCOVERY_HANDOFF_TTL_SECONDS)}s): "
472 f"{stale_context}. {remedy}"
473 )
474 return payload, bundle_id, generated_at
475
476
477 def _parse_mock_flag(payload: dict[str, Any], path: Path, *, label: str, remedy: str) -> bool:
478 raw_mock = payload.get("mock")
479 if raw_mock is None:
480 return False
481 if not isinstance(raw_mock, bool):
482 raise HandoffContractError(
483 f"{label} {path} has non-boolean \"mock\" value "
484 f"{raw_mock!r}. {remedy}"
485 )
486 return raw_mock
487
488
489 def _validate_nomination(nomination: pipeline.Nomination) -> None:
490 """Validate deserialized nomination and seed-item field types so one
491 corrupt row is skipped cleanly instead of crashing resume/digest/sorting."""
492 if not isinstance(nomination.name, str):
493 raise TypeError("nomination.name must be a string")
494 if not isinstance(nomination.summary, str):
495 raise TypeError("nomination.summary must be a string")
496 if not math.isfinite(nomination.seed_score):
497 raise ValueError("nomination.seed_score must be finite")
498 if nomination.worthiness is not None and not math.isfinite(nomination.worthiness):
499 raise ValueError("nomination.worthiness must be finite")
500 for item in nomination.items:
501 if not isinstance(item.item_id, str):
502 raise TypeError("item.item_id must be a string")
503 if not isinstance(item.source, str) or not item.source.strip():
504 raise TypeError("item.source must be a non-empty string")
505 for attr in ("title", "body", "url", "snippet", "why_relevant", "date_confidence"):
506 if not isinstance(getattr(item, attr), str):
507 raise TypeError(f"item.{attr} must be a string")
508 for attr in ("author", "container", "published_at"):
509 val = getattr(item, attr)
510 if val is not None and not isinstance(val, str):
511 raise TypeError(f"item.{attr} must be a string or null")
512 if not math.isfinite(item.relevance_hint):
513 raise ValueError("item.relevance_hint must be finite")
514 for key, val in item.engagement.items():
515 if not isinstance(key, str):
516 raise TypeError("item.engagement keys must be strings")
517 if isinstance(val, (int, float)) and not isinstance(val, bool):
518 if not math.isfinite(float(val)):
519 raise ValueError(f"item.engagement[{key!r}] must be finite")
520 top_comments = item.metadata.get("top_comments")
521 if top_comments is not None:
522 if not isinstance(top_comments, list):
523 raise TypeError("item.metadata.top_comments must be a list")
524 for comment in top_comments:
525 if not isinstance(comment, dict):
526 continue
527 for text_key in ("excerpt", "text", "body"):
528 text_val = comment.get(text_key)
529 if text_val is not None and not isinstance(text_val, str):
530 raise TypeError(f"comment.{text_key} must be a string or null")
531
532
533 def _parse_bundle_file(path: Path) -> NominationsBundle:
534 payload, bundle_id, generated_at = _parse_handoff_envelope(
535 path,
536 label="Nominations bundle",
537 kind=schema.DISCOVERY_NOMINATIONS_KIND,
538 schema_version=schema.DISCOVERY_NOMINATIONS_SCHEMA_VERSION,
539 remedy=_RESWEEP_REMEDY,
540 missing_id_context="judgments cannot bind to it",
541 stale_context="the momentum window it captured has moved on",
542 )
543 version = payload.get("schema_version")
544 mock_flag = _parse_mock_flag(
545 payload, path, label="Nominations bundle", remedy=_RESWEEP_REMEDY
546 )
547
548 raw_context = payload.get("context")
549 if raw_context is None:
550 context: dict[str, Any] = {}
551 elif isinstance(raw_context, dict):
552 context = raw_context
553 else:
554 raise HandoffContractError(
555 f"Nominations bundle {path} has malformed \"context\" "
556 f"(expected object, got {type(raw_context).__name__}). {_RESWEEP_REMEDY}"
557 )
558
559 boundary = context.get("enrichment_source_boundary")
560 if boundary is not None and (
561 not isinstance(boundary, list) or any(not isinstance(s, str) for s in boundary)
562 ):
563 raise HandoffContractError(
564 f"Nominations bundle {path} has malformed "
565 f"context.enrichment_source_boundary. {_RESWEEP_REMEDY}"
566 )
567 requested = context.get("requested_sources")
568 if requested is not None and (
569 not isinstance(requested, list) or any(not isinstance(s, str) for s in requested)
570 ):
571 raise HandoffContractError(
572 f"Nominations bundle {path} has malformed "
573 f"context.requested_sources. {_RESWEEP_REMEDY}"
574 )
575
576 raw_lookback = context.get("lookback_days")
577 if raw_lookback is None:
578 lookback_days = 30
579 else:
580 lookback_days = validate_lookback_days(
581 raw_lookback,
582 field_name="context.lookback_days",
583 source_desc=f"Nominations bundle {path}",
584 remedy=_RESWEEP_REMEDY,
585 )
586
587 rows_raw = payload.get("nominations")
588 if not isinstance(rows_raw, list):
589 raise HandoffContractError(
590 f"Nominations bundle {path} must carry a top-level "
591 f"\"nominations\" list, got {type(rows_raw).__name__}. "
592 f"{_RESWEEP_REMEDY}"
593 )
594
595 nominations: list[BundleNomination] = []
596 seen_ids: set[str] = set()
597 for position, row in enumerate(rows_raw, start=1):
598 # Lenient per row: the bundle is engine-written, but one corrupted
599 # row must not discard the rest of the pool.
600 if not isinstance(row, dict):
601 _warn(
602 f"skipping malformed nomination row {position} in "
603 f"{path.name} (not an object)"
604 )
605 continue
606 nom_raw = row.get("nomination")
607 if not isinstance(nom_raw, dict):
608 _warn(
609 f"skipping unparseable nomination row {position} in "
610 f"{path.name}: nomination field is not an object"
611 )
612 continue
613 items_raw = nom_raw.get("items")
614 if items_raw is not None and not isinstance(items_raw, list):
615 _warn(
616 f"skipping unparseable nomination row {position} in "
617 f"{path.name}: nomination.items is not a list"
618 )
619 continue
620 try:
621 for item_raw in items_raw or ():
622 if not isinstance(item_raw, dict):
623 raise TypeError("nomination item must be an object")
624 if item_raw.get("engagement") is not None and not isinstance(item_raw.get("engagement"), dict):
625 raise TypeError("nomination item.engagement must be an object")
626 if item_raw.get("metadata") is not None and not isinstance(item_raw.get("metadata"), dict):
627 raise TypeError("nomination item.metadata must be an object")
628 nomination = pipeline.Nomination(
629 **schema.nomination_kwargs_from_dict(nom_raw)
630 )
631 _validate_nomination(nomination)
632 except (AttributeError, KeyError, TypeError, ValueError, OverflowError) as exc:
633 _warn(
634 f"skipping unparseable nomination row {position} in "
635 f"{path.name}: {type(exc).__name__}: {exc}"
636 )
637 continue
638 raw_id = row.get("id")
639 if raw_id is None:
640 nomination_id = f"n{position}"
641 elif isinstance(raw_id, str) and raw_id.strip():
642 nomination_id = raw_id.strip()
643 else:
644 nomination_id = f"n{position}"
645 if nomination_id in seen_ids:
646 raise HandoffContractError(
647 f"Nominations bundle {path} contains duplicate nomination id "
648 f"{nomination_id!r}. {_RESWEEP_REMEDY}"
649 )
650 seen_ids.add(nomination_id)
651 engagement_raw = row.get("engagement_by_source")
652 engagement = {
653 str(source): dict(metrics)
654 for source, metrics in (
655 engagement_raw.items() if isinstance(engagement_raw, dict) else ()
656 )
657 if isinstance(metrics, dict)
658 }
659 sources_raw = row.get("sources")
660 if sources_raw is None:
661 sources: list[str] = []
662 elif isinstance(sources_raw, list):
663 sources = [s for s in sources_raw if isinstance(s, str)]
664 if len(sources) != len(sources_raw):
665 _warn(
666 f"ignoring non-string entries in sources list on nomination "
667 f"row {position} in {path.name}"
668 )
669 else:
670 _warn(
671 f"ignoring malformed sources list on nomination row {position} "
672 f"in {path.name}"
673 )
674 sources = []
675 nominations.append(BundleNomination(
676 nomination_id=nomination_id,
677 nomination=nomination,
678 cluster_id=str(row.get("cluster_id") or ""),
679 heuristic_name=str(row.get("heuristic_name") or ""),
680 heuristic_junk=bool(row.get("heuristic_junk")),
681 sources=sources,
682 engagement_by_source=engagement,
683 ))
684
685 if not nominations:
686 # Leg 1 never writes an empty bundle (a zero-nomination sweep
687 # short-circuits with no bundle file), so an empty or all-invalid
688 # nominations array is corrupt state: fail closed, never hand the
689 # resume leg a silently empty pool.
690 raise HandoffContractError(
691 f"Nominations bundle {path} contains no readable nominations "
692 f"(leg 1 never writes an empty pool). {_RESWEEP_REMEDY}"
693 )
694
695 # Sweep status is advisory coverage context: restore it through the same
696 # deserializer every report uses, but degrade a malformed map to empty
697 # rather than discarding an otherwise-valid pool.
698 try:
699 source_status = schema._source_status_from_dict(payload)
700 except (AttributeError, KeyError, TypeError, ValueError):
701 _warn(f"ignoring malformed source_status map in {path.name}")
702 source_status = {}
703
704 warnings = payload.get("warnings", [])
705 if not isinstance(warnings, list) or any(not isinstance(warning, str) for warning in warnings):
706 _warn(f"ignoring malformed warnings list in {path.name}")
707 warnings = []
708
709 return NominationsBundle(
710 schema_version=str(version),
711 bundle_id=bundle_id,
712 generated_at=str(generated_at or ""),
713 from_date=str(payload.get("from_date") or ""),
714 to_date=str(payload.get("to_date") or ""),
715 domain=str(payload.get("domain") or ""),
716 tier=str(payload.get("tier") or "deep"),
717 enrichment_source_boundary=(
718 list(boundary) if boundary is not None else None
719 ),
720 requested_sources=(
721 list(requested) if requested is not None else None
722 ),
723 lookback_days=lookback_days,
724 nominations=nominations,
725 source_status=source_status,
726 mock=mock_flag,
727 path=path,
728 warnings=warnings,
729 )
730
731
732 def read_pending_report(
733 *,
734 save_dir: str | Path | None = None,
735 config_dir: Path | None = None,
736 ) -> PendingReport:
737 """Locate and parse the leg-2 pending report for the finalize leg.
738
739 Same strictness family as the bundle reader: missing file (the searched
740 location named - save dir when supplied, else config dir, never a
741 cross-store fallback), unreadable, invalid JSON, wrong kind or schema version,
742 missing bundle_id, or stale TTL all raise HandoffContractError (mapped to
743 exit 2 by the CLI layer). Staleness is measured from the PENDING report's
744 own generated_at - the leg-2 write started a fresh authoring window - and
745 the remedy is the resume leg, not a full re-sweep.
746 """
747 searched = _search_paths(save_dir, config_dir, pending_report_path)
748 path = next((candidate for candidate in searched if candidate.exists()), None)
749 if path is None:
750 raise HandoffContractError(
751 "No pending discovery report found. Searched:\n"
752 f"{_searched_lines(searched)}\n{_RESUME_REMEDY}"
753 )
754 return _parse_pending_file(path)
755
756
757 def _parse_pending_file(path: Path) -> PendingReport:
758 payload, bundle_id, generated_at = _parse_handoff_envelope(
759 path,
760 label="Pending discovery report",
761 kind=schema.DISCOVERY_PENDING_KIND,
762 schema_version=schema.DISCOVERY_PENDING_SCHEMA_VERSION,
763 remedy=_RESUME_REMEDY,
764 missing_id_context="angles cannot bind to it",
765 stale_context="the judged window it captured has moved on",
766 )
767 version = payload.get("schema_version")
768 report = payload.get("report")
769 if not isinstance(report, dict):
770 raise HandoffContractError(
771 f"Pending discovery report {path} must carry a top-level "
772 f"\"report\" object. {_RESUME_REMEDY}"
773 )
774 # Lenient per row (engine-written, but one corrupt row must not discard
775 # the rest): keep only well-shaped angle-input entries.
776 angle_inputs_raw = payload.get("angle_inputs")
777 angle_inputs = {
778 str(nomination_id): {
779 str(key): str(value) for key, value in info.items()
780 }
781 for nomination_id, info in (
782 angle_inputs_raw.items() if isinstance(angle_inputs_raw, dict) else ()
783 )
784 if isinstance(info, dict)
785 }
786 mock_flag = _parse_mock_flag(
787 payload, path, label="Pending discovery report", remedy=_RESUME_REMEDY
788 )
789 return PendingReport(
790 schema_version=str(version),
791 bundle_id=bundle_id,
792 generated_at=str(generated_at or ""),
793 run_ref=str(payload.get("run_ref") or ""),
794 report=report,
795 angle_inputs=angle_inputs,
796 mock=mock_flag,
797 path=path,
798 )
799
800
801 def _load_host_file(path: str | Path, label: str) -> dict[str, Any]:
802 """Load a host-authored handoff file with strict top-level checks."""
803 file_path = Path(path).expanduser()
804 try:
805 raw = file_path.read_text(encoding="utf-8")
806 except (OSError, UnicodeDecodeError) as exc:
807 raise HandoffContractError(
808 f"Could not read {label} file {file_path}: {exc}"
809 ) from exc
810 try:
811 payload = json.loads(raw)
812 except (json.JSONDecodeError, ValueError) as exc:
813 raise HandoffContractError(
814 f"{label.capitalize()} file {file_path} is not valid JSON: {exc}"
815 ) from exc
816 if not isinstance(payload, dict):
817 raise HandoffContractError(
818 f"{label.capitalize()} file {file_path} must be a top-level JSON "
819 f"object, got {type(payload).__name__}."
820 )
821 return payload
822
823
824 def _require_bundle_binding(
825 payload: dict[str, Any],
826 bundle: NominationsBundle | PendingReport,
827 *,
828 label: str,
829 save_dir: str | Path | None,
830 config_dir: Path | None,
831 ) -> None:
832 """Enforce bundle-id binding between a host file and the current bundle
833 (or, on the finalize leg, the pending report that inherited its id).
834 The mismatch message names the file actually validated against - the
835 pending report on the finalize leg - so a host's retry is not misdirected
836 at the nominations bundle. A mismatch means the host echoed the wrong id
837 into an otherwise-current file, so the remedy is the cheap one - correct
838 the bundle_id field and re-run this same leg - never the expensive
839 re-sweep/resume remedies (those belong to missing/stale state)."""
840 file_bundle_id = str(payload.get("bundle_id") or "")
841 if file_bundle_id == bundle.bundle_id:
842 return
843 if isinstance(bundle, PendingReport):
844 searched = _search_paths(save_dir, config_dir, pending_report_path)
845 noun = "current pending discovery report"
846 location_label = "Pending-report locations searched"
847 else:
848 searched = _search_paths(save_dir, config_dir, nominations_bundle_path)
849 noun = "current nominations bundle"
850 location_label = "Bundle locations searched"
851 if not searched and bundle.path is not None:
852 searched = [bundle.path]
853 raise HandoffContractError(
854 f"The {label} file is bound to bundle_id {file_bundle_id!r} but the "
855 f"{noun} is {bundle.bundle_id!r}. {location_label}:\n"
856 f"{_searched_lines(searched)}\n"
857 f"Correct the bundle_id field in your {label} file to "
858 f"{bundle.bundle_id!r} and re-run this same leg."
859 )
860
861
862 def _truncate_at_word(text: str, max_chars: int) -> str:
863 """Cap ``text`` at ``max_chars``, cutting back to a word boundary and
864 stripping trailing punctuation. Text within the cap passes through
865 untouched."""
866 if len(text) <= max_chars:
867 return text
868 return text[:max_chars].rsplit(" ", 1)[0].rstrip(_TRUNCATE_STRIP_CHARS)
869
870
871 def _sanitized_name(raw: object) -> str | None:
872 """One whitespace-collapsed, punctuation-stripped, length-capped topic
873 name, or None for anything unusable (non-strings, and names that
874 sanitize to empty - e.g. emoji-only - count as per-row-absent)."""
875 if not isinstance(raw, str):
876 return None
877 name = " ".join(raw.split()).strip(_TRUNCATE_STRIP_CHARS)
878 name = _truncate_at_word(name, _NAME_MAX_CHARS)
879 if not any(char.isalnum() for char in name):
880 return None
881 return name
882
883
884 def _sanitized_angle(raw: object) -> str | None:
885 """One whitespace-collapsed, length-capped angle sentence, or None for
886 anything unusable. Non-strings are rejected outright, never coerced."""
887 if not isinstance(raw, str):
888 return None
889 text = _truncate_at_word(" ".join(raw.split()), _ANGLE_MAX_CHARS)
890 return text or None
891
892
893 def _known_rows(
894 rows: list[Any],
895 known: set[str],
896 *,
897 row_label: str,
898 unknown_label: str,
899 ) -> Iterator[tuple[str, dict[str, Any]]]:
900 """Shared lenient per-row gate for host-authored files: skip non-object
901 rows, rows with no nomination id, and rows for unknown ids - warning on
902 each - and yield (row_id, row) for the rest."""
903 for row in rows:
904 if not isinstance(row, dict):
905 _warn(f"skipping malformed {row_label} row (not an object)")
906 continue
907 row_id = str(row.get("id") or "").strip()
908 if not row_id:
909 _warn(f"skipping {row_label} row with no nomination id")
910 continue
911 if row_id not in known:
912 _warn(f"ignoring {unknown_label} for unknown nomination id {row_id!r}")
913 continue
914 yield row_id, row
915
916
917 def _clamped_worthiness(raw: object) -> int | None:
918 """Worthiness clamped to 0-100 integers; non-numeric or non-finite values are absent."""
919 if isinstance(raw, bool):
920 return None
921 try:
922 value = float(raw) # type: ignore[arg-type]
923 except (TypeError, ValueError, OverflowError):
924 return None
925 if not math.isfinite(value):
926 return None
927 return max(0, min(100, round(value)))
928
929
930 def read_judgments(
931 path: str | Path,
932 bundle: NominationsBundle,
933 *,
934 save_dir: str | Path | None = None,
935 config_dir: Path | None = None,
936 ) -> dict[str, HostJudgment]:
937 """Read the host judgments file for leg 2, keyed by nomination id.
938
939 Strict at the top level (readable, valid JSON object, ``judgments`` list,
940 bundle_id bound to ``bundle``), lenient per row: an unknown id is warned
941 and ignored, a missing/unusable name or junk field is per-row-absent, and
942 worthiness is clamped to 0-100 integers. Nominations with no row at all
943 are simply missing from the mapping - use ``judgment_for`` to get the
944 ROW_ABSENT marker for them.
945 """
946 payload = _load_host_file(path, "judgments")
947 _require_bundle_binding(
948 payload, bundle, label="judgments", save_dir=save_dir, config_dir=config_dir,
949 )
950 rows = payload.get("judgments")
951 if not isinstance(rows, list):
952 raise HandoffContractError(
953 f"Judgments file {path} must carry a top-level \"judgments\" list."
954 )
955 known = {entry.nomination_id for entry in bundle.nominations}
956 judgments: dict[str, HostJudgment] = {}
957 for row_id, row in _known_rows(
958 rows, known, row_label="judgments", unknown_label="judgment"
959 ):
960 # Only a real JSON boolean is a junk verdict: null, "false", 0, or
961 # any other non-bool value is per-row-absent (bundle heuristic),
962 # never coerced - bool("false") is True.
963 raw_junk = row.get("junk")
964 judgments[row_id] = HostJudgment(
965 name=_sanitized_name(row.get("name")),
966 junk=raw_junk if isinstance(raw_junk, bool) else None,
967 worthiness=_clamped_worthiness(row.get("worthiness")),
968 )
969 return judgments
970
971
972 def judgment_for(
973 judgments: dict[str, HostJudgment],
974 nomination_id: str,
975 ) -> HostJudgment:
976 """The host's verdict for one nomination, or ROW_ABSENT when the host
977 omitted the row (caller falls back to the bundle's heuristic name/junk)."""
978 return judgments.get(nomination_id, ROW_ABSENT)
979
980
981 def read_angles(
982 path: str | Path | None,
983 bundle: NominationsBundle | PendingReport,
984 *,
985 save_dir: str | Path | None = None,
986 config_dir: Path | None = None,
987 ) -> dict[str, HostAngles]:
988 """Read the host angles file for leg 3, keyed by nomination id.
989
990 ``bundle`` is the binding target: the finalize leg passes the pending
991 report (the bundle_id echo validates against it, and the known ids are
992 its surviving ``angle_inputs`` ids), while a NominationsBundle binds
993 against the full pool. A missing angles file is legal: ``path=None``
994 returns an empty mapping and every topic ships without angles. When a
995 path is given the same strict-top-level / lenient-per-row rules as
996 judgments apply; angle sentences are word-boundary capped at 200 chars.
997 """
998 if path is None:
999 return {}
1000 payload = _load_host_file(path, "angles")
1001 _require_bundle_binding(
1002 payload, bundle, label="angles", save_dir=save_dir, config_dir=config_dir,
1003 )
1004 rows = payload.get("angles")
1005 if not isinstance(rows, list):
1006 raise HandoffContractError(
1007 f"Angles file {path} must carry a top-level \"angles\" list."
1008 )
1009 known = (
1010 set(bundle.angle_inputs)
1011 if isinstance(bundle, PendingReport)
1012 else {entry.nomination_id for entry in bundle.nominations}
1013 )
1014 angles: dict[str, HostAngles] = {}
1015 for row_id, row in _known_rows(
1016 rows, known, row_label="angles", unknown_label="angles"
1017 ):
1018 podcast = _sanitized_angle(row.get("podcast"))
1019 x_article = _sanitized_angle(row.get("x_article"))
1020 if podcast is None and x_article is None:
1021 # No usable hook at all: treat the row as absent.
1022 continue
1023 angles[row_id] = HostAngles(podcast=podcast, x_article=x_article)
1024 return angles
1025
1026
1027 def resolve_name_collisions(
1028 pairs: Sequence[tuple[pipeline.Nomination, str]],
1029 ) -> list[str]:
1030 """Re-run the nominate-stage casefold/entity-token collision rules over
1031 host-applied names, returning one collision-free name per input pair in
1032 order.
1033
1034 Short host-judged names collide far more often than raw titles; a
1035 colliding name gets the later nomination's strongest non-shared entity
1036 token appended (``pipeline._disambiguated_topic_name``, fed synthetic
1037 per-nomination clusters built from the seed items). Unlike the nominate
1038 stage, a collision can never DROP a nomination here - the pool already
1039 de-duplicated same-story clusters at leg 1 - so when no distinguishing
1040 entity token exists the name falls back to an ordinal suffix.
1041 """
1042 candidate_map: dict[str, schema.Candidate] = {}
1043 clusters: list[schema.Cluster] = []
1044 for index, (nomination, _applied) in enumerate(pairs):
1045 candidate_ids: list[str] = []
1046 for item_index, item in enumerate(nomination.items):
1047 candidate_id = f"handoff-{index}-{item_index}"
1048 candidate_map[candidate_id] = schema.Candidate(
1049 candidate_id=candidate_id,
1050 item_id=item.item_id,
1051 source=item.source,
1052 title=item.title,
1053 url=item.url,
1054 snippet=item.snippet,
1055 subquery_labels=[],
1056 native_ranks={},
1057 local_relevance=0.0,
1058 freshness=0,
1059 engagement=None,
1060 source_quality=0.0,
1061 rrf_score=0.0,
1062 )
1063 candidate_ids.append(candidate_id)
1064 clusters.append(schema.Cluster(
1065 cluster_id=f"handoff-n{index}",
1066 title=nomination.name,
1067 candidate_ids=candidate_ids,
1068 representative_ids=candidate_ids[:1],
1069 sources=sorted({
1070 item.source for item in nomination.items if isinstance(item.source, str)
1071 }),
1072 score=nomination.seed_score,
1073 ))
1074
1075 resolved_names: list[str] = []
1076 taken: dict[str, schema.Cluster] = {}
1077 entity_counts_cache: dict[str, Counter] = {}
1078 for index, (_nomination, applied) in enumerate(pairs):
1079 cluster = clusters[index]
1080 name = applied
1081 key = name.casefold()
1082 if key in taken:
1083 resolved = pipeline._disambiguated_topic_name(
1084 name, cluster, taken[key], candidate_map, entity_counts_cache,
1085 taken,
1086 )
1087 if resolved is None:
1088 # Indistinguishable by content: keep the nomination anyway
1089 # (distinct stories at leg 1) under an ordinal suffix.
1090 suffix = 2
1091 while f"{name} {suffix}".casefold() in taken:
1092 suffix += 1
1093 resolved = f"{name} {suffix}"
1094 name = resolved
1095 key = name.casefold()
1096 taken[key] = cluster
1097 resolved_names.append(name)
1098 return resolved_names
1099
1100
1101 def _one_line(text: str) -> str:
1102 return " ".join(text.split())
1103
1104
1105 def build_host_digest(bundle: NominationsBundle) -> str:
1106 """The host-facing judging digest for a nominations bundle: plain,
1107 promptable text with one structural line per nomination (id, seed source
1108 names, velocity/engagement signal) plus capped evidence lines (leader
1109 title, leader snippet, strongest community comment - the surface the
1110 engine judge used to see). Names the bundle file and instructs the host
1111 to read its full evidence before judging.
1112
1113 The evidence lines are scraped third-party text, so they are fenced the
1114 way the deleted engine judge fenced its candidate block (the exact
1115 ``rerank._fenced_untrusted_content`` fence: a security-notice header
1116 stating the fenced content is data, never instructions, around
1117 ``<untrusted_content>`` tags). The structural lines - nomination ids,
1118 sources, signal, bundle path, judging instructions - stay outside the
1119 fence."""
1120 location = str(bundle.path) if bundle.path is not None else (
1121 NOMINATIONS_BUNDLE_FILENAME
1122 )
1123 domain_label = bundle.domain or "global trending (no domain filter)"
1124 lines = [
1125 f"Discovery nominations awaiting host judgment "
1126 f"({len(bundle.nominations)} topics).",
1127 f"Domain: {domain_label} | window {bundle.from_date} -> "
1128 f"{bundle.to_date} | tier {bundle.tier}",
1129 f"Bundle file: {location} (bundle_id {bundle.bundle_id})",
1130 "Read the bundle file's per-nomination evidence before judging; the "
1131 "lines below are only a digest.",
1132 "",
1133 ]
1134 evidence_lines: list[str] = []
1135 for entry in bundle.nominations:
1136 items = entry.nomination.items
1137 leader = items[0] if items else None
1138 title = _one_line((leader.title if leader else "") or entry.nomination.name)
1139 sources = ", ".join(entry.sources) if entry.sources else "unknown"
1140 native_total = sum(
1141 rerank.discovery_engagement_total(item) for item in items
1142 )
1143 lines.append(
1144 f"{entry.nomination_id} | sources: {sources} | "
1145 f"signal: seed velocity {entry.nomination.seed_score:.1f}, "
1146 f"{native_total:,.0f} native interactions"
1147 )
1148 evidence_lines.append(f"- id: {entry.nomination_id}")
1149 evidence_lines.append(f" title: {title[:_DIGEST_TITLE_MAX_CHARS]}")
1150 snippet_text = _one_line(
1151 (leader.snippet if leader else "") or entry.nomination.summary
1152 )
1153 if snippet_text:
1154 evidence_lines.append(
1155 f" snippet: {snippet_text[:_DIGEST_SNIPPET_MAX_CHARS]}"
1156 )
1157 top_comment = pipeline._best_community_comment(items)
1158 if top_comment:
1159 evidence_lines.append(
1160 f" top comment: "
1161 f"{_one_line(top_comment)[:_DIGEST_COMMENT_MAX_CHARS]}"
1162 )
1163 if evidence_lines:
1164 lines.append("")
1165 lines.append(rerank._fenced_untrusted_content("\n".join(evidence_lines)))
1166 return "\n".join(lines)
1167
1167 lines PYTHON