返回 last30days-skill
test_discover_mode.py
根目录 / tests / test_discover_mode.py
1 import argparse
2 import contextlib
3 import inspect
4 import json
5 import os
6 import subprocess
7 import sys
8 import urllib.error
9 from pathlib import Path
10 from unittest import mock
11
12 import pytest
13
14 import last30days as cli
15 from lib import dates, digg, discovery_handoff, pipeline, planner, reddit_listing, render, rerank, schema
16
17
18 REPO_ROOT = Path(__file__).resolve().parents[1]
19
20
21 def _item(
22 item_id: str,
23 source: str,
24 title: str,
25 *,
26 published_at: str = "2026-07-09",
27 engagement: dict[str, int | float] | None = None,
28 ) -> schema.SourceItem:
29 return schema.SourceItem(
30 item_id=item_id,
31 source=source,
32 title=title,
33 body=title,
34 url=f"https://{source}.example/{item_id}",
35 published_at=published_at,
36 engagement=engagement or {},
37 snippet=f"Evidence about {title}",
38 )
39
40
41 def _candidate(item: schema.SourceItem) -> schema.Candidate:
42 return schema.Candidate(
43 candidate_id=f"candidate-{item.item_id}",
44 item_id=item.item_id,
45 source=item.source,
46 title=item.title,
47 url=item.url,
48 snippet=item.snippet,
49 subquery_labels=["discovery-listings"],
50 native_ranks={f"discovery-listings:{item.source}": 1},
51 local_relevance=0.9,
52 freshness=95,
53 engagement=100,
54 source_quality=0.8,
55 rrf_score=0.1,
56 sources=[item.source],
57 source_items=[item],
58 final_score=80,
59 )
60
61
62 def test_discovery_plan_reuses_category_peer_mapping():
63 plan = planner.build_discovery_plan(
64 "AI agents",
65 available_sources=["reddit", "hackernews"],
66 )
67
68 assert plan.category == "ai_agent_framework"
69 assert plan.subreddits == ["LangChain", "LocalLLaMA", "AI_Agents", "MachineLearning"]
70 assert plan.sources == ["reddit", "hackernews"]
71
72
73 def test_discovery_plan_keeps_keyless_reddit_for_unknown_domains():
74 plan = planner.build_discovery_plan(
75 "urban gardening",
76 available_sources=["reddit", "hackernews"],
77 )
78
79 assert plan.category is None
80 assert plan.subreddits == ["all"]
81 assert plan.sources == ["reddit", "hackernews"]
82
83
84 def test_discovery_plan_empty_domain_is_global_trending():
85 """Bare --discover: sweep every river feed's hot list; X sits out of the
86 nominate stage because its search lane needs a keyword."""
87 plan = planner.build_discovery_plan(
88 "",
89 available_sources=["reddit", "hackernews", "digg", "x"],
90 )
91
92 assert plan.domain == ""
93 assert plan.category is None
94 assert plan.subreddits == ["all"]
95 assert plan.sources == ["reddit", "hackernews", "digg"]
96 assert "x" not in plan.sources
97
98
99 def test_global_discovery_disables_keyword_gate():
100 """Global trending fetches with keyword_gate=False; domain runs keep it on."""
101 seen: dict[str, bool] = {}
102
103 def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
104 seen[plan.domain or "global"] = keyword_gate
105 return [], None
106
107 with mock.patch.object(pipeline, "available_sources", return_value=["hackernews"]), \
108 mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
109 pipeline.run_discover(domain="", config={}, as_of_date="2026-07-10")
110 pipeline.run_discover(domain="AI agents", config={}, as_of_date="2026-07-10")
111
112 assert seen["global"] is False
113 assert seen["AI agents"] is True
114
115
116 def test_uncategorized_discovery_uses_parseable_r_all_listing_paths():
117 card = (
118 '<shreddit-post permalink="/r/gardening/comments/abc123/urban_garden/" '
119 'post-title="Urban gardening is taking off" score="42" comment-count="7" '
120 'author="gardener" subreddit-name="gardening" '
121 'created-timestamp="2026-07-09T12:00:00+00:00">'
122 )
123 requested_urls: list[str] = []
124
125 def fake_get(url, **_kwargs):
126 requested_urls.append(url)
127 return card
128
129 with mock.patch.object(reddit_listing.http, "reddit_keyless_get_text", side_effect=fake_get):
130 result = reddit_listing.fetch_discovery_listings(
131 ["all"], query="urban gardening",
132 )
133
134 assert len(result["items"]) == 1
135 assert any("/r/all/rising/" in url for url in requested_urls)
136 assert any("/r/all/top/?t=week" in url for url in requested_urls)
137 assert all("name=all" not in url for url in requested_urls)
138
139
140 def test_velocity_scoring_favors_a_recent_spike_over_static_bigness():
141 recent = _item(
142 "recent",
143 "reddit",
144 "Recent spike",
145 published_at="2026-07-09",
146 engagement={"score": 100, "num_comments": 10},
147 )
148 old = _item(
149 "old",
150 "reddit",
151 "Older large thread",
152 published_at="2026-06-20",
153 engagement={"score": 300, "num_comments": 10},
154 )
155
156 assert rerank.engagement_velocity_score(recent, as_of_date="2026-07-10") > (
157 rerank.engagement_velocity_score(old, as_of_date="2026-07-10")
158 )
159
160
161 def test_domain_filter_ignores_generic_ai_only_matches():
162 assert pipeline._matches_discovery_domain(
163 "AI agents", "An AI agent bankrupted its operator"
164 )
165 assert not pipeline._matches_discovery_domain(
166 "AI agents", "Global dialogue on AI governance"
167 )
168
169
170 @pytest.mark.parametrize(
171 ("domain", "listing_title"),
172 [
173 ("城市园艺", "城市园艺技巧与社区花园"),
174 ("גינון עירוני", "מדריך חדש לגינון עירוני"),
175 ],
176 )
177 def test_domain_filter_tokenizes_non_latin_domains(domain, listing_title):
178 assert pipeline._matches_discovery_domain(domain, listing_title)
179
180
181 def test_x_velocity_excludes_views_and_bookmarks():
182 xquik_item = _item(
183 "xquik",
184 "x",
185 "X backend reach",
186 engagement={
187 "likes": 10,
188 "reposts": 3,
189 "replies": 2,
190 "quotes": 1,
191 "views": 100_000,
192 "bookmarks": 5_000,
193 },
194 )
195 standard_item = _item(
196 "standard",
197 "x",
198 "X backend interactions",
199 engagement={"likes": 10, "reposts": 3, "replies": 2, "quotes": 1},
200 )
201
202 assert rerank.discovery_engagement_total(xquik_item) == 16
203 assert rerank.engagement_velocity_score(
204 xquik_item, as_of_date="2026-07-10"
205 ) == rerank.engagement_velocity_score(standard_item, as_of_date="2026-07-10")
206
207
208 def test_discovery_renderer_snapshot():
209 report = schema.DiscoveryReport(
210 domain="AI agents",
211 range_from="2026-06-10",
212 range_to="2026-07-10",
213 generated_at="2026-07-10T00:00:00+00:00",
214 plan=schema.DiscoveryPlan(
215 domain="AI agents",
216 category="ai_agent_framework",
217 subreddits=["AI_Agents"],
218 sources=["reddit", "hackernews"],
219 ),
220 topics=[schema.DiscoveryTopic(
221 rank=1,
222 name="Agent memory protocols",
223 why_spiking="Two independent listing items accelerated this week.",
224 momentum="new-this-week",
225 velocity_score=123.45,
226 sources=["hackernews", "reddit"],
227 engagement_by_source={
228 "reddit": {"score": 120, "num_comments": 30},
229 "hackernews": {"points": 80},
230 },
231 command='/last30days "Agent memory protocols"',
232 )],
233 )
234
235 with mock.patch.object(render, "_render_badge", return_value=["BADGE", ""]):
236 rendered = render.render_discovery(report)
237
238 assert rendered == (
239 "BADGE\n\n"
240 "# Trending discovery: AI agents\n\n"
241 "Window: 2026-06-10 to 2026-07-10\n"
242 "Feeds: reddit, hackernews\n"
243 "Communities: r/AI_Agents\n\n"
244 "## 1. Agent memory protocols\n\n"
245 "**Momentum:** New this week · velocity 123.45\n\n"
246 "Two independent listing items accelerated this week.\n\n"
247 "**Evidence:** Reddit: score 120, num comments 30 · Hacker News: points 80\n\n"
248 "**Research next:** `/last30days \"Agent memory protocols\"`\n"
249 )
250
251
252 def test_keyless_discovery_degrades_without_digg():
253 def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
254 return pipeline._mock_discovery_items(source, plan.domain, to_date), None
255
256 with mock.patch.object(pipeline, "available_sources", return_value=["reddit", "hackernews"]), \
257 mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
258 report = pipeline.run_discover(
259 domain="AI agents",
260 config={},
261 as_of_date="2026-07-10",
262 )
263
264 assert 5 <= len(report.topics) <= 10
265 assert report.source_status["reddit"].state == "ok"
266 assert report.source_status["hackernews"].state == "ok"
267 assert report.source_status["digg"].state == "skipped-unconfigured"
268 assert report.source_status["x"].state == "skipped-unconfigured"
269 assert all(topic.command.startswith('/last30days "') for topic in report.topics)
270
271
272 def test_discovery_drops_zero_velocity_clusters():
273 raw_item = {
274 "id": "zero-engagement",
275 "text": "AI agent launch with no interactions",
276 "url": "https://x.com/example/status/1",
277 "author_handle": "example",
278 "date": "2026-07-09",
279 "engagement": {"likes": 0, "reposts": 0, "replies": 0, "quotes": 0},
280 "relevance": 0.9,
281 }
282
283 with mock.patch.object(pipeline, "available_sources", return_value=["x"]), \
284 mock.patch.object(pipeline, "_fetch_discovery_source", return_value=([raw_item], None)):
285 report = pipeline.run_discover(
286 domain="AI agents",
287 config={},
288 as_of_date="2026-07-10",
289 )
290
291 assert report.topics == []
292 assert report.outcome == "nothing-solid"
293 assert any("confidence floor" in warning for warning in report.warnings)
294
295
296 def test_explicit_unavailable_discovery_source_does_not_widen_to_other_sources():
297 with mock.patch.object(pipeline, "available_sources", return_value=[]), \
298 mock.patch.object(pipeline, "_fetch_discovery_source") as fetch:
299 with pytest.raises(ValueError, match="No listing sources are available"):
300 pipeline.run_discover(
301 domain="AI agents",
302 config={},
303 requested_sources=["digg"],
304 as_of_date="2026-07-10",
305 )
306
307 fetch.assert_not_called()
308
309
310 def test_discovery_reads_browser_credentials_and_does_not_schedule_pending_x():
311 parser = cli.build_parser()
312 args, extra = parser.parse_known_args(["--discover", "AI agents"])
313 assert cli._config_policy_for_args(args, "", extra).browser_cookies == "read"
314
315 no_cookies_args, extra = parser.parse_known_args(
316 ["--no-browser-cookies", "--discover", "AI agents"]
317 )
318 assert cli._config_policy_for_args(no_cookies_args, "", extra).browser_cookies == "off"
319
320 fetched_sources: list[str] = []
321
322 def fake_available_sources(config, requested_sources, *, x_pending=None, local_only=False):
323 assert x_pending is False
324 return ["reddit", "hackernews"] + (["x"] if x_pending is not False else [])
325
326 def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
327 fetched_sources.append(source)
328 return pipeline._mock_discovery_items(source, plan.domain, to_date), None
329
330 with mock.patch.object(pipeline, "available_sources", side_effect=fake_available_sources), \
331 mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
332 report = pipeline.run_discover(
333 domain="AI agents",
334 config={"FROM_BROWSER": "firefox", "_BROWSER_COOKIE_MODE": "plan_only"},
335 as_of_date="2026-07-10",
336 )
337
338 assert "x" not in fetched_sources
339 assert report.source_status["x"].state == "skipped-unconfigured"
340
341
342 def test_authenticated_x_discovery_uses_available_backend():
343 plan = planner.build_discovery_plan(
344 "AI agents",
345 available_sources=["x"],
346 )
347 raw = pipeline._mock_discovery_items("x", plan.domain, "2026-07-10")
348 with mock.patch.object(pipeline.env, "x_backend_chain", return_value=["bird"]), \
349 mock.patch.object(pipeline, "_fetch_x_backend", return_value=(raw, "")) as fetch:
350 items, error = pipeline._fetch_discovery_source(
351 "x",
352 plan,
353 from_date="2026-06-10",
354 to_date="2026-07-10",
355 depth="default",
356 mock=False,
357 config={"AUTH_TOKEN": "dummy", "CT0": "dummy"},
358 )
359
360 assert error is None
361 assert len(items) == 6
362 fetch.assert_called_once()
363
364
365 def test_listing_failure_is_not_reported_as_clean_no_results():
366 def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
367 if source == "reddit":
368 return [], "connection timed out"
369 return pipeline._mock_discovery_items(source, plan.domain, to_date), None
370
371 with mock.patch.object(pipeline, "available_sources", return_value=["reddit", "hackernews"]), \
372 mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
373 report = pipeline.run_discover(
374 domain="AI agents",
375 config={},
376 as_of_date="2026-07-10",
377 )
378
379 assert report.source_status["reddit"].state == "timeout"
380 assert report.source_status["reddit"].detail == "connection timed out"
381
382
383 def test_discovery_listing_block_is_reported_as_rate_limited():
384 # get_text swallows the 429 and hands back None; without the tee the lane
385 # could not tell that apart from an empty listing and the sweep reported a
386 # clean no-results (issue #899).
387 blocked = urllib.error.HTTPError(
388 "https://www.reddit.com/svc/shreddit/community-more-posts/rising/",
389 429,
390 "Too Many Requests",
391 {},
392 None,
393 )
394
395 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
396 mock.patch("lib.http.time.sleep"), \
397 mock.patch("lib.http.urllib.request.urlopen", side_effect=blocked):
398 report = pipeline.run_discover(
399 domain="AI agents",
400 config={},
401 as_of_date="2026-07-10",
402 subreddits=["AI_Agents"],
403 )
404
405 outcome = report.source_status["reddit"]
406 assert outcome.state == "rate-limited"
407 assert "429" in (outcome.detail or "")
408
409
410 def test_discovery_listing_403_is_reported_as_auth_failed():
411 blocked = urllib.error.HTTPError(
412 "https://www.reddit.com/r/all/rising/", 403, "Forbidden", {}, None,
413 )
414 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
415 mock.patch("lib.http.urllib.request.urlopen", side_effect=blocked):
416 report = pipeline.run_discover(
417 domain="", config={}, as_of_date="2026-07-10",
418 )
419
420 outcome = report.source_status["reddit"]
421 assert outcome.state == schema.AUTH_FAILED
422 assert "403" in (outcome.detail or "")
423
424
425 @pytest.mark.parametrize("body", [
426 "",
427 "<!doctype html><html><body><h1>You've been blocked</h1></body></html>",
428 "<html><body><main>Reddit listing layout changed</main></body></html>",
429 ])
430 def test_reddit_global_listing_without_cards_reports_schema_drift(body):
431 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
432 mock.patch.object(reddit_listing.http, "get_text", return_value=body), \
433 mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):
434 report = pipeline.run_discover(
435 domain="", config={}, as_of_date="2026-07-10",
436 )
437
438 outcome = report.source_status["reddit"]
439 assert outcome.state == schema.SCHEMA_DRIFT
440 assert "HTTP 2xx" in (outcome.detail or "")
441 assert "no post cards" in (outcome.detail or "")
442
443
444 def test_reddit_domain_filter_zero_after_valid_listing_remains_no_results():
445 body = (
446 "<!doctype html><html><body>"
447 '<shreddit-post permalink="/r/cats/comments/abc123/post/" '
448 'post-title="A playful kitten" score="42" comment-count="7" '
449 'author="owner" subreddit-name="cats" '
450 'created-timestamp="2026-07-09T12:00:00+00:00">'
451 "</body></html>"
452 )
453 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
454 mock.patch.object(reddit_listing.http, "get_text", return_value=body), \
455 mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):
456 report = pipeline.run_discover(
457 domain="urban gardening", config={}, as_of_date="2026-07-10",
458 subreddits=["all"],
459 )
460
461 assert report.source_status["reddit"].state == schema.NO_RESULTS
462
463
464 @pytest.mark.parametrize("body", [
465 "<div></div>",
466 "<!doctype html><html><body><main>No posts yet</main></body></html>",
467 ])
468 def test_empty_dedicated_reddit_listing_remains_no_results(body):
469 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
470 mock.patch.object(reddit_listing.http, "get_text", return_value=body), \
471 mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):
472 report = pipeline.run_discover(
473 domain="tea", config={}, as_of_date="2026-07-10",
474 subreddits=["tea"],
475 )
476
477 assert report.source_status["reddit"].state == schema.NO_RESULTS
478
479
480 def test_dedicated_reddit_challenge_fragment_reports_schema_drift():
481 body = "<div class='challenge-platform'>Please verify you are human</div>"
482 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
483 mock.patch.object(reddit_listing.http, "get_text", return_value=body), \
484 mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):
485 report = pipeline.run_discover(
486 domain="tea", config={}, as_of_date="2026-07-10",
487 subreddits=["tea"],
488 )
489
490 outcome = report.source_status["reddit"]
491 assert outcome.state == schema.SCHEMA_DRIFT
492 assert "interstitial" in (outcome.detail or "")
493
494
495 def test_dedicated_reddit_search_challenge_fixture_reports_schema_drift():
496 body = (REPO_ROOT / "fixtures/reddit_search_challenge.html").read_text(
497 encoding="utf-8"
498 )
499 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
500 mock.patch.object(reddit_listing.http, "get_text", return_value=body), \
501 mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):
502 report = pipeline.run_discover(
503 domain="tea", config={}, as_of_date="2026-07-10",
504 subreddits=["tea"],
505 )
506
507 outcome = report.source_status["reddit"]
508 assert outcome.state == schema.SCHEMA_DRIFT
509 assert "interstitial" in (outcome.detail or "")
510
511
512 def test_dedicated_reddit_verification_title_reports_schema_drift():
513 body = "<html><title>Please wait for verification</title></html>"
514 with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \
515 mock.patch.object(reddit_listing.http, "get_text", return_value=body), \
516 mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):
517 report = pipeline.run_discover(
518 domain="tea", config={}, as_of_date="2026-07-10",
519 subreddits=["tea"],
520 )
521
522 outcome = report.source_status["reddit"]
523 assert outcome.state == schema.SCHEMA_DRIFT
524 assert "interstitial" in (outcome.detail or "")
525
526
527 _DIGG_NEW_HELP = "Search Digg stories.\n\nFlags:\n --sort string relevance, score or newest\n"
528 _DIGG_OLD_HELP = "Search Digg stories by title and summary.\n\nFlags:\n --topic strings (default [ai])\n"
529
530
531 def _digg_top_row(index: int, **overrides) -> dict:
532 short_id = f"top{index:05d}"
533 row = {
534 "rank": index,
535 "clusterId": f"11111111-2222-3333-4444-{short_id:0>12}",
536 "clusterUrlId": short_id,
537 "url": f"https://digg.com/world/{short_id}",
538 "topic": "world",
539 "title": f"Top story number {index}",
540 "description": "Longer description of the story.",
541 "diggScore": 900 - index,
542 "postCount": 40 + index,
543 "uniqueAuthors": 20 + index,
544 "publishedAt": "2026-11-10T08:30:00Z",
545 }
546 row.update(overrides)
547 return row
548
549
550 def _fake_digg_cli(monkeypatch, *, help_text: str, stdout: str) -> list:
551 """Stand in for digg-pp-cli; returns the list its non-help calls land in."""
552 calls: list = []
553
554 def fake_run(cmd, *, timeout, env=None, on_pid=None):
555 if "--help" in cmd:
556 return digg.subproc.SubprocResult(returncode=0, stdout=help_text, stderr="")
557 calls.append(list(cmd))
558 return digg.subproc.SubprocResult(returncode=0, stdout=stdout, stderr="")
559
560 monkeypatch.setattr(digg, "_all_topic_search", None)
561 monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")
562 monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run)
563 return calls
564
565
566 def _fetch_digg_discovery(domain: str, *, keyword_gate: bool):
567 plan = schema.DiscoveryPlan(
568 domain=domain, category=None, subreddits=[], sources=["digg"],
569 )
570 return pipeline._fetch_discovery_source(
571 "digg", plan, from_date="2026-10-12", to_date="2026-11-11",
572 depth="default", mock=False, config={}, keyword_gate=keyword_gate,
573 )
574
575
576 def test_global_digg_discovery_lists_top_stories(monkeypatch):
577 rows = [_digg_top_row(i) for i in range(1, 21)]
578 calls = _fake_digg_cli(
579 monkeypatch, help_text=_DIGG_NEW_HELP, stdout=json.dumps({"meta": {}, "results": rows}),
580 )
581
582 items, error = _fetch_digg_discovery("", keyword_gate=False)
583
584 assert error is None
585 assert [cmd[1] for cmd in calls] == ["top"]
586 assert len(items) == 20
587 assert items[0]["title"] == "Top story number 1"
588 assert items[0]["engagement"] == {"postCount": 41, "uniqueAuthors": 21, "digg_score": 899}
589 for item in items:
590 assert set(item["engagement"]) == {"postCount", "uniqueAuthors", "digg_score"}
591 assert item["date"] == "2026-11-10"
592
593
594 def test_domain_digg_discovery_searches_instead_of_reading_top(monkeypatch):
595 story = _digg_top_row(1, title="Bitcoin crypto rally accelerates")
596 calls = _fake_digg_cli(
597 monkeypatch, help_text=_DIGG_NEW_HELP, stdout=json.dumps({"meta": {}, "results": [story]}),
598 )
599
600 items, error = _fetch_digg_discovery("crypto", keyword_gate=True)
601
602 assert error is None
603 assert [(cmd[1], cmd[-2], cmd[-1]) for cmd in calls] == [("search", "--", "crypto")]
604 assert [item["title"] for item in items] == ["Bitcoin crypto rally accelerates"]
605
606
607 def test_global_digg_discovery_on_an_older_cli_is_empty_without_a_failure(monkeypatch):
608 # digg-pp-cli 2026.10.1 answers `top --agent` from a local store, in plain
609 # text when that store is empty, and has no titles when it is not.
610 calls = _fake_digg_cli(
611 monkeypatch, help_text=_DIGG_OLD_HELP,
612 stdout="no clusters in the local store. Run `digg-pp-cli sync` first.\n",
613 )
614
615 items, error = _fetch_digg_discovery("", keyword_gate=False)
616
617 assert items == []
618 assert error is None
619 assert calls == []
620
621
622 def _global_trending_report(monkeypatch, *, digg_rows: list[dict], reddit_items: list[dict]):
623 _fake_digg_cli(
624 monkeypatch, help_text=_DIGG_NEW_HELP,
625 stdout=json.dumps({"meta": {}, "results": digg_rows}),
626 )
627 monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["reddit", "digg"])
628 monkeypatch.setattr(
629 reddit_listing, "fetch_discovery_listings",
630 lambda *a, **k: {"items": reddit_items, "errors": []},
631 )
632 return pipeline.run_discover(domain="", config={}, as_of_date="2026-11-11")
633
634
635 _FERRY_TITLE = "Harbor ferry strike halts morning commute"
636
637
638 def _ferry_reddit_item() -> dict:
639 return {
640 "id": "ferry-r-1",
641 "title": _FERRY_TITLE,
642 "url": "https://reddit.com/r/news/comments/ferry1",
643 "subreddit": "news",
644 "date": "2026-11-10",
645 "engagement": {"score": 20, "num_comments": 6},
646 "selftext": _FERRY_TITLE,
647 "relevance": 0.9,
648 "why_relevant": "listing",
649 }
650
651
652 def test_lone_digg_top_story_below_the_engagement_floor_is_not_a_trend(monkeypatch):
653 # 30 posts + 12 authors = 42 interactions from one source: under the
654 # single-source floor of 200, however high the Digg Score is.
655 row = _digg_top_row(1, title=_FERRY_TITLE, diggScore=9000, postCount=30, uniqueAuthors=12)
656
657 report = _global_trending_report(monkeypatch, digg_rows=[row], reddit_items=[])
658
659 assert report.topics == []
660 assert report.outcome == "nothing-solid"
661 assert report.weak_signal == _FERRY_TITLE
662
663
664 def test_digg_top_story_with_a_reddit_item_for_the_same_event_is_a_trend(monkeypatch):
665 row = _digg_top_row(1, title=_FERRY_TITLE, diggScore=9000, postCount=30, uniqueAuthors=12)
666
667 report = _global_trending_report(
668 monkeypatch, digg_rows=[row], reddit_items=[_ferry_reddit_item()],
669 )
670
671 assert len(report.topics) == 1
672 assert sorted(report.topics[0].sources) == ["digg", "reddit"]
673
674
675 def test_reddit_discovery_adapter_preserves_partial_feed_errors():
676 """When one shreddit sort lane fails and another succeeds, the failed lane's error is kept.
677
678 Errors are cleared per (sub, sort) pair, not per subreddit. Arctic-shift cannot
679 recover a specific sort lane since it's recency-only.
680 """
681 item = {
682 "url": "https://reddit.com/r/example/comments/1",
683 "title": "AI agent launch",
684 "subreddit": "AI_Agents", # Required for error-clearing logic.
685 }
686 with mock.patch.object(
687 reddit_listing,
688 "_fetch_one_with_status",
689 side_effect=[([], "rising timed out"), ([item], None)],
690 ), mock.patch(
691 "lib.reddit_arctic.fetch_listings",
692 return_value=[], # Arctic supplement returns nothing.
693 ):
694 result = reddit_listing.fetch_discovery_listings(
695 ["AI_Agents"], query="AI agents",
696 )
697
698 assert result["items"] == [item]
699 # Shreddit top succeeded → no error for top.
700 # Shreddit rising failed → error for rising is preserved.
701 # Error-clearing is per (sub, sort) pair, not per subreddit.
702 assert len(result["errors"]) == 1
703 assert "rising" in result["errors"][0].lower()
704
705
706 def test_discovery_cli_json_contract_and_mutual_exclusion():
707 result = subprocess.run(
708 [
709 sys.executable,
710 "skills/last30days/scripts/last30days.py",
711 "--discover",
712 "AI agents",
713 "--mock",
714 "--emit=json",
715 ],
716 cwd=REPO_ROOT,
717 capture_output=True,
718 text=True,
719 check=False,
720 )
721 assert result.returncode == 0, result.stderr
722 payload = json.loads(result.stdout)
723 assert payload["schema_version"] == "1.1"
724 assert payload["kind"] == "discovery"
725 assert 5 <= len(payload["results"]) <= 10
726 assert payload["results"][0]["command"].startswith('/last30days "')
727 # 1.1 fields ship in every result, with defaults when nothing set them.
728 for topic in payload["results"]:
729 assert topic["podcast_angle"] is None
730 assert topic["x_article_angle"] is None
731 assert topic["previously_surfaced_count"] == 0
732 assert topic["last_surfaced"] is None
733 assert topic["covered"] is False
734
735 invalid = subprocess.run(
736 [
737 sys.executable,
738 "skills/last30days/scripts/last30days.py",
739 "topic",
740 "--discover",
741 "AI agents",
742 "--mock",
743 ],
744 cwd=REPO_ROOT,
745 capture_output=True,
746 text=True,
747 check=False,
748 )
749 assert invalid.returncode == 2
750 assert "cannot be combined with a positional topic" in invalid.stderr
751
752 drill_conflict = subprocess.run(
753 [
754 sys.executable,
755 "skills/last30days/scripts/last30days.py",
756 "--discover",
757 "AI agents",
758 "--drill",
759 "1",
760 "--mock",
761 ],
762 cwd=REPO_ROOT,
763 capture_output=True,
764 text=True,
765 check=False,
766 )
767 assert drill_conflict.returncode == 2
768 assert "mutually exclusive" in drill_conflict.stderr
769
770
771 def _discovery_report(topic: schema.DiscoveryTopic) -> schema.DiscoveryReport:
772 return schema.DiscoveryReport(
773 domain="AI agents",
774 range_from="2026-06-10",
775 range_to="2026-07-10",
776 generated_at="2026-07-10T00:00:00+00:00",
777 plan=schema.DiscoveryPlan(
778 domain="AI agents",
779 category="ai_agent_framework",
780 subreddits=["AI_Agents"],
781 sources=["reddit", "hackernews"],
782 ),
783 topics=[topic],
784 )
785
786
787 def test_discovery_export_round_trips_angles_and_queue_annotations():
788 """The 1.1 fields must carry real values through to_discovery_export."""
789 payload = schema.to_discovery_export(_discovery_report(schema.DiscoveryTopic(
790 rank=1,
791 name="Agent memory protocols",
792 why_spiking="Two independent listing items accelerated this week.",
793 momentum="new-this-week",
794 velocity_score=123.45,
795 sources=["hackernews", "reddit"],
796 engagement_by_source={"reddit": {"score": 120, "num_comments": 30}},
797 command='/last30days "Agent memory protocols"',
798 podcast_angle="Why agent memory is the next context-window fight",
799 x_article_angle="Agent memory protocols, explained through this week's launches",
800 previously_surfaced_count=2,
801 last_surfaced="2026-07-03",
802 covered=True,
803 )))
804
805 assert payload["schema_version"] == "1.1"
806 result = payload["results"][0]
807 assert result["podcast_angle"] == "Why agent memory is the next context-window fight"
808 assert result["x_article_angle"] == (
809 "Agent memory protocols, explained through this week's launches"
810 )
811 assert result["previously_surfaced_count"] == 2
812 assert result["last_surfaced"] == "2026-07-03"
813 assert result["covered"] is True
814
815
816 def test_discovery_topic_constructs_with_only_pre_existing_fields():
817 """Pre-1.1 constructor calls must keep working; new fields default."""
818 topic = schema.DiscoveryTopic(
819 rank=1,
820 name="Agent memory protocols",
821 why_spiking="Two independent listing items accelerated this week.",
822 momentum="building",
823 velocity_score=10.0,
824 sources=["reddit"],
825 engagement_by_source={"reddit": {"score": 120}},
826 command='/last30days "Agent memory protocols"',
827 )
828
829 assert topic.podcast_angle is None
830 assert topic.x_article_angle is None
831 assert topic.previously_surfaced_count == 0
832 assert topic.last_surfaced is None
833 assert topic.covered is False
834
835 result = schema.to_discovery_export(_discovery_report(topic))["results"][0]
836 assert result["podcast_angle"] is None
837 assert result["x_article_angle"] is None
838 assert result["previously_surfaced_count"] == 0
839 assert result["last_surfaced"] is None
840 assert result["covered"] is False
841
842
843 def test_discovery_cli_mock_render_has_no_angle_or_pipeline_lines():
844 """--mock runs never resolve a reasoning provider, so rendered cards must
845 omit the U5 angle and Pipeline lines entirely - and stay deterministic
846 across runs (same-day mock fixtures)."""
847 def _run_once() -> subprocess.CompletedProcess:
848 return subprocess.run(
849 [
850 sys.executable,
851 "skills/last30days/scripts/last30days.py",
852 "--discover",
853 "AI agents",
854 "--mock",
855 ],
856 cwd=REPO_ROOT,
857 capture_output=True,
858 text=True,
859 check=False,
860 )
861
862 first = _run_once()
863 second = _run_once()
864 assert first.returncode == 0, first.stderr
865 assert "**Podcast angle:**" not in first.stdout
866 assert "**X article angle:**" not in first.stdout
867 assert "**Pipeline:**" not in first.stdout
868 assert first.stdout == second.stdout
869
870
871 def test_discovery_cli_bare_discover_is_global_trending():
872 """Bare --discover (no domain) must run global trending, not error."""
873 result = subprocess.run(
874 [
875 sys.executable,
876 "skills/last30days/scripts/last30days.py",
877 "--discover",
878 "--mock",
879 "--emit=json",
880 ],
881 cwd=REPO_ROOT,
882 capture_output=True,
883 text=True,
884 check=False,
885 )
886 assert result.returncode == 0, result.stderr
887 payload = json.loads(result.stdout)
888 assert payload["kind"] == "discovery"
889 assert payload["domain"] == ""
890 assert payload["outcome"] in {"ok", "nothing-solid"}
891
892
893 def test_discovery_cli_shallow_skips_enrichment():
894 """--discover-shallow ranks on listing evidence only (still floored)."""
895 result = subprocess.run(
896 [
897 sys.executable,
898 "skills/last30days/scripts/last30days.py",
899 "--discover", "AI agents",
900 "--discover-shallow",
901 "--mock",
902 "--emit=json",
903 ],
904 cwd=REPO_ROOT,
905 capture_output=True,
906 text=True,
907 check=False,
908 )
909 assert result.returncode == 0, result.stderr
910 payload = json.loads(result.stdout)
911 assert payload["results"], "shallow mock sweep should still rank mock topics"
912 assert all(
913 "listing item" in topic["why_spiking"] for topic in payload["results"]
914 ), "shallow mode must be judged on listing evidence, not enriched corpora"
915
916
917 def test_discovery_cli_rejects_shallow_without_discover():
918 """--discover-shallow on a normal topic run must error, not silently no-op
919 into a full research pass (P2 from PR #816 review)."""
920 result = subprocess.run(
921 [
922 sys.executable,
923 "skills/last30days/scripts/last30days.py",
924 "AI agents",
925 "--discover-shallow",
926 "--mock",
927 ],
928 cwd=REPO_ROOT,
929 capture_output=True,
930 text=True,
931 check=False,
932 )
933 assert result.returncode == 2
934 assert "--discover-shallow only applies to --discover runs" in result.stderr
935
936
937 def test_discovery_cli_rejects_historical_as_of():
938 result = subprocess.run(
939 [
940 sys.executable,
941 "skills/last30days/scripts/last30days.py",
942 "--discover",
943 "AI agents",
944 "--as-of",
945 "2026-06-01",
946 "--mock",
947 ],
948 cwd=REPO_ROOT,
949 capture_output=True,
950 text=True,
951 check=False,
952 )
953
954 assert result.returncode == 2
955 assert "--as-of cannot be used with --discover" in result.stderr
956 assert "current live listings" in result.stderr
957
958
959 def test_discovery_filters_incompatible_default_sources_but_rejects_explicit_only():
960 default_result = subprocess.run(
961 [
962 sys.executable,
963 "skills/last30days/scripts/last30days.py",
964 "--discover",
965 "AI agents",
966 "--mock",
967 "--emit=json",
968 ],
969 cwd=REPO_ROOT,
970 env={**os.environ, "LAST30DAYS_DEFAULT_SEARCH": "reddit,x,youtube,hn"},
971 capture_output=True,
972 text=True,
973 check=False,
974 )
975 assert default_result.returncode == 0, default_result.stderr
976
977 explicit_result = subprocess.run(
978 [
979 sys.executable,
980 "skills/last30days/scripts/last30days.py",
981 "--discover",
982 "AI agents",
983 "--search=youtube",
984 "--mock",
985 ],
986 cwd=REPO_ROOT,
987 capture_output=True,
988 text=True,
989 check=False,
990 )
991 assert explicit_result.returncode == 2
992 assert "unsupported: youtube" in explicit_result.stderr
993
994
995 def test_detect_category_rejects_suffix_false_positives():
996 from lib import categories
997
998 assert categories.detect_category("Dubai agents") is None
999 assert categories.detect_category("Thai agents real estate") is None
1000 assert categories.detect_category("AI agents") == "ai_agent_framework"
1001 assert categories.detect_category("what's new in ai agent frameworks") == "ai_agent_framework"
1002
1003
1004 def test_discovery_engagement_excludes_rank_metadata():
1005 from lib import pipeline, schema
1006
1007 items = [
1008 schema.SourceItem(
1009 item_id=f"digg-{i}", source="digg", title="t", body="b",
1010 url=f"https://di.gg/{i}", published_at="2026-07-05", snippet="s",
1011 engagement={"postCount": 5, "rank": 100 * (i + 1), "rank_score": 0.5},
1012 )
1013 for i in range(3)
1014 ]
1015 totals = pipeline._discovery_engagement(items)
1016 assert totals["digg"]["postCount"] == 15
1017 assert "rank" not in totals["digg"]
1018 assert "rank_score" not in totals["digg"]
1019
1020
1021 def test_domain_matching_preserves_non_plural_anchors():
1022 from lib import pipeline
1023
1024 assert pipeline._matches_discovery_domain("AI bias", "Addressing AI bias in models")
1025 assert pipeline._matches_discovery_domain("supply chain crisis", "The crisis deepens for chip supply")
1026 # Plural matching still works both directions.
1027 assert pipeline._matches_discovery_domain("AI agents", "The best AI agent stacks")
1028
1029
1030 def test_x_fallback_success_is_clean(monkeypatch):
1031 from lib import pipeline, env
1032
1033 calls = []
1034
1035 def fake_fetch(backend, subquery, from_date, to_date, depth, config, warnings=None, deadline=None):
1036 calls.append(backend)
1037 if backend == "bird":
1038 return [], "cookie expired"
1039 return [object()], None
1040
1041 monkeypatch.setattr(pipeline, "_fetch_x_backend", fake_fetch)
1042 monkeypatch.setattr(env, "x_backend_chain", lambda config: ["bird", "xquik"])
1043 plan = pipeline.schema.DiscoveryPlan(
1044 domain="ai agents", category=None, subreddits=[], sources=["x"],
1045 )
1046 items, error = pipeline._fetch_discovery_source(
1047 "x", plan,
1048 from_date="2026-06-11", to_date="2026-07-11", depth="quick",
1049 mock=False, config={},
1050 )
1051 assert error is None
1052 assert len(items) == 1
1053 assert calls == ["bird", "xquik"]
1054
1055
1056 def _digg_envelope(*clusters: dict) -> dict:
1057 return {"results": list(clusters)}
1058
1059
1060 def _digg_cluster(cluster_id: str, title: str, tldr: str = "") -> dict:
1061 return {
1062 "clusterUrlId": cluster_id,
1063 "title": title,
1064 "tldr": tldr,
1065 "rank": 5,
1066 "postCount": 12,
1067 "uniqueAuthors": 8,
1068 }
1069
1070
1071 def test_digg_discovery_drops_off_domain_clusters(monkeypatch):
1072 """Regression: a crypto sweep surfaced AI stories because the Digg
1073 branch (an AI-only leaderboard feed) applied no domain filter."""
1074 envelope = _digg_envelope(
1075 _digg_cluster("c1", "Bitcoin crypto rally accelerates"),
1076 _digg_cluster("c2", "OpenAI ships a new frontier model"),
1077 )
1078 monkeypatch.setattr(pipeline.digg, "search_digg", lambda *a, **k: envelope)
1079 plan = schema.DiscoveryPlan(
1080 domain="crypto", category=None, subreddits=[], sources=["digg"],
1081 )
1082 items, error = pipeline._fetch_discovery_source(
1083 "digg", plan,
1084 from_date="2026-06-11", to_date="2026-07-11", depth="quick",
1085 mock=False, config={},
1086 )
1087 assert error is None
1088 titles = [item["title"] for item in items]
1089 assert titles == ["Bitcoin crypto rally accelerates"]
1090
1091
1092 def test_digg_discovery_keeps_domain_matching_clusters(monkeypatch):
1093 envelope = _digg_envelope(
1094 _digg_cluster("c1", "AI agents reshape support desks"),
1095 _digg_cluster("c2", "The best AI agent stacks compared"),
1096 )
1097 monkeypatch.setattr(pipeline.digg, "search_digg", lambda *a, **k: envelope)
1098 plan = schema.DiscoveryPlan(
1099 domain="AI agents", category=None, subreddits=[], sources=["digg"],
1100 )
1101 items, error = pipeline._fetch_discovery_source(
1102 "digg", plan,
1103 from_date="2026-06-11", to_date="2026-07-11", depth="quick",
1104 mock=False, config={},
1105 )
1106 assert error is None
1107 assert len(items) == 2
1108
1109
1110 def test_digg_discovery_all_filtered_is_clean_no_results(monkeypatch):
1111 envelope = _digg_envelope(
1112 _digg_cluster("c1", "OpenAI ships a new frontier model"),
1113 _digg_cluster("c2", "Anthropic updates its agent SDK"),
1114 )
1115 monkeypatch.setattr(pipeline.digg, "search_digg", lambda *a, **k: envelope)
1116 plan = schema.DiscoveryPlan(
1117 domain="crypto", category=None, subreddits=[], sources=["digg"],
1118 )
1119 items, error = pipeline._fetch_discovery_source(
1120 "digg", plan,
1121 from_date="2026-06-11", to_date="2026-07-11", depth="quick",
1122 mock=False, config={},
1123 )
1124 assert error is None
1125 assert items == []
1126
1127
1128 def test_x_discovery_preserves_producing_backends_own_error(monkeypatch):
1129 """A backend that returns items plus its own error is a partial outcome;
1130 only earlier failed-over backends' errors are observability-only."""
1131 monkeypatch.setattr(
1132 pipeline, "_fetch_x_backend",
1133 lambda *a, **k: ([{"id": "x-1", "title": "t"}], "rate limited after page 1"),
1134 )
1135 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda config: ["bird"])
1136 plan = schema.DiscoveryPlan(
1137 domain="ai agents", category=None, subreddits=[], sources=["x"],
1138 )
1139 items, error = pipeline._fetch_discovery_source(
1140 "x", plan,
1141 from_date="2026-06-11", to_date="2026-07-11", depth="quick",
1142 mock=False, config={},
1143 )
1144 assert len(items) == 1
1145 assert error == "rate limited after page 1"
1146
1147
1148 # --- U6 persistent topic queue: discovery persistence hook + queue CLI -------
1149
1150
1151 def _queue_topic(rank: int, name: str) -> schema.DiscoveryTopic:
1152 return schema.DiscoveryTopic(
1153 rank=rank,
1154 name=name,
1155 why_spiking=f"Listing evidence about {name}.",
1156 momentum="building",
1157 velocity_score=42.5,
1158 sources=["reddit"],
1159 engagement_by_source={"reddit": {"score": 120}},
1160 command=f'/last30days "{name}"',
1161 )
1162
1163
1164 def _queue_report(names: list[str]) -> schema.DiscoveryReport:
1165 return schema.DiscoveryReport(
1166 domain="AI agents",
1167 range_from="2026-06-20",
1168 range_to="2026-07-20",
1169 generated_at="2026-07-20T00:00:00+00:00",
1170 plan=schema.DiscoveryPlan(
1171 domain="AI agents", category=None, subreddits=["all"],
1172 sources=["reddit"],
1173 ),
1174 topics=[_queue_topic(rank, name) for rank, name in enumerate(names, start=1)],
1175 )
1176
1177
1178 def _run_scoped_discover(save_dir, config=None, names=("Gemma 4 chat templates",)):
1179 import datetime as _datetime
1180
1181 parser = cli.build_parser()
1182 args, _extra = parser.parse_known_args(
1183 ["--discover", "AI agents", "--save-dir", str(save_dir), "--save-suffix", os.urandom(4).hex()]
1184 )
1185 report = _queue_report(list(names))
1186 # Stamp a real, distinct run identity per mocked run: generated_at is
1187 # runtime-stamped in reality, and a fixed fixture timestamp would make two
1188 # "separate" runs share a run_ref and trip the retry idempotency guard.
1189 report.generated_at = _datetime.datetime.now(_datetime.timezone.utc).isoformat()
1190 with mock.patch.object(pipeline, "run_discover", return_value=report):
1191 return cli._run_discover(args, dict(config or {}))
1192
1193
1194 def test_discovery_run_records_surfacings_in_scoped_db_only(tmp_path, monkeypatch, capsys):
1195 import store
1196
1197 monkeypatch.setattr(store, "DB_PATH", tmp_path / "global" / "research.db")
1198 save_dir = tmp_path / "client"
1199 save_dir.mkdir()
1200
1201 assert _run_scoped_discover(save_dir) == 0
1202 first = capsys.readouterr().out
1203 assert "**Pipeline:**" not in first # nothing prior to annotate from
1204
1205 scoped_db = save_dir / "research.db"
1206 assert scoped_db.is_file()
1207 assert not (tmp_path / "global" / "research.db").exists()
1208
1209 import sqlite3
1210 conn = sqlite3.connect(scoped_db)
1211 rows = conn.execute(
1212 "SELECT name, surface_count, status FROM discovery_topics"
1213 ).fetchall()
1214 conn.close()
1215 assert rows == [("Gemma 4 chat templates", 1, "surfaced")]
1216
1217
1218 def test_second_discovery_run_annotates_from_prior_state_then_records(tmp_path, capsys):
1219 save_dir = tmp_path / "client"
1220 save_dir.mkdir()
1221
1222 assert _run_scoped_discover(save_dir) == 0
1223 capsys.readouterr()
1224 assert _run_scoped_discover(save_dir) == 0
1225 second = capsys.readouterr().out
1226
1227 # Annotation reflects the state BEFORE this run's own surfacing was
1228 # recorded: one prior surfacing means this appearance is the 2nd.
1229 assert "**Pipeline:** surfaced 2nd time" in second
1230
1231 import sqlite3
1232 conn = sqlite3.connect(save_dir / "research.db")
1233 count = conn.execute(
1234 "SELECT surface_count FROM discovery_topics WHERE name = ?",
1235 ("Gemma 4 chat templates",),
1236 ).fetchone()[0]
1237 conn.close()
1238 assert count == 2
1239
1240
1241 def test_covered_topic_resurfacing_renders_marked_covered(tmp_path, capsys):
1242 import store
1243
1244 save_dir = tmp_path / "client"
1245 save_dir.mkdir()
1246
1247 assert _run_scoped_discover(save_dir) == 0
1248 with store.scoped_db(save_dir / "research.db"):
1249 assert store.mark_discovery_covered(
1250 "Gemma 4 chat templates", as_of="2026-07-20"
1251 ) is not None
1252 capsys.readouterr()
1253
1254 assert _run_scoped_discover(save_dir) == 0
1255 rendered = capsys.readouterr().out
1256 assert "marked covered" in rendered
1257 assert "**Pipeline:** surfaced 2nd time, marked covered" in rendered
1258
1259
1260 def test_queue_opt_out_via_process_env_seam(tmp_path, monkeypatch, capsys):
1261 from lib import env
1262
1263 monkeypatch.setenv("LAST30DAYS_DISCOVERY_QUEUE", "off")
1264 monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "does-not-exist.env")
1265 monkeypatch.chdir(tmp_path)
1266 with mock.patch.object(env, "_load_keychain", return_value={}), \
1267 mock.patch.object(env, "_load_pass", return_value={}):
1268 config = env.get_config()
1269 assert config["LAST30DAYS_DISCOVERY_QUEUE"] == "off"
1270
1271 save_dir = tmp_path / "client"
1272 save_dir.mkdir()
1273 assert _run_scoped_discover(save_dir, config=config) == 0
1274 assert "**Pipeline:**" not in capsys.readouterr().out
1275 assert not (save_dir / "research.db").exists()
1276
1277
1278 def test_queue_opt_out_via_env_file_seam(tmp_path, monkeypatch, capsys):
1279 from lib import env
1280
1281 monkeypatch.delenv("LAST30DAYS_DISCOVERY_QUEUE", raising=False)
1282 env_file = tmp_path / "config.env"
1283 env_file.write_text("LAST30DAYS_DISCOVERY_QUEUE=off\n", encoding="utf-8")
1284 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
1285 monkeypatch.chdir(tmp_path)
1286 with mock.patch.object(env, "_load_keychain", return_value={}), \
1287 mock.patch.object(env, "_load_pass", return_value={}):
1288 config = env.get_config()
1289 assert config["LAST30DAYS_DISCOVERY_QUEUE"] == "off"
1290
1291 save_dir = tmp_path / "client"
1292 save_dir.mkdir()
1293 assert _run_scoped_discover(save_dir, config=config) == 0
1294 assert not (save_dir / "research.db").exists()
1295
1296
1297 def test_discovery_queue_failure_never_crashes_a_finished_run(tmp_path, monkeypatch, capsys):
1298 """P0: a broken research.db (locked, read-only, corrupt) must not destroy
1299 a finished multi-minute pipeline run - the brief still renders (exit 0)
1300 with a stderr warning, and queue fields keep their defaults."""
1301 import sqlite3
1302
1303 import store
1304
1305 def _locked(*_args, **_kwargs):
1306 raise sqlite3.OperationalError("database is locked")
1307
1308 monkeypatch.setattr(store, "record_discovery_surfacing", _locked)
1309 save_dir = tmp_path / "client"
1310 save_dir.mkdir()
1311
1312 assert _run_scoped_discover(save_dir) == 0
1313 captured = capsys.readouterr()
1314 assert "## 1. Gemma 4 chat templates" in captured.out
1315 assert "**Pipeline:**" not in captured.out
1316 assert "[last30days] Warning:" in captured.err
1317 assert "database is locked" in captured.err
1318
1319
1320 def test_sibling_topics_in_same_run_do_not_cross_annotate(tmp_path, capsys):
1321 """Annotations describe the queue state BEFORE this run: two same-anchor
1322 siblings surfaced by ONE run must not fuzzy-match each other's rows and
1323 render a false 'surfaced 2nd time' on first-ever topics."""
1324 import sqlite3
1325
1326 save_dir = tmp_path / "client"
1327 save_dir.mkdir()
1328
1329 assert _run_scoped_discover(
1330 save_dir, names=("Gemma 4 chat templates", "Gemma 4 enterprise")
1331 ) == 0
1332 rendered = capsys.readouterr().out
1333 assert "## 1. Gemma 4 chat templates" in rendered
1334 assert "## 2. Gemma 4 enterprise" in rendered
1335 assert "**Pipeline:**" not in rendered
1336
1337 conn = sqlite3.connect(save_dir / "research.db")
1338 rows = conn.execute(
1339 "SELECT name, surface_count FROM discovery_topics ORDER BY name"
1340 ).fetchall()
1341 conn.close()
1342 assert rows == [("Gemma 4 chat templates", 1), ("Gemma 4 enterprise", 1)]
1343
1344
1345 def test_discovery_mock_run_writes_no_research_db(tmp_path):
1346 """--mock stays 100% side-effect-free: no queue writes, no research.db."""
1347 result = subprocess.run(
1348 [
1349 sys.executable,
1350 "skills/last30days/scripts/last30days.py",
1351 "--discover",
1352 "AI agents",
1353 "--mock",
1354 "--save-dir",
1355 str(tmp_path),
1356 ],
1357 cwd=REPO_ROOT,
1358 capture_output=True,
1359 text=True,
1360 check=False,
1361 )
1362 assert result.returncode == 0, result.stderr
1363 assert not (tmp_path / "research.db").exists()
1364
1365
1366 def test_queue_list_shows_uncovered_only_by_default(tmp_path, monkeypatch, capsys):
1367 import store
1368
1369 save_dir = tmp_path / "client"
1370 save_dir.mkdir()
1371 with store.scoped_db(save_dir / "research.db"):
1372 store.record_discovery_surfacing(
1373 "Gemma 4 chat templates", domain="AI agents", run_ref="r1", as_of="2026-07-19",
1374 )
1375 store.record_discovery_surfacing(
1376 "OpenAI Agent SDK", domain="AI agents", run_ref="r1", as_of="2026-07-20",
1377 )
1378 store.mark_discovery_covered("OpenAI Agent SDK", as_of="2026-07-20")
1379
1380 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
1381 monkeypatch.setattr(
1382 sys, "argv", ["last30days.py", "queue", "list", "--save-dir", str(save_dir)]
1383 )
1384 assert cli.main() == 0
1385 out = capsys.readouterr().out
1386 assert "Gemma 4 chat templates" in out
1387 assert "OpenAI Agent SDK" not in out
1388 for column in ("name", "domain", "surface_count", "last_surfaced", "status"):
1389 assert column in out
1390
1391
1392 def test_queue_list_empty_db_reports_no_recorded_runs(tmp_path, monkeypatch, capsys):
1393 """A db that exists but has zero discovery rows (e.g. created via --store
1394 by a topic run) must not claim every topic is covered."""
1395 import store
1396
1397 save_dir = tmp_path / "client"
1398 save_dir.mkdir()
1399 store.init_db(save_dir / "research.db")
1400
1401 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
1402 monkeypatch.setattr(
1403 sys, "argv", ["last30days.py", "queue", "list", "--save-dir", str(save_dir)]
1404 )
1405 assert cli.main() == 0
1406 out = capsys.readouterr().out
1407 assert "no discovery run has recorded topics yet" in out
1408 assert "marked covered" not in out
1409
1410
1411 def test_queue_cover_marks_topic_covered(tmp_path, monkeypatch, capsys):
1412 import sqlite3
1413
1414 import store
1415
1416 save_dir = tmp_path / "client"
1417 save_dir.mkdir()
1418 with store.scoped_db(save_dir / "research.db"):
1419 store.record_discovery_surfacing(
1420 "Gemma 4 chat templates", domain="AI agents", run_ref="r1", as_of="2026-07-19",
1421 )
1422
1423 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
1424 monkeypatch.setattr(
1425 sys,
1426 "argv",
1427 ["last30days.py", "queue", "cover", "Gemma 4 chat templates", "--save-dir", str(save_dir)],
1428 )
1429 assert cli.main() == 0
1430
1431 conn = sqlite3.connect(save_dir / "research.db")
1432 status, covered_at = conn.execute(
1433 "SELECT status, covered_at FROM discovery_topics WHERE name = ?",
1434 ("Gemma 4 chat templates",),
1435 ).fetchone()
1436 conn.close()
1437 assert status == "covered"
1438 assert covered_at
1439
1440
1441 def test_queue_cover_unknown_name_exits_2_with_stderr(tmp_path, monkeypatch, capsys):
1442 import store
1443
1444 save_dir = tmp_path / "client"
1445 save_dir.mkdir()
1446 with store.scoped_db(save_dir / "research.db"):
1447 store.record_discovery_surfacing(
1448 "Gemma 4 chat templates", domain="AI agents", run_ref="r1", as_of="2026-07-19",
1449 )
1450
1451 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
1452 monkeypatch.setattr(
1453 sys,
1454 "argv",
1455 ["last30days.py", "queue", "cover", "No Such Topic", "--save-dir", str(save_dir)],
1456 )
1457 assert cli.main() == 2
1458 err = capsys.readouterr().err
1459 assert "No Such Topic" in err
1460
1461
1462 def test_queue_cover_cli_unknown_name_subprocess_exit_code(tmp_path):
1463 result = subprocess.run(
1464 [
1465 sys.executable,
1466 "skills/last30days/scripts/last30days.py",
1467 "queue",
1468 "cover",
1469 "No Such Topic",
1470 "--save-dir",
1471 str(tmp_path),
1472 ],
1473 cwd=REPO_ROOT,
1474 capture_output=True,
1475 text=True,
1476 check=False,
1477 )
1478 assert result.returncode == 2
1479 assert "No Such Topic" in result.stderr
1480
1481
1482 def test_discovery_exits_when_configured_sources_have_no_discovery_feed(monkeypatch, capsys):
1483 """A configured source boundary must hold: never silently widen a sweep
1484 to feeds the user filtered out."""
1485 monkeypatch.setattr(
1486 cli.env, "get_config", lambda **_kwargs: {"LAST30DAYS_DEFAULT_SEARCH": "youtube"}
1487 )
1488 monkeypatch.setattr(sys, "argv", ["last30days.py", "--discover", "AI agents", "--mock"])
1489 with mock.patch.object(pipeline, "run_discover") as run:
1490 assert cli.main() == 2
1491
1492 run.assert_not_called()
1493 err = capsys.readouterr().err
1494 assert "no discovery-capable sources" in err
1495 assert "reddit" in err
1496
1497
1498 # --- U2: three-command protocol CLI surface (flags, scoping, dispatch) ---
1499
1500
1501 def _run_protocol_cli(argv: list[str], env_overrides: dict[str, str] | None = None):
1502 """Run the real CLI entry point; env overrides layer onto the test env."""
1503 return subprocess.run(
1504 [sys.executable, "skills/last30days/scripts/last30days.py", *argv],
1505 cwd=REPO_ROOT,
1506 capture_output=True,
1507 text=True,
1508 check=False,
1509 env={**os.environ, **(env_overrides or {})},
1510 )
1511
1512
1513 @pytest.mark.parametrize(
1514 ("argv", "fragment"),
1515 [
1516 # Orphans: protocol flags without --discover reject loudly (never a
1517 # silent no-op into a normal research run - same rule as
1518 # --discover-shallow).
1519 (
1520 ["AI agents", "--nominate-only", "--mock"],
1521 "--nominate-only only applies to --discover runs",
1522 ),
1523 (
1524 ["AI agents", "--judgments", "judgments.json", "--mock"],
1525 "--judgments only applies to --discover runs",
1526 ),
1527 (
1528 ["AI agents", "--finalize", "--mock"],
1529 "--finalize only applies to --discover runs",
1530 ),
1531 (
1532 ["AI agents", "--angles", "angles.json", "--mock"],
1533 "--angles only applies to --discover --finalize runs",
1534 ),
1535 # --angles is a --finalize modifier even when --discover is present.
1536 (
1537 ["--discover", "AI agents", "--angles", "angles.json", "--mock"],
1538 "--angles only applies to --discover --finalize runs",
1539 ),
1540 # The three legs are mutually exclusive: one leg per invocation.
1541 (
1542 ["--discover", "AI agents", "--nominate-only", "--judgments", "j.json"],
1543 "--nominate-only and --judgments are mutually exclusive",
1544 ),
1545 (
1546 ["--discover", "AI agents", "--nominate-only", "--finalize"],
1547 "--nominate-only and --finalize are mutually exclusive",
1548 ),
1549 (
1550 ["--discover", "AI agents", "--judgments", "j.json", "--finalize"],
1551 "--judgments and --finalize are mutually exclusive",
1552 ),
1553 ],
1554 )
1555 def test_discovery_cli_protocol_flag_combinations_exit_2(argv, fragment):
1556 """Every orphan/mutual-exclusion combination names the offending flags."""
1557 result = _run_protocol_cli(argv)
1558 assert result.returncode == 2, result.stderr
1559 assert fragment in result.stderr
1560
1561
1562 @pytest.mark.parametrize(
1563 "leg_argv",
1564 [
1565 ["--nominate-only"],
1566 ["--judgments", "judgments.json"],
1567 ["--finalize"],
1568 ],
1569 )
1570 def test_discovery_cli_mock_protocol_leg_requires_save_dir(leg_argv):
1571 """--mock protocol legs without --save-dir would write handoff state into
1572 the real config dir; reject before any leg runs. LAST30DAYS_MEMORY_DIR is
1573 pinned empty so a dev machine's save-dir fallback can't mask the check."""
1574 result = _run_protocol_cli(
1575 ["--discover", "AI agents", "--mock", *leg_argv],
1576 env_overrides={"LAST30DAYS_MEMORY_DIR": ""},
1577 )
1578 assert result.returncode == 2, result.stderr
1579 assert "mock protocol legs require --save-dir to stay side-effect-free" in result.stderr
1580
1581
1582 def test_discovery_cli_finalize_flag_reaches_leg_3(tmp_path):
1583 """With --save-dir, --finalize routes to the real leg 3 (formerly the U5
1584 stub): an empty state dir is a contract failure naming the pending report
1585 and the resume-leg remedy - proof the dispatch reached the finalize body."""
1586 result = _run_protocol_cli(
1587 ["--discover", "AI agents", "--mock", "--save-dir", str(tmp_path), "--finalize"],
1588 )
1589 assert result.returncode == 2, result.stderr
1590 assert "No pending discovery report found" in result.stderr
1591 assert str(tmp_path / discovery_handoff.PENDING_REPORT_FILENAME) in result.stderr
1592 assert "--discover --judgments" in result.stderr
1593
1594
1595 # --- U3 leg 1: --discover --nominate-only (sweep, bundle, digest) -------------
1596
1597
1598 def _run_nominate_only(save_dir, *extra_argv):
1599 return _run_protocol_cli(
1600 [
1601 "--discover", "AI agents", "--mock",
1602 "--save-dir", str(save_dir), "--nominate-only", *extra_argv,
1603 ],
1604 # Pin the default-search seam empty so a dev machine's configured
1605 # boundary cannot leak into the bundle-context assertions.
1606 env_overrides={"LAST30DAYS_DEFAULT_SEARCH": ""},
1607 )
1608
1609
1610 def test_discovery_cli_nominate_only_writes_bundle_and_digest(tmp_path):
1611 """Leg 1 exits 0, writes the nominations bundle under the save dir, and
1612 prints the host digest naming the bundle path with one line per
1613 nomination - no judging, enrichment, floor, or queue on this leg."""
1614 result = _run_nominate_only(tmp_path)
1615 assert result.returncode == 0, result.stderr
1616 bundle_path = tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME
1617 assert bundle_path.is_file()
1618 payload = json.loads(bundle_path.read_text(encoding="utf-8"))
1619 assert payload["kind"] == schema.DISCOVERY_NOMINATIONS_KIND
1620 assert payload["schema_version"] == schema.DISCOVERY_NOMINATIONS_SCHEMA_VERSION
1621 assert payload["domain"] == "AI agents"
1622 assert payload["tier"] == "deep"
1623 # Leg-1 invocation context rides along for leg 2.
1624 assert payload["context"]["lookback_days"] == 30
1625 assert payload["context"]["requested_sources"] is None
1626 assert payload["context"]["enrichment_source_boundary"] is None
1627 # Momentum window matches the sweep dates (computed the same day).
1628 assert (payload["from_date"], payload["to_date"]) == dates.get_date_range(30)
1629 assert payload["nominations"]
1630 for row in payload["nominations"]:
1631 # Heuristic fallbacks: no provider ran, so the nomination's own
1632 # name/junk ARE the topic_shape heuristics.
1633 assert row["heuristic_name"] == row["nomination"]["name"]
1634 assert row["heuristic_junk"] == row["nomination"]["junk_shape"]
1635 assert row["sources"] == sorted({
1636 item["source"] for item in row["nomination"]["items"]
1637 })
1638 # Digest on stdout: names the bundle file, instructs reading it before
1639 # judging, and carries exactly one line per nomination id.
1640 assert str(bundle_path) in result.stdout
1641 assert "before judging" in result.stdout
1642 for row in payload["nominations"]:
1643 matching = [
1644 line for line in result.stdout.splitlines()
1645 if line.startswith(f"{row['id']} | ")
1646 ]
1647 assert len(matching) == 1
1648 # No queue writes on leg 1.
1649 assert not (tmp_path / "research.db").exists()
1650
1651
1652 def test_discovery_cli_nominate_only_source_boundary_rides_into_bundle(tmp_path):
1653 result = _run_nominate_only(tmp_path, "--search", "reddit")
1654 assert result.returncode == 0, result.stderr
1655 payload = json.loads(
1656 (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
1657 encoding="utf-8"
1658 )
1659 )
1660 assert payload["context"]["requested_sources"] == ["reddit"]
1661 assert payload["context"]["enrichment_source_boundary"] == ["reddit"]
1662 for row in payload["nominations"]:
1663 assert row["sources"] == ["reddit"]
1664
1665
1666 def test_discovery_cli_nominate_only_mock_is_deterministic(tmp_path):
1667 """Two mock leg-1 runs agree on every nomination row and digest line
1668 (only bundle_id/generated_at/path may differ)."""
1669 def run_leg(save_dir):
1670 save_dir.mkdir()
1671 result = _run_nominate_only(save_dir)
1672 assert result.returncode == 0, result.stderr
1673 payload = json.loads(
1674 (save_dir / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
1675 encoding="utf-8"
1676 )
1677 )
1678 return payload, result.stdout
1679
1680 first_payload, first_out = run_leg(tmp_path / "a")
1681 second_payload, second_out = run_leg(tmp_path / "b")
1682 assert first_payload["nominations"] == second_payload["nominations"]
1683 assert (first_payload["from_date"], first_payload["to_date"]) == (
1684 second_payload["from_date"], second_payload["to_date"],
1685 )
1686 ids = [row["id"] for row in first_payload["nominations"]]
1687
1688 def digest_lines(out: str) -> list[str]:
1689 return [
1690 line for line in out.splitlines()
1691 if any(line.startswith(f"{row_id} | ") for row_id in ids)
1692 ]
1693
1694 assert digest_lines(first_out) == digest_lines(second_out)
1695
1696
1697 def test_discovery_cli_nominate_only_shallow_marks_tier(tmp_path):
1698 result = _run_nominate_only(tmp_path, "--discover-shallow")
1699 assert result.returncode == 0, result.stderr
1700 payload = json.loads(
1701 (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
1702 encoding="utf-8"
1703 )
1704 )
1705 assert payload["tier"] == "shallow"
1706
1707
1708 def test_discovery_cli_nominate_only_zero_nominations_nothing_solid(tmp_path, capsys):
1709 """An empty sweep short-circuits to the existing nothing-solid brief:
1710 exit 0, NO bundle file, nothing for later legs."""
1711 parser = cli.build_parser()
1712 args, _extra = parser.parse_known_args(
1713 ["--discover", "AI agents", "--save-dir", str(tmp_path), "--nominate-only"]
1714 )
1715
1716 def empty_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
1717 return [], None
1718
1719 with mock.patch.object(
1720 pipeline, "available_sources", return_value=["hackernews"],
1721 ), mock.patch.object(
1722 pipeline, "_fetch_discovery_source", side_effect=empty_fetch,
1723 ), mock.patch.object(pipeline, "enrich_nominations") as enrich:
1724 assert cli._run_discover_protocol_leg(args, {}) == 0
1725
1726 enrich.assert_not_called()
1727 out = capsys.readouterr().out
1728 assert "Nothing solid this window." in out
1729 assert not (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).exists()
1730 assert not (tmp_path / "research.db").exists()
1731
1732
1733 def test_discovery_cli_nominate_only_skips_enrichment_providers_and_queue(tmp_path):
1734 """Spies on the leg-1 boundary: enrichment, provider resolution, and the
1735 queue hook are never touched, and no research.db appears."""
1736 parser = cli.build_parser()
1737 args, _extra = parser.parse_known_args(
1738 ["--discover", "AI agents", "--mock", "--save-dir", str(tmp_path), "--nominate-only"]
1739 )
1740 with mock.patch.object(pipeline, "enrich_nominations") as enrich, \
1741 mock.patch.object(pipeline.providers, "resolve_runtime") as resolve, \
1742 mock.patch.object(cli, "_annotate_and_record_discovery_queue") as queue_hook:
1743 assert cli._run_discover_protocol_leg(args, {}) == 0
1744 enrich.assert_not_called()
1745 resolve.assert_not_called()
1746 queue_hook.assert_not_called()
1747 assert (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).is_file()
1748 assert not (tmp_path / "research.db").exists()
1749
1750
1751 def test_discover_handoff_state_dir_scopes_to_save_dir_then_config(tmp_path, monkeypatch):
1752 """One resolver for all three legs: save dir when given, else config dir
1753 (the same base the report cache uses)."""
1754 save_dir = tmp_path / "client"
1755 resolved = cli._discover_handoff_state_dir(argparse.Namespace(save_dir=str(save_dir)))
1756 assert resolved == save_dir.resolve()
1757
1758 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path / "config")
1759 resolved = cli._discover_handoff_state_dir(argparse.Namespace(save_dir=None))
1760 assert resolved == tmp_path / "config"
1761
1762
1763 def test_discovery_protocol_dispatch_maps_contract_error_to_exit_2(monkeypatch, capsys):
1764 """HandoffContractError raised inside any leg body maps to stderr + exit 2
1765 at the dispatch layer, so U3-U5 leg bodies can raise it freely."""
1766
1767 def _stale_bundle(_args, _config):
1768 raise discovery_handoff.HandoffContractError(
1769 "Nominations bundle is stale; run a fresh re-sweep."
1770 )
1771
1772 monkeypatch.setattr(cli, "_run_discover_nominate", _stale_bundle)
1773 args = argparse.Namespace(nominate_only=True, judgments=None, finalize=False)
1774 assert cli._run_discover_protocol_leg(args, {}) == 2
1775 err = capsys.readouterr().err
1776 assert "Nominations bundle is stale; run a fresh re-sweep." in err
1777
1778
1779 # --- U4 leg 2: --discover --judgments (resume, enrich, pending report) --------
1780
1781
1782 def _leg1_bundle_payload(save_dir) -> dict:
1783 """Run leg 1 in-process against the save dir and return the bundle JSON."""
1784 parser = cli.build_parser()
1785 args, _extra = parser.parse_known_args(
1786 ["--discover", "AI agents", "--mock", "--save-dir", str(save_dir),
1787 "--nominate-only"]
1788 )
1789 assert cli._run_discover_protocol_leg(args, {}) == 0
1790 return json.loads(
1791 (Path(save_dir) / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
1792 encoding="utf-8"
1793 )
1794 )
1795
1796
1797 def _run_leg2(save_dir, judgments_payload, config=None) -> int:
1798 judgments_path = Path(save_dir) / "judgments.json"
1799 judgments_path.write_text(json.dumps(judgments_payload), encoding="utf-8")
1800 parser = cli.build_parser()
1801 args, _extra = parser.parse_known_args([
1802 "--discover", "AI agents", "--mock", "--save-dir", str(save_dir),
1803 "--judgments", str(judgments_path),
1804 ])
1805 return cli._run_discover_protocol_leg(args, dict(config or {}))
1806
1807
1808 def _rich_enrichment_report(topic: str) -> schema.Report:
1809 """A per-topic fake enrichment corpus with topic-unique URLs so distinct
1810 topics never trip the same-story fold."""
1811 import datetime as _datetime
1812
1813 slug = "".join(ch if ch.isalnum() else "-" for ch in topic.lower())
1814 published = (_datetime.date.today() - _datetime.timedelta(days=1)).isoformat()
1815 items = {
1816 "reddit": [schema.SourceItem(
1817 item_id=f"r-{slug}", source="reddit", title=topic, body=topic,
1818 url=f"https://reddit.com/r/x/{slug}", published_at=published,
1819 engagement={"score": 800, "num_comments": 300}, snippet=topic,
1820 )],
1821 "hackernews": [schema.SourceItem(
1822 item_id=f"h-{slug}", source="hackernews", title=topic, body=topic,
1823 url=f"https://example.com/{slug}", published_at=published,
1824 engagement={"points": 400, "comments": 150}, snippet=topic,
1825 )],
1826 }
1827 return schema.Report(
1828 topic=topic,
1829 range_from="2026-06-10", range_to="2026-07-10",
1830 generated_at="2026-07-10T00:00:00+00:00",
1831 provider_runtime=schema.ProviderRuntime(
1832 reasoning_provider="none",
1833 planner_model="deterministic",
1834 rerank_model="deterministic",
1835 ),
1836 query_plan=schema.QueryPlan(
1837 intent="factual", freshness_mode="balanced_recent",
1838 cluster_mode="none", raw_topic=topic, subqueries=[],
1839 source_weights={},
1840 ),
1841 clusters=[], ranked_candidates=[],
1842 items_by_source=items, errors_by_source={},
1843 )
1844
1845
1846 def test_discovery_cli_resume_pending_report_round_trip(tmp_path, capsys):
1847 """Scenario 8: leg 2 persists ONE pending report - bundle_id binding, a
1848 fresh generated_at (the leg-3 TTL clock), the queue's run_ref format, the
1849 full report with host names and contiguous ranks, and angle inputs keyed
1850 by surviving nomination ids - and prints the angle inputs plus the
1851 finalize instructions. No queue writes, no artifact saves."""
1852 from lib import env as lib_env
1853
1854 bundle_payload = _leg1_bundle_payload(tmp_path)
1855 capsys.readouterr()
1856 ids = [row["id"] for row in bundle_payload["nominations"]]
1857 assert "n1" in ids
1858 judgments = {
1859 "bundle_id": bundle_payload["bundle_id"],
1860 "judgments": [
1861 {"id": "n1", "name": "Renamed Topic One", "junk": False,
1862 "worthiness": 90},
1863 ],
1864 }
1865
1866 def fake_run(*, topic, **_kwargs):
1867 return _rich_enrichment_report(topic)
1868
1869 with mock.patch.object(pipeline, "run", side_effect=fake_run):
1870 assert _run_leg2(tmp_path, judgments) == 0
1871 out = capsys.readouterr().out
1872
1873 pending_path = tmp_path / discovery_handoff.PENDING_REPORT_FILENAME
1874 assert pending_path.is_file()
1875 payload = json.loads(pending_path.read_text(encoding="utf-8"))
1876 assert payload["bundle_id"] == bundle_payload["bundle_id"]
1877 # Fresh TTL clock: generated_at is the resume run's, not the sweep's.
1878 assert lib_env.is_timestamp_fresh(payload["generated_at"], 3600)
1879 assert payload["generated_at"] != bundle_payload["generated_at"]
1880 assert payload["run_ref"] == f"discover:AI agents:{payload['generated_at']}"
1881
1882 report_dict = payload["report"]
1883 topic_names = [topic["name"] for topic in report_dict["topics"]]
1884 assert "Renamed Topic One" in topic_names
1885 assert [topic["rank"] for topic in report_dict["topics"]] == list(
1886 range(1, len(topic_names) + 1)
1887 )
1888 assert all(topic["evidence_urls"] for topic in report_dict["topics"])
1889
1890 angle_inputs = payload["angle_inputs"]
1891 assert angle_inputs
1892 assert set(angle_inputs) <= set(ids)
1893 assert angle_inputs["n1"]["name"] == "Renamed Topic One"
1894 for entry in angle_inputs.values():
1895 assert set(entry) == {"name", "titles", "top_comment", "engagement"}
1896
1897 # stdout: angle inputs + instruction block with the bundle_id echo.
1898 assert "Renamed Topic One" in out
1899 assert bundle_payload["bundle_id"] in out
1900 assert "--discover --finalize" in out
1901 # No queue writes and no artifact saves on this leg.
1902 assert not (tmp_path / "research.db").exists()
1903 assert not list(tmp_path.glob("*discover-raw*"))
1904
1905
1906 def test_discovery_cli_resume_zero_survivors_renders_nothing_solid(tmp_path, capsys):
1907 """Scenario 9: every nomination host-junked - leg 2 renders the honest
1908 nothing-solid brief itself, exits 0, and leaves NO pending file (there is
1909 nothing for leg 3 to finalize)."""
1910 bundle_payload = _leg1_bundle_payload(tmp_path)
1911 capsys.readouterr()
1912 judgments = {
1913 "bundle_id": bundle_payload["bundle_id"],
1914 "judgments": [
1915 {"id": row["id"], "junk": True}
1916 for row in bundle_payload["nominations"]
1917 ],
1918 }
1919 with mock.patch.object(pipeline, "enrich_nominations") as enrich:
1920 assert _run_leg2(tmp_path, judgments) == 0
1921 enrich.assert_not_called()
1922 out = capsys.readouterr().out
1923 assert "Nothing solid this window." in out
1924 assert not (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).exists()
1925 assert not (tmp_path / "research.db").exists()
1926
1927
1928 def test_discovery_cli_resume_never_resolves_providers_or_queue(tmp_path, capsys):
1929 """Leg 2 has no LLM pass (the host IS the judge) and no queue write (the
1930 queue belongs to leg 3): provider resolution and the queue hook are never
1931 touched on the resume leg."""
1932 bundle_payload = _leg1_bundle_payload(tmp_path)
1933 capsys.readouterr()
1934 judgments = {"bundle_id": bundle_payload["bundle_id"], "judgments": []}
1935
1936 def fake_run(*, topic, **_kwargs):
1937 return _rich_enrichment_report(topic)
1938
1939 with mock.patch.object(pipeline, "run", side_effect=fake_run), \
1940 mock.patch.object(pipeline.providers, "resolve_runtime") as resolve, \
1941 mock.patch.object(cli, "_annotate_and_record_discovery_queue") as queue_hook:
1942 assert _run_leg2(tmp_path, judgments) == 0
1943
1944 resolve.assert_not_called()
1945 queue_hook.assert_not_called()
1946
1947
1948 def test_discovery_cli_resume_without_bundle_exits_2(tmp_path):
1949 """A resume against an empty state dir is a contract failure: exit 2 with
1950 the searched locations and the re-sweep remedy on stderr."""
1951 judgments_path = tmp_path / "judgments.json"
1952 judgments_path.write_text(
1953 json.dumps({"bundle_id": "deadbeef", "judgments": []}), encoding="utf-8"
1954 )
1955 result = _run_protocol_cli([
1956 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
1957 "--judgments", str(judgments_path),
1958 ])
1959 assert result.returncode == 2, result.stderr
1960 assert "No discovery nominations bundle found" in result.stderr
1961 assert "--discover --nominate-only" in result.stderr
1962
1963
1964 def test_discovery_cli_resume_full_mock_offline_is_deterministic(tmp_path):
1965 """Scenario 10: a full mock leg 2 (mock judgments against a mock leg-1
1966 bundle, --save-dir scoped) runs offline end to end - exit 0, a pending
1967 report bound to the bundle, deterministic angle inputs across two resumes,
1968 and zero queue writes."""
1969 leg1 = _run_nominate_only(tmp_path)
1970 assert leg1.returncode == 0, leg1.stderr
1971 bundle_payload = json.loads(
1972 (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
1973 encoding="utf-8"
1974 )
1975 )
1976 rows = bundle_payload["nominations"]
1977 keep = [row["id"] for row in rows if not row["heuristic_junk"]][:2]
1978 assert keep, "mock sweep should nominate at least one non-junk topic"
1979 judgments_path = tmp_path / "judgments.json"
1980 judgments_path.write_text(json.dumps({
1981 "bundle_id": bundle_payload["bundle_id"],
1982 "judgments": [
1983 {"id": keep[0], "name": "Renamed Mock Topic", "junk": False,
1984 "worthiness": 90},
1985 *[
1986 {"id": row["id"], "junk": True}
1987 for row in rows if row["id"] not in keep
1988 ],
1989 ],
1990 }), encoding="utf-8")
1991
1992 def run_leg2():
1993 return _run_protocol_cli(
1994 [
1995 "--discover", "AI agents", "--mock",
1996 "--save-dir", str(tmp_path),
1997 "--judgments", str(judgments_path),
1998 ],
1999 env_overrides={"LAST30DAYS_DEFAULT_SEARCH": ""},
2000 )
2001
2002 first = run_leg2()
2003 assert first.returncode == 0, first.stderr
2004 pending_path = tmp_path / discovery_handoff.PENDING_REPORT_FILENAME
2005 first_payload = json.loads(pending_path.read_text(encoding="utf-8"))
2006 second = run_leg2()
2007 assert second.returncode == 0, second.stderr
2008 second_payload = json.loads(pending_path.read_text(encoding="utf-8"))
2009
2010 assert first_payload["bundle_id"] == bundle_payload["bundle_id"]
2011 assert set(first_payload["angle_inputs"]) <= set(keep)
2012 # Deterministic: two mock resumes agree on every angle input.
2013 assert first_payload["angle_inputs"] == second_payload["angle_inputs"]
2014 assert "Renamed Mock Topic" in first.stdout
2015 assert bundle_payload["bundle_id"] in first.stdout
2016 assert "--discover --finalize" in first.stdout
2017 assert not (tmp_path / "research.db").exists()
2018
2019
2020 # --- U5 leg 3: --discover --finalize (angles, render, artifacts, queue) --------
2021
2022
2023 def _fresh_generated_at() -> str:
2024 import datetime as _datetime
2025
2026 return _datetime.datetime.now(_datetime.timezone.utc).isoformat()
2027
2028
2029 def _write_pending_report(
2030 save_dir,
2031 names=("Gemma 4 chat templates",),
2032 bundle_id="cafe1234cafe1234",
2033 ) -> dict:
2034 """Write a synthetic (schema-true) leg-2 pending report into save_dir and
2035 return its payload. Mirrors the exact U4 writer shape: full schema round
2036 trip of the report plus angle_inputs keyed by surviving nomination id."""
2037 generated_at = _fresh_generated_at()
2038 report = _queue_report(list(names))
2039 report.generated_at = generated_at
2040 payload = {
2041 "kind": schema.DISCOVERY_PENDING_KIND,
2042 "schema_version": schema.DISCOVERY_PENDING_SCHEMA_VERSION,
2043 "bundle_id": bundle_id,
2044 "generated_at": generated_at,
2045 "run_ref": f"discover:{report.domain or 'trending'}:{generated_at}",
2046 "report": schema.to_dict(report),
2047 "angle_inputs": {
2048 f"n{position}": {
2049 "name": name,
2050 "titles": f"Listing title about {name}",
2051 "top_comment": "",
2052 "engagement": "120 native interactions across reddit",
2053 }
2054 for position, name in enumerate(names, start=1)
2055 },
2056 }
2057 save_dir = Path(save_dir)
2058 save_dir.mkdir(parents=True, exist_ok=True)
2059 (save_dir / discovery_handoff.PENDING_REPORT_FILENAME).write_text(
2060 json.dumps(payload), encoding="utf-8"
2061 )
2062 return payload
2063
2064
2065 def _write_angles_file(save_dir, bundle_id, rows) -> Path:
2066 path = Path(save_dir) / "angles.json"
2067 path.write_text(
2068 json.dumps({"bundle_id": bundle_id, "angles": rows}), encoding="utf-8"
2069 )
2070 return path
2071
2072
2073 def _run_leg3(save_dir, config=None, *extra_argv) -> int:
2074 """Run leg 3 in-process, non-mock (finalize is offline by design)."""
2075 parser = cli.build_parser()
2076 args, _extra = parser.parse_known_args([
2077 "--discover", "AI agents", "--save-dir", str(save_dir),
2078 "--save-suffix", os.urandom(4).hex(), "--finalize", *extra_argv,
2079 ])
2080 return cli._run_discover_protocol_leg(args, dict(config or {}))
2081
2082
2083 def test_discovery_report_round_trips_through_schema_dicts():
2084 """to_dict -> JSON -> discovery_report_from_dict is lossless: the exact
2085 round trip leg 3 performs on the pending report."""
2086 import dataclasses
2087
2088 original = _queue_report(["Gemma 4 chat templates"])
2089 original.topics[0] = dataclasses.replace(
2090 original.topics[0],
2091 top_comment='"Sharp take" - u/dev (1,200 votes)',
2092 corroboration_count=2,
2093 evidence_urls=["https://reddit.com/r/x/1"],
2094 )
2095 payload = json.loads(json.dumps(schema.to_dict(original)))
2096 assert schema.discovery_report_from_dict(payload) == original
2097
2098
2099 def test_discovery_cli_finalize_applies_host_angles_and_records_queue(tmp_path, capsys):
2100 """Scenario: finalize with an angles file renders host angle lines
2101 verbatim, saves the discovery artifact, and records the queue under the
2102 LEG-2 run identity (the pending report's run_ref)."""
2103 import sqlite3 as _sqlite3
2104
2105 pending = _write_pending_report(tmp_path)
2106 angles_path = _write_angles_file(tmp_path, pending["bundle_id"], [
2107 {"id": "n1",
2108 "podcast": "Is Gemma 4 chat templating a lock-in play?",
2109 "x_article": "Five Gemma 4 template changes worth writing about."},
2110 ])
2111
2112 assert _run_leg3(tmp_path, None, "--angles", str(angles_path)) == 0
2113 out = capsys.readouterr().out
2114 assert "## 1. Gemma 4 chat templates" in out
2115 assert (
2116 "**Podcast angle:** Is Gemma 4 chat templating a lock-in play?" in out
2117 )
2118 assert (
2119 "**X article angle:** Five Gemma 4 template changes worth writing about."
2120 in out
2121 )
2122 # First-ever topic: nothing prior to annotate from.
2123 assert "**Pipeline:**" not in out
2124 # Artifact saved via the existing O_EXCL discovery path.
2125 assert list(tmp_path.glob("*discover-raw*"))
2126 # Queue row recorded under the pending report's run_ref.
2127 conn = _sqlite3.connect(tmp_path / "research.db")
2128 conn.row_factory = _sqlite3.Row
2129 row = dict(conn.execute("SELECT * FROM discovery_topics").fetchone())
2130 conn.close()
2131 assert row["name"] == "Gemma 4 chat templates"
2132 assert row["surface_count"] == 1
2133 assert row["last_run_ref"] == pending["run_ref"]
2134 # Pending file left in place: idempotent retries are a design requirement.
2135 assert (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).is_file()
2136
2137
2138 def test_discovery_cli_finalize_without_angles_renders_angle_less_brief(tmp_path, capsys):
2139 """Omitting --angles is legal: the brief ships without angle lines and the
2140 queue still records the surfacing."""
2141 _write_pending_report(tmp_path)
2142
2143 assert _run_leg3(tmp_path) == 0
2144 out = capsys.readouterr().out
2145 assert "## 1. Gemma 4 chat templates" in out
2146 assert "**Podcast angle:**" not in out
2147 assert "**X article angle:**" not in out
2148
2149 import sqlite3 as _sqlite3
2150 conn = _sqlite3.connect(tmp_path / "research.db")
2151 rows = conn.execute(
2152 "SELECT name, surface_count FROM discovery_topics"
2153 ).fetchall()
2154 conn.close()
2155 assert rows == [("Gemma 4 chat templates", 1)]
2156
2157
2158 def test_discovery_cli_double_finalize_same_run_ref_counts_once(tmp_path, capsys):
2159 """AE6: a finalize retry (same pending report, same run_ref) neither
2160 double-counts the surfacing nor annotates the retry as a resurfacing -
2161 the rendered brief is stable across retries."""
2162 import sqlite3 as _sqlite3
2163
2164 _write_pending_report(tmp_path)
2165
2166 assert _run_leg3(tmp_path) == 0
2167 first = capsys.readouterr().out
2168 assert _run_leg3(tmp_path) == 0
2169 second = capsys.readouterr().out
2170
2171 assert "## 1. Gemma 4 chat templates" in second
2172 # The retry must not describe itself as a 2nd surfacing.
2173 assert "**Pipeline:**" not in second
2174 assert first == second
2175
2176 conn = _sqlite3.connect(tmp_path / "research.db")
2177 row = conn.execute(
2178 "SELECT surface_count, covered_at FROM discovery_topics"
2179 ).fetchone()
2180 conn.close()
2181 assert row == (1, None)
2182
2183
2184 def test_discovery_cli_finalize_retry_with_prior_history_renders_identically(tmp_path, capsys):
2185 """F3: a finalize retry over a topic WITH pre-run history reconstructs
2186 the pre-run queue state (surface_count minus this run's own recording)
2187 instead of nulling the prior - the retry renders the same 'surfaced Nth
2188 time' line as the first attempt."""
2189 import sqlite3 as _sqlite3
2190
2191 import store
2192
2193 with store.scoped_db(tmp_path / "research.db"):
2194 store.record_discovery_surfacing(
2195 "Gemma 4 chat templates", domain="AI agents", run_ref="run-old",
2196 as_of="2026-07-13",
2197 )
2198 _write_pending_report(tmp_path)
2199
2200 assert _run_leg3(tmp_path) == 0
2201 first = capsys.readouterr().out
2202 assert "**Pipeline:** surfaced 2nd time" in first
2203
2204 assert _run_leg3(tmp_path) == 0
2205 second = capsys.readouterr().out
2206 assert "**Pipeline:** surfaced 2nd time" in second
2207 assert first == second
2208
2209 # The retry never double-counted the surfacing.
2210 conn = _sqlite3.connect(tmp_path / "research.db")
2211 count = conn.execute(
2212 "SELECT surface_count FROM discovery_topics"
2213 ).fetchone()[0]
2214 conn.close()
2215 assert count == 2
2216
2217
2218 def test_discovery_cli_finalize_retry_keeps_covered_history(tmp_path, capsys):
2219 """F3: the reconstructed pre-run state keeps the prior's covered mark
2220 (covered_at intact), so a retry still renders 'marked covered'."""
2221 import store
2222
2223 with store.scoped_db(tmp_path / "research.db"):
2224 store.record_discovery_surfacing(
2225 "Gemma 4 chat templates", domain="AI agents", run_ref="run-old",
2226 as_of="2026-07-13",
2227 )
2228 store.mark_discovery_covered("Gemma 4 chat templates", as_of="2026-07-14")
2229 _write_pending_report(tmp_path)
2230
2231 assert _run_leg3(tmp_path) == 0
2232 first = capsys.readouterr().out
2233 assert "**Pipeline:** surfaced 2nd time, marked covered" in first
2234
2235 assert _run_leg3(tmp_path) == 0
2236 second = capsys.readouterr().out
2237 assert "**Pipeline:** surfaced 2nd time, marked covered" in second
2238 assert first == second
2239
2240 with store.scoped_db(tmp_path / "research.db"):
2241 row = store.match_discovery_topic("Gemma 4 chat templates")
2242 assert row is not None
2243 assert row["status"] == "covered"
2244 assert row["covered_at"] == "2026-07-14"
2245
2246
2247 def test_discovery_cli_finalize_new_run_ref_still_increments(tmp_path, capsys):
2248 """Scenario 8: the guard is per-run. A LATER protocol round (fresh pending
2249 report, fresh run_ref) increments and annotates normally."""
2250 import sqlite3 as _sqlite3
2251
2252 _write_pending_report(tmp_path)
2253 assert _run_leg3(tmp_path) == 0
2254 capsys.readouterr()
2255
2256 # A new leg-2 round over the same story: new generated_at -> new run_ref.
2257 _write_pending_report(tmp_path)
2258 assert _run_leg3(tmp_path) == 0
2259 out = capsys.readouterr().out
2260 assert "**Pipeline:** surfaced 2nd time" in out
2261
2262 conn = _sqlite3.connect(tmp_path / "research.db")
2263 count = conn.execute(
2264 "SELECT surface_count FROM discovery_topics"
2265 ).fetchone()[0]
2266 conn.close()
2267 assert count == 2
2268
2269
2270 def test_discovery_cli_finalize_queue_failure_degrades_to_warning(tmp_path, monkeypatch, capsys):
2271 """The finalize queue call sits behind the same guarded hook as the
2272 one-shot: a broken research.db degrades to a stderr warning and the brief
2273 still prints (exit 0)."""
2274 import sqlite3 as _sqlite3
2275
2276 import store
2277
2278 def _locked(*_args, **_kwargs):
2279 raise _sqlite3.OperationalError("database is locked")
2280
2281 monkeypatch.setattr(store, "record_discovery_surfacing", _locked)
2282 _write_pending_report(tmp_path)
2283
2284 assert _run_leg3(tmp_path) == 0
2285 captured = capsys.readouterr()
2286 assert "## 1. Gemma 4 chat templates" in captured.out
2287 assert "**Pipeline:**" not in captured.out
2288 assert "[last30days] Warning:" in captured.err
2289 assert "database is locked" in captured.err
2290
2291
2292 def test_discovery_cli_finalize_covered_inheritance_on_rename_drift(tmp_path, capsys):
2293 """A host-authored name that fuzzy-matches a covered prior inherits the
2294 covered mark (rename-drift scenario) - same convention as the one-shot."""
2295 import store
2296
2297 with store.scoped_db(tmp_path / "research.db"):
2298 store.record_discovery_surfacing(
2299 "Gemma 4 chat templates", domain="AI agents", run_ref="run-old",
2300 as_of="2026-07-13",
2301 )
2302 store.mark_discovery_covered("Gemma 4 chat templates", as_of="2026-07-14")
2303
2304 _write_pending_report(tmp_path, names=("Gemma 4 template fixes",))
2305 assert _run_leg3(tmp_path) == 0
2306 out = capsys.readouterr().out
2307 assert "marked covered" in out
2308
2309 with store.scoped_db(tmp_path / "research.db"):
2310 fresh = store.match_discovery_topic("Gemma 4 template fixes")
2311 assert fresh is not None
2312 assert fresh["status"] == "covered"
2313 assert fresh["covered_at"] == "2026-07-14"
2314
2315
2316 def test_discovery_cli_finalize_is_offline(tmp_path, capsys):
2317 """Leg 3 is the cheap leg: no sweep, no enrichment, no provider
2318 resolution - only the pending report, the angles file, and the queue."""
2319 _write_pending_report(tmp_path)
2320 parser = cli.build_parser()
2321 args, _extra = parser.parse_known_args([
2322 "--discover", "AI agents", "--save-dir", str(tmp_path), "--finalize",
2323 ])
2324 with mock.patch.object(pipeline, "run_discover") as sweep, \
2325 mock.patch.object(pipeline, "run") as research, \
2326 mock.patch.object(pipeline, "enrich_nominations") as enrich, \
2327 mock.patch.object(pipeline.providers, "resolve_runtime") as resolve:
2328 assert cli._run_discover_protocol_leg(args, {}) == 0
2329 sweep.assert_not_called()
2330 research.assert_not_called()
2331 enrich.assert_not_called()
2332 resolve.assert_not_called()
2333
2334
2335 def test_discovery_cli_finalize_emit_json_carries_host_angles(tmp_path, capsys):
2336 """--emit json respects the same export contract as the one-shot; host
2337 angles ride in the discovery export fields."""
2338 pending = _write_pending_report(tmp_path)
2339 angles_path = _write_angles_file(tmp_path, pending["bundle_id"], [
2340 {"id": "n1", "podcast": "A hook worth exporting"},
2341 ])
2342 assert _run_leg3(
2343 tmp_path, None, "--angles", str(angles_path), "--emit", "json",
2344 ) == 0
2345 payload = json.loads(capsys.readouterr().out)
2346 assert payload["kind"] == "discovery"
2347 assert payload["results"][0]["podcast_angle"] == "A hook worth exporting"
2348 assert payload["results"][0]["x_article_angle"] is None
2349
2350
2351 def test_discovery_cli_finalize_rejects_html_like_the_one_shot(tmp_path):
2352 """The HTML guard is hoisted to the shared --discover dispatch: finalize
2353 rejects --emit=html before touching any handoff state, even when a valid
2354 pending report exists."""
2355 _write_pending_report(tmp_path)
2356 result = _run_protocol_cli([
2357 "--discover", "AI agents", "--save-dir", str(tmp_path), "--finalize",
2358 "--emit", "html",
2359 ])
2360 assert result.returncode == 2, result.stderr
2361 assert "does not support HTML publishing" in result.stderr
2362
2363
2364 def test_discovery_cli_protocol_legs_reject_as_of_and_html(tmp_path):
2365 """F4: the one-shot's --as-of and HTML guards bind on EVERY protocol leg
2366 before dispatch - legs 1 and 2 must not sweep historical dates or accept
2367 an HTML pipeline discovery does not have."""
2368 nominate = _run_protocol_cli([
2369 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2370 "--nominate-only", "--as-of", "2026-06-01",
2371 ])
2372 assert nominate.returncode == 2, nominate.stderr
2373 assert "--as-of cannot be used with --discover" in nominate.stderr
2374 assert "current live listings" in nominate.stderr
2375
2376 # The judgments file deliberately does not exist: the guard must fire
2377 # before any handoff file is read.
2378 judgments = _run_protocol_cli([
2379 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2380 "--judgments", str(tmp_path / "missing-judgments.json"), "--emit=html",
2381 ])
2382 assert judgments.returncode == 2, judgments.stderr
2383 assert "does not support HTML publishing" in judgments.stderr
2384
2385
2386 def test_discovery_cli_finalize_stale_pending_exits_2(tmp_path, capsys):
2387 """TTL is measured from the PENDING report's generated_at (the leg-2
2388 write started a fresh window); a stale one names the resume remedy."""
2389 import datetime as _datetime
2390
2391 stale = (
2392 _datetime.datetime.now(_datetime.timezone.utc)
2393 - _datetime.timedelta(
2394 seconds=discovery_handoff.DISCOVERY_HANDOFF_TTL_SECONDS + 60
2395 )
2396 ).isoformat()
2397 payload = _write_pending_report(tmp_path)
2398 pending_path = tmp_path / discovery_handoff.PENDING_REPORT_FILENAME
2399 payload["generated_at"] = stale
2400 pending_path.write_text(json.dumps(payload), encoding="utf-8")
2401
2402 assert _run_leg3(tmp_path) == 2
2403 err = capsys.readouterr().err
2404 assert "stale" in err
2405 assert "--discover --judgments" in err
2406
2407
2408 def test_discovery_cli_finalize_missing_pending_names_save_dir_only(tmp_path, monkeypatch, capsys):
2409 """With an explicit --save-dir the not-found message names ONLY the
2410 save-dir location (the single handoff store - no config-dir fallback)
2411 plus the resume-leg remedy."""
2412 config_dir = tmp_path / "config"
2413 monkeypatch.setattr(cli.env, "CONFIG_DIR", config_dir)
2414 save_dir = tmp_path / "client"
2415 assert _run_leg3(save_dir) == 2
2416 err = capsys.readouterr().err
2417 assert str(save_dir.resolve() / discovery_handoff.PENDING_REPORT_FILENAME) in err
2418 assert str(config_dir) not in err
2419 assert "--discover --judgments" in err
2420 assert "--discover --nominate-only" in err
2421
2422
2423 def test_discovery_cli_finalize_angles_bundle_mismatch_exits_2(tmp_path, capsys):
2424 pending = _write_pending_report(tmp_path)
2425 angles_path = _write_angles_file(tmp_path, "deadbeefdeadbeef", [
2426 {"id": "n1", "podcast": "Bound to the wrong bundle"},
2427 ])
2428 assert _run_leg3(tmp_path, None, "--angles", str(angles_path)) == 2
2429 err = capsys.readouterr().err
2430 assert "deadbeefdeadbeef" in err
2431 assert pending["bundle_id"] in err
2432
2433
2434 def test_discovery_cli_finalize_invalid_pending_json_exits_2(tmp_path, capsys):
2435 (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).write_text(
2436 "{not json", encoding="utf-8"
2437 )
2438 assert _run_leg3(tmp_path) == 2
2439 assert "JSON" in capsys.readouterr().err
2440
2441
2442 def test_discovery_cli_finalize_malformed_pending_report_body_exits_2(tmp_path, capsys):
2443 """F7: a pending file whose top-level envelope validates but whose report
2444 body is structurally incomplete (missing required report keys) is a
2445 contract failure with the resume remedy - exit 2, never a traceback."""
2446 payload = _write_pending_report(tmp_path)
2447 payload["report"] = {"domain": "AI agents", "topics": []} # no range/dates
2448 (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).write_text(
2449 json.dumps(payload), encoding="utf-8"
2450 )
2451 assert _run_leg3(tmp_path) == 2
2452 err = capsys.readouterr().err
2453 assert "malformed" in err
2454 assert "--discover --judgments" in err
2455
2456
2457 def test_discovery_cli_finalize_wrong_kind_or_version_exits_2(tmp_path, capsys):
2458 payload = _write_pending_report(tmp_path)
2459 pending_path = tmp_path / discovery_handoff.PENDING_REPORT_FILENAME
2460
2461 payload["kind"] = "discovery-nominations"
2462 pending_path.write_text(json.dumps(payload), encoding="utf-8")
2463 assert _run_leg3(tmp_path) == 2
2464 assert "discovery-nominations" in capsys.readouterr().err
2465
2466 payload["kind"] = schema.DISCOVERY_PENDING_KIND
2467 payload["schema_version"] = "99.0"
2468 pending_path.write_text(json.dumps(payload), encoding="utf-8")
2469 assert _run_leg3(tmp_path) == 2
2470 assert "99.0" in capsys.readouterr().err
2471
2472
2473 @pytest.mark.skipif(
2474 hasattr(os, "geteuid") and os.geteuid() == 0,
2475 reason="root ignores directory permission bits",
2476 )
2477 def test_discovery_cli_resume_unwritable_pending_write_is_contract_error(tmp_path, capsys):
2478 """F9: the leg-2 pending-report write gets the same fail-closed treatment
2479 as the bundle write - a read-only state dir is HandoffContractError
2480 (exit 2 naming the path), never a raw OSError traceback."""
2481 bundle_payload = _leg1_bundle_payload(tmp_path)
2482 capsys.readouterr()
2483 judgments_path = tmp_path / "judgments.json"
2484 judgments_path.write_text(json.dumps({
2485 "bundle_id": bundle_payload["bundle_id"],
2486 "judgments": [],
2487 }), encoding="utf-8")
2488 parser = cli.build_parser()
2489 args, _extra = parser.parse_known_args([
2490 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2491 "--judgments", str(judgments_path),
2492 ])
2493
2494 def fake_run(*, topic, **_kwargs):
2495 return _rich_enrichment_report(topic)
2496
2497 tmp_path.chmod(0o500)
2498 try:
2499 with mock.patch.object(pipeline, "run", side_effect=fake_run):
2500 assert cli._run_discover_protocol_leg(args, {}) == 2
2501 finally:
2502 tmp_path.chmod(0o700)
2503 err = capsys.readouterr().err
2504 assert "Could not write pending discovery report" in err
2505 assert str(
2506 tmp_path.resolve() / discovery_handoff.PENDING_REPORT_FILENAME
2507 ) in err
2508
2509
2510 # --- F11: cross-round pending invalidation ------------------------------------
2511
2512
2513 def test_discovery_cli_nominate_clears_stale_pending_from_prior_round(tmp_path, capsys):
2514 """F11: a fresh leg-1 bundle starts a NEW protocol round - any pending
2515 report left by a prior round is deleted, so a bare --finalize afterwards
2516 is not-found (exit 2) instead of silently consuming stale state."""
2517 _write_pending_report(tmp_path) # prior round's leg-2 output
2518 _leg1_bundle_payload(tmp_path) # fresh round: leg 1 writes a new bundle
2519 capsys.readouterr()
2520 assert not (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).exists()
2521
2522 assert _run_leg3(tmp_path) == 2
2523 assert "No pending discovery report found" in capsys.readouterr().err
2524
2525
2526 def test_discovery_cli_resume_nothing_solid_clears_stale_pending(tmp_path, capsys):
2527 """F11: a zero-survivor leg 2 wrote no pending file THIS round, so a
2528 stale one from an earlier round must not survive it - bare --finalize
2529 afterwards exits 2 not-found."""
2530 bundle_payload = _leg1_bundle_payload(tmp_path)
2531 _write_pending_report(tmp_path) # stale pending from an earlier round
2532 judgments = {
2533 "bundle_id": bundle_payload["bundle_id"],
2534 "judgments": [
2535 {"id": row["id"], "junk": True}
2536 for row in bundle_payload["nominations"]
2537 ],
2538 }
2539 with mock.patch.object(pipeline, "enrich_nominations") as enrich:
2540 assert _run_leg2(tmp_path, judgments) == 0
2541 enrich.assert_not_called()
2542 capsys.readouterr()
2543 assert not (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).exists()
2544
2545 assert _run_leg3(tmp_path) == 2
2546 assert "No pending discovery report found" in capsys.readouterr().err
2547
2548
2549 # --- F19: mock/real handoff provenance must match across legs ------------------
2550
2551
2552 def test_discovery_cli_resume_rejects_mock_state_mismatch(tmp_path, capsys):
2553 """F19: a leg-2 run whose --mock flag disagrees with the bundle's stamped
2554 provenance exits 2 before any resume work; matching modes still pass."""
2555 bundle_payload = _leg1_bundle_payload(tmp_path) # mock-born bundle
2556 capsys.readouterr()
2557 judgments_path = tmp_path / "judgments.json"
2558 judgments_path.write_text(json.dumps({
2559 "bundle_id": bundle_payload["bundle_id"],
2560 "judgments": [],
2561 }), encoding="utf-8")
2562 parser = cli.build_parser()
2563 bundle_path = tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME
2564
2565 # Real leg 2 over the mock-born bundle: exit 2, the resume never runs.
2566 args, _extra = parser.parse_known_args([
2567 "--discover", "AI agents", "--save-dir", str(tmp_path),
2568 "--judgments", str(judgments_path),
2569 ])
2570 with mock.patch.object(pipeline, "run_discover_resume") as resume:
2571 assert cli._run_discover_protocol_leg(args, {}) == 2
2572 resume.assert_not_called()
2573 err = capsys.readouterr().err
2574 assert "mock-born state cannot be finalized by a real run" in err
2575
2576 # Mock leg 2 over a real bundle: the inverse also exits 2.
2577 payload = json.loads(bundle_path.read_text(encoding="utf-8"))
2578 payload["mock"] = False
2579 bundle_path.write_text(json.dumps(payload), encoding="utf-8")
2580 args, _extra = parser.parse_known_args([
2581 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2582 "--judgments", str(judgments_path),
2583 ])
2584 with mock.patch.object(pipeline, "run_discover_resume") as resume:
2585 assert cli._run_discover_protocol_leg(args, {}) == 2
2586 resume.assert_not_called()
2587 err = capsys.readouterr().err
2588 assert "cannot be finalized by a --mock run" in err
2589
2590 # Matching modes pass the parity gate and reach the resume engine.
2591 payload["mock"] = True
2592 bundle_path.write_text(json.dumps(payload), encoding="utf-8")
2593 with mock.patch.object(pipeline, "enrich_nominations", return_value=[]):
2594 assert cli._run_discover_protocol_leg(args, {}) == 0
2595 capsys.readouterr()
2596
2597
2598 def test_discovery_cli_finalize_rejects_mock_state_mismatch(tmp_path, capsys):
2599 """F19: finalize enforces the same provenance parity against the pending
2600 report's stamped mock flag, in both directions."""
2601 _write_pending_report(tmp_path) # real pending (no mock stamp = real)
2602 parser = cli.build_parser()
2603 args, _extra = parser.parse_known_args([
2604 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2605 "--finalize",
2606 ])
2607 assert cli._run_discover_protocol_leg(args, {}) == 2
2608 assert "cannot be finalized by a --mock run" in capsys.readouterr().err
2609
2610 # Mock-born pending finalized by a real run: inverse direction.
2611 pending_path = tmp_path / discovery_handoff.PENDING_REPORT_FILENAME
2612 payload = json.loads(pending_path.read_text(encoding="utf-8"))
2613 payload["mock"] = True
2614 pending_path.write_text(json.dumps(payload), encoding="utf-8")
2615 assert _run_leg3(tmp_path) == 2
2616 assert (
2617 "mock-born state cannot be finalized by a real run"
2618 in capsys.readouterr().err
2619 )
2620
2621
2622 # --- F1: degraded sweep state survives the protocol (strict exit on legs) ------
2623
2624
2625 def _degraded_nominate_result() -> pipeline.DiscoverNominateResult:
2626 from_date, to_date = dates.get_date_range(30)
2627 nomination = pipeline.Nomination(
2628 name="Agent SDK Wars",
2629 seed_score=61.0,
2630 items=[_item(
2631 "hn1", "hackernews", "Agent SDK Wars heat up",
2632 engagement={"points": 900, "comments": 400},
2633 )],
2634 summary="Agent SDK Wars heat up across the listings.",
2635 junk_shape=False,
2636 worthiness=None,
2637 )
2638 return pipeline.DiscoverNominateResult(
2639 plan=schema.DiscoveryPlan(
2640 domain="AI agents", category=None, subreddits=[],
2641 sources=["hackernews"],
2642 ),
2643 from_date=from_date,
2644 to_date=to_date,
2645 source_status={
2646 "hackernews": schema.SourceOutcome(
2647 source="hackernews", state="ok", items_returned=1,
2648 ),
2649 "reddit": schema.SourceOutcome(
2650 source="reddit", state=schema.UNREACHABLE, detail="dns failure",
2651 ),
2652 },
2653 pool=[(nomination, "c-agent")],
2654 )
2655
2656
2657 def test_discovery_protocol_strict_exit_and_degraded_state_survive_all_legs(tmp_path, capsys):
2658 """F1: the leg-1 sweep's degraded source outcomes ride the bundle into
2659 leg 2's report and pending file, and on into leg 3's brief - and under
2660 LAST30DAYS_STRICT_EXIT every leg renders normally but exits 3, mirroring
2661 the one-shot's strict-exit contract."""
2662 strict = {"LAST30DAYS_STRICT_EXIT": "1"}
2663 parser = cli.build_parser()
2664
2665 # Leg 1: bundle written (render/output still happens), exit shifts to 3.
2666 args1, _extra = parser.parse_known_args([
2667 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2668 "--nominate-only",
2669 ])
2670 with mock.patch.object(
2671 pipeline, "run_discover_nominate",
2672 return_value=_degraded_nominate_result(),
2673 ):
2674 assert cli._run_discover_protocol_leg(args1, strict) == 3
2675 captured = capsys.readouterr()
2676 assert "strict-exit: degraded sources: reddit" in captured.err
2677 bundle_payload = json.loads(
2678 (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
2679 encoding="utf-8"
2680 )
2681 )
2682 assert bundle_payload["source_status"]["reddit"]["state"] == schema.UNREACHABLE
2683
2684 # Leg 2: the restored sweep status reaches the pending report (degraded
2685 # warning included) and the exit code stays strict.
2686 judgments = {
2687 "bundle_id": bundle_payload["bundle_id"],
2688 "judgments": [{"id": "n1", "junk": False, "worthiness": 80}],
2689 }
2690
2691 def fake_run(*, topic, **_kwargs):
2692 return _rich_enrichment_report(topic)
2693
2694 with mock.patch.object(pipeline, "run", side_effect=fake_run):
2695 assert _run_leg2(tmp_path, judgments, config=strict) == 3
2696 captured = capsys.readouterr()
2697 assert "strict-exit: degraded sources: reddit" in captured.err
2698 pending_payload = json.loads(
2699 (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).read_text(
2700 encoding="utf-8"
2701 )
2702 )
2703 assert pending_payload["report"]["source_status"]["reddit"]["state"] == (
2704 schema.UNREACHABLE
2705 )
2706 assert any(
2707 "Some discovery sources degraded: reddit" in warning
2708 for warning in pending_payload["report"]["warnings"]
2709 )
2710
2711 # Leg 3: the brief renders the degraded coverage note and exits 3 too.
2712 args3, _extra = parser.parse_known_args([
2713 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2714 "--finalize",
2715 ])
2716 assert cli._run_discover_protocol_leg(args3, strict) == 3
2717 captured = capsys.readouterr()
2718 assert "Some discovery sources degraded: reddit" in captured.out
2719 assert "strict-exit: degraded sources: reddit" in captured.err
2720
2721
2722 def test_discovery_nominate_nothing_solid_applies_strict_exit(tmp_path, capsys):
2723 """F1c: the leg-1 nothing-solid short-circuit is a terminal return too -
2724 it renders the brief and still exits 3 under strict exit when the sweep
2725 itself was degraded."""
2726 import dataclasses
2727
2728 strict = {"LAST30DAYS_STRICT_EXIT": "1"}
2729 result = dataclasses.replace(_degraded_nominate_result(), pool=[])
2730 parser = cli.build_parser()
2731 args, _extra = parser.parse_known_args([
2732 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2733 "--nominate-only",
2734 ])
2735 with mock.patch.object(
2736 pipeline, "run_discover_nominate", return_value=result,
2737 ):
2738 assert cli._run_discover_protocol_leg(args, strict) == 3
2739 captured = capsys.readouterr()
2740 assert "Nothing solid this window." in captured.out
2741 assert "strict-exit: degraded sources: reddit" in captured.err
2742 assert not (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).exists()
2743
2744
2745 def test_discovery_cli_full_mock_protocol_three_legs_end_to_end(tmp_path):
2746 """The whole protocol offline: nominate -> judgments -> finalize (with
2747 angles) produces a complete brief. Mock finalize writes NO queue rows and
2748 renders deterministically across two runs."""
2749 leg1 = _run_nominate_only(tmp_path)
2750 assert leg1.returncode == 0, leg1.stderr
2751 bundle_payload = json.loads(
2752 (tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME).read_text(
2753 encoding="utf-8"
2754 )
2755 )
2756 rows = bundle_payload["nominations"]
2757 keep = [row["id"] for row in rows if not row["heuristic_junk"]][:1]
2758 assert keep, "mock sweep should nominate at least one non-junk topic"
2759 judgments_path = tmp_path / "judgments.json"
2760 judgments_path.write_text(json.dumps({
2761 "bundle_id": bundle_payload["bundle_id"],
2762 "judgments": [
2763 {"id": keep[0], "name": "Renamed Mock Topic", "junk": False,
2764 "worthiness": 90},
2765 *[
2766 {"id": row["id"], "junk": True}
2767 for row in rows if row["id"] not in keep
2768 ],
2769 ],
2770 }), encoding="utf-8")
2771 leg2 = _run_protocol_cli(
2772 [
2773 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2774 "--judgments", str(judgments_path),
2775 ],
2776 env_overrides={"LAST30DAYS_DEFAULT_SEARCH": ""},
2777 )
2778 assert leg2.returncode == 0, leg2.stderr
2779 pending_payload = json.loads(
2780 (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).read_text(
2781 encoding="utf-8"
2782 )
2783 )
2784 angles_path = _write_angles_file(tmp_path, pending_payload["bundle_id"], [
2785 {"id": keep[0],
2786 "podcast": "A mock podcast hook for the renamed topic",
2787 "x_article": "A mock X-article hook for the renamed topic"},
2788 ])
2789
2790 def run_leg3():
2791 return _run_protocol_cli([
2792 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2793 "--finalize", "--angles", str(angles_path),
2794 ])
2795
2796 first = run_leg3()
2797 assert first.returncode == 0, first.stderr
2798 # A complete brief: topic card, host angle lines, research handoff.
2799 assert "## 1. Renamed Mock Topic" in first.stdout
2800 assert (
2801 "**Podcast angle:** A mock podcast hook for the renamed topic"
2802 in first.stdout
2803 )
2804 assert (
2805 "**X article angle:** A mock X-article hook for the renamed topic"
2806 in first.stdout
2807 )
2808 assert '**Research next:** `/last30days "Renamed Mock Topic"`' in first.stdout
2809 # Mock stays queue-free and deterministic.
2810 assert not (tmp_path / "research.db").exists()
2811 second = run_leg3()
2812 assert second.returncode == 0, second.stderr
2813 assert first.stdout == second.stdout
2814 assert not (tmp_path / "research.db").exists()
2815
2816
2817 # --- U6: engine-side LLM judge removed - discovery is provider-free -----------
2818 # The stage-1 judge and stage-2 angle pass are deleted: no discovery code path
2819 # may resolve a provider runtime or construct a provider client, ever.
2820
2821
2822 def _provider_tripwires() -> list:
2823 """Patches that make ANY provider touch explode: resolve_runtime plus
2824 every client class on the providers module surface."""
2825 def _forbid(label: str):
2826 def _raise(*_args, **_kwargs):
2827 raise AssertionError(f"{label} touched from a discovery code path")
2828 return _raise
2829
2830 return [
2831 mock.patch.object(pipeline.providers, name, new=_forbid(f"providers.{name}"))
2832 for name in (
2833 "resolve_runtime",
2834 "GeminiClient",
2835 "OpenAIClient",
2836 "XAIClient",
2837 "OpenRouterClient",
2838 )
2839 ]
2840
2841
2842 def test_mock_discovery_constructs_no_provider_client(tmp_path, capsys):
2843 """--mock discovery must stay network-clean across the one-shot path AND
2844 all three protocol legs: subprocess tests inherit ambient env keys, so a
2845 single ungated resolve (or a directly constructed client) could let a
2846 --mock run reach the network. It must not emit the loud one-shot
2847 heuristics note either - the note is for real runs, not deliberate mock
2848 runs."""
2849 with contextlib.ExitStack() as stack:
2850 for patcher in _provider_tripwires():
2851 stack.enter_context(patcher)
2852
2853 # One-shot sweep.
2854 report = pipeline.run_discover(
2855 domain="AI agents", config={}, mock=True, as_of_date="2026-07-10",
2856 )
2857 assert report.topics
2858
2859 # Leg 1 (nominate-only) -> leg 2 (real mock enrichment sub-runs) ->
2860 # leg 3 (finalize, no angles file).
2861 bundle_payload = _leg1_bundle_payload(tmp_path)
2862 judgments = {"bundle_id": bundle_payload["bundle_id"], "judgments": []}
2863 assert _run_leg2(tmp_path, judgments) == 0
2864 parser = cli.build_parser()
2865 args, _extra = parser.parse_known_args([
2866 "--discover", "AI agents", "--mock", "--save-dir", str(tmp_path),
2867 "--finalize",
2868 ])
2869 assert cli._run_discover_protocol_leg(args, {}) == 0
2870
2871 assert "deterministic heuristics" not in capsys.readouterr().err
2872
2873
2874 def test_discovery_paths_are_provider_free_at_the_source_level():
2875 """Source-inspection pin (like the enrich ThreadPoolExecutor pin): no
2876 provider resolution is reachable from any discovery entry point, and the
2877 deleted judge module is never referenced by the pipeline."""
2878 for func in (
2879 pipeline.run_discover,
2880 pipeline.run_discover_nominate,
2881 pipeline.run_discover_resume,
2882 pipeline.nominate_topic_pool,
2883 pipeline.nominate_topics,
2884 pipeline.enrich_nominations,
2885 ):
2886 assert "resolve_runtime" not in inspect.getsource(func), func.__name__
2887
2888 needle = "discovery" + "_judge" # split so this pin never matches itself
2889 assert needle not in inspect.getsource(pipeline)
2890
2891
2892 def test_no_engine_judge_references_remain_anywhere():
2893 """Repo-level pin: the engine judge module is deleted and nothing under
2894 skills/ or tests/ references it by name."""
2895 needle = "discovery" + "_judge" # split so this pin never matches itself
2896 assert not (
2897 REPO_ROOT / "skills" / "last30days" / "scripts" / "lib" / f"{needle}.py"
2898 ).exists()
2899 offenders = [
2900 str(path)
2901 for root in ("skills", "tests")
2902 for path in sorted((REPO_ROOT / root).rglob("*.py"))
2903 if needle in path.read_text(encoding="utf-8", errors="ignore")
2904 ]
2905 assert offenders == []
2906
2906 lines PYTHON