Skip to content

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

fix(discovery): preserve coverage warnings across protocol legs (#1223)

Ilia Alshanetsky2e605ecfaf97
diff --git a/changelog.d/+discovery-protocol-receipts.fixed.md b/changelog.d/+discovery-protocol-receipts.fixed.md
new file mode 100644
index 00000000..4cf4d847
--- /dev/null
+++ b/changelog.d/+discovery-protocol-receipts.fixed.md
@@ -0,0 +1 @@
+Preserve discovery sweep coverage warnings through saved nomination bundles, resumed research, and final reports, including empty results. Older nomination bundles continue to load.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 73391e44..9031774f 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -2137,6 +2137,7 @@ def _run_discover_nominate(args: argparse.Namespace, config: dict[str, object])
# 2-3 report degraded coverage instead of silently reading clean; the
# mock stamp keeps mock-born and real state from cross-finalizing.
source_status=result.source_status,
+ warnings=result.warnings,
mock=args.mock,
# Same resolution as _discover_handoff_state_dir: save dir when
# given, else the config dir.
diff --git a/skills/last30days/scripts/lib/discovery_handoff.py b/skills/last30days/scripts/lib/discovery_handoff.py
index 2586f3ae..6df4d218 100644
--- a/skills/last30days/scripts/lib/discovery_handoff.py
+++ b/skills/last30days/scripts/lib/discovery_handoff.py
@@ -117,7 +117,8 @@ class NominationsBundle:
instead of silently reading as clean. ``mock`` is the writing run's
provenance - mock-born state must never be finalized by a real run (and
vice versa); files written before either field existed read as an empty
- map and a real run."""
+ map and a real run. ``warnings`` retains informational sweep coverage
+ separately from source outcomes; older files read with no warnings."""
schema_version: str
bundle_id: str
@@ -133,6 +134,7 @@ class NominationsBundle:
source_status: dict[str, schema.SourceOutcome] = field(default_factory=dict)
mock: bool = False
path: Path | None = None
+ warnings: list[str] = field(default_factory=list)
@dataclass(frozen=True)
@@ -244,6 +246,7 @@ def write_nominations_bundle(
enrichment_source_boundary: list[str] | None,
requested_sources: list[str] | None,
source_status: dict[str, schema.SourceOutcome] | None = None,
+ warnings: Sequence[str] | None = None,
mock: bool = False,
save_dir: str | Path | None = None,
config_dir: Path | None = None,
@@ -257,7 +260,8 @@ def write_nominations_bundle(
"empty boundary" are different contracts. ``source_status`` is the
sweep's finalized per-source outcome map (serialized via the same
``schema.to_dict`` round trip every report uses) so degraded coverage
- survives into legs 2-3; ``mock`` stamps the writing run's provenance.
+ survives into legs 2-3; ``warnings`` preserves informational coverage
+ receipts, and ``mock`` stamps the writing run's provenance.
"""
if tier not in _VALID_TIERS:
raise ValueError(f"tier must be one of {_VALID_TIERS}, got {tier!r}")
@@ -305,6 +309,7 @@ def write_nominations_bundle(
"domain": domain,
"tier": tier,
"mock": bool(mock),
+ "warnings": list(warnings or []),
"source_status": {
source: schema.to_dict(outcome)
for source, outcome in (source_status or {}).items()
@@ -353,6 +358,7 @@ def write_nominations_bundle(
source_status=dict(source_status or {}),
mock=bool(mock),
path=path,
+ warnings=list(warnings or []),
)
@@ -522,6 +528,11 @@ def _parse_bundle_file(path: Path) -> NominationsBundle:
_warn(f"ignoring malformed source_status map in {path.name}")
source_status = {}
+ warnings = payload.get("warnings", [])
+ if not isinstance(warnings, list) or any(not isinstance(warning, str) for warning in warnings):
+ _warn(f"ignoring malformed warnings list in {path.name}")
+ warnings = []
+
return NominationsBundle(
schema_version=str(version),
bundle_id=bundle_id,
@@ -543,6 +554,7 @@ def _parse_bundle_file(path: Path) -> NominationsBundle:
source_status=source_status,
mock=bool(payload.get("mock")),
path=path,
+ warnings=warnings,
)
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 19337485..6e6b6d56 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -1417,6 +1417,7 @@ class DiscoverNominateResult:
to_date: str
source_status: dict[str, schema.SourceOutcome]
pool: list[tuple[Nomination, str]]
+ warnings: list[str] = field(default_factory=list)
def run_discover_nominate(
@@ -1461,6 +1462,7 @@ def run_discover_nominate(
to_date=sweep.to_date,
source_status=sweep.source_status,
pool=pool,
+ warnings=list(sweep.bundle.artifacts.get("x_partial_coverage", [])),
)
@@ -1474,6 +1476,7 @@ def nominate_nothing_solid_report(result: DiscoverNominateResult) -> schema.Disc
failed = _degraded_discovery_sources(result.source_status)
if failed:
warnings.append(f"Some discovery sources degraded: {', '.join(sorted(failed))}.")
+ warnings.extend(result.warnings)
return schema.DiscoveryReport(
domain=result.plan.domain,
range_from=result.from_date,
@@ -1986,7 +1989,10 @@ def run_discover_resume(
plan=plan,
topics=topics,
source_status=source_status,
- warnings=_discovery_report_warnings(topics, outcome, source_status),
+ warnings=(
+ _discovery_report_warnings(topics, outcome, source_status)
+ + list(getattr(bundle, "warnings", None) or [])
+ ),
outcome=outcome,
weak_signal=weak_signal[1] if weak_signal and not topics else None,
)
diff --git a/tests/test_discover_handoff.py b/tests/test_discover_handoff.py
index ac233983..48c960d0 100644
--- a/tests/test_discover_handoff.py
+++ b/tests/test_discover_handoff.py
@@ -226,6 +226,19 @@ def test_bundle_reader_defaults_source_status_and_mock_for_older_files(tmp_path)
assert read.mock is False
[email protected]("warnings", [None, "warning", {"warning": "text"}, ["valid", 3]])
+def test_bundle_ignores_malformed_advisory_warnings(tmp_path, capsys, warnings):
+ written = _write(tmp_path)
+ path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ payload["warnings"] = warnings
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ read = handoff.read_nominations_bundle(config_dir=tmp_path)
+ assert read.nominations == written.nominations
+ assert read.warnings == []
+ assert "ignoring malformed warnings list" in capsys.readouterr().err
+
+
# --- Scenario 2: parity pin --------------------------------------------------
diff --git a/tests/test_discover_receipts.py b/tests/test_discover_receipts.py
new file mode 100644
index 00000000..e2840361
--- /dev/null
+++ b/tests/test_discover_receipts.py
@@ -0,0 +1,131 @@
+import json
+import time
+
+import pytest
+
+import last30days as cli
+from lib import discovery_handoff, health, pipeline, render, schema
+
+
+def _args(directory, *extra):
+ return cli.build_parser().parse_args([
+ "--discover", "AI agents", "--search", "x", "--discover-shallow",
+ "--save-dir", str(directory), *extra,
+ ])
+
+
[email protected]("legacy", [False, True])
[email protected]("discard", [False, True])
+def test_sweep_warning_survives_saved_protocol_round_trip(tmp_path, monkeypatch, capsys, legacy, discard):
+ warning = "X: xapi window truncated to 7 days"
+ config = {
+ "LAST30DAYS_X_BACKEND": "xapi", "X_BEARER_TOKEN": "dummy",
+ "LAST30DAYS_STORE": str(tmp_path / "research.db"),
+ }
+ calls = []
+
+ def search(_token, topic, from_date, to_date, **kwargs):
+ calls.append(topic)
+ result = {"items": [{
+ "id": "1", "text": f"{topic}: Agent memory protocols improve local runtimes",
+ "url": "https://x.com/example/status/1", "author_handle": "example",
+ "date": to_date, "engagement": {"likes": 900, "reposts": 100},
+ "relevance": 1.0,
+ }]}
+ if len(calls) == 1:
+ result["warning"] = "window truncated to 7 days"
+ return result
+
+ monkeypatch.setattr(pipeline.x_api, "search_x", search)
+ monkeypatch.setattr(pipeline.x_api, "search_handles", lambda *a, **k: [])
+ monkeypatch.setattr(pipeline.x_api, "search_mentions", lambda *a, **k: [])
+ runtime = schema.ProviderRuntime(
+ reasoning_provider="native", planner_model="", rerank_model="",
+ x_search_backend="xapi",
+ )
+ monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
+
+ assert cli._run_discover_protocol_leg(_args(tmp_path, "--nominate-only"), config) == 0
+ capsys.readouterr()
+ bundle_path = tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME
+ payload = json.loads(bundle_path.read_text(encoding="utf-8"))
+ assert payload["nominations"]
+ assert payload["warnings"] == [warning]
+ if legacy:
+ payload.pop("warnings")
+ bundle_path.write_text(json.dumps(payload), encoding="utf-8")
+ expected = [] if legacy else [warning]
+ bundle = discovery_handoff.read_nominations_bundle(save_dir=tmp_path)
+ assert bundle.schema_version == "1.0"
+ assert bundle.warnings == expected
+ assert bundle.source_status["x"].state == "ok"
+
+ judgments = tmp_path / "judgments.json"
+ judgments.write_text(json.dumps({
+ "bundle_id": bundle.bundle_id,
+ "judgments": [{"id": row.nomination_id, "junk": discard, "worthiness": 90}
+ for row in bundle.nominations],
+ }), encoding="utf-8")
+ assert cli._run_discover_protocol_leg(_args(tmp_path, "--judgments", str(judgments)), config) == 0
+ resumed = capsys.readouterr()
+ if discard:
+ assert "Nothing solid this window." in resumed.out
+ assert resumed.out.count(warning) == len(expected)
+ assert not (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).exists()
+ return
+ assert len(calls) > 1
+ pending = discovery_handoff.read_pending_report(save_dir=tmp_path)
+ assert pending.report["topics"]
+ assert pending.report["warnings"].count(warning) == len(expected)
+ assert pending.report["source_status"]["x"]["state"] == "ok"
+
+ assert cli._run_discover_protocol_leg(_args(tmp_path, "--finalize"), config) == 0
+ assert capsys.readouterr().out.count(warning) == len(expected)
+ saved = list(tmp_path.glob("*.md"))
+ assert saved
+ assert saved[0].read_text(encoding="utf-8").count(warning) == len(expected)
+
+
[email protected]("outcome", ["budget-stop", "complete", "first-failure"])
+def test_empty_nomination_report_preserves_bird_coverage(monkeypatch, outcome):
+ now = [1000.0]
+ calls = []
+ config = {
+ "LAST30DAYS_X_BACKEND": "bird", "AUTH_TOKEN": "dummy", "CT0": "dummy",
+ "_research_deadline": 1005.0,
+ }
+
+ def search(query, count, timeout, deadline=None, **kwargs):
+ calls.append(query)
+ if outcome != "complete":
+ now[0] = deadline - 0.5
+ if outcome == "first-failure":
+ return {"items": [], "error": "Invalid JSON response (anti-bot interstitial)"}
+ return {"items": []}
+
+ monkeypatch.setattr(pipeline.bird_x, "_run_bird_search", search)
+ monkeypatch.setattr(time, "monotonic", lambda: now[0])
+ result = pipeline.run_discover_nominate(
+ domain="Widget compiler development", config=config, depth="quick", requested_sources=["x"],
+ )
+ assert result.pool == []
+ report = pipeline.nominate_nothing_solid_report(result)
+ compact = render.render_discovery(report)
+ receipts = [warning for warning in report.warnings if "search budget" in warning]
+ if outcome == "budget-stop":
+ assert len(calls) == 1
+ assert report.source_status["x"].state == schema.NO_RESULTS
+ assert receipts == [
+ "X: bird Partial coverage: optional zero-result retries skipped because the search budget was exhausted."
+ ]
+ assert receipts[0] in compact
+ elif outcome == "complete":
+ assert len(calls) > 1
+ assert report.source_status["x"].state == schema.NO_RESULTS
+ assert receipts == []
+ else:
+ assert len(calls) == 1
+ assert report.source_status["x"].state == health.SCHEMA_DRIFT
+ assert "Invalid JSON response" in report.source_status["x"].detail
+ assert "Some discovery sources degraded: x." in report.warnings
+ assert receipts == []