| 1 | import copy |
| 2 | import io |
| 3 | import json |
| 4 | from contextlib import redirect_stderr, redirect_stdout |
| 5 | from dataclasses import replace |
| 6 | from pathlib import Path |
| 7 | from unittest import mock |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | import last30days as cli |
| 12 | from lib import library, library_index, pipeline, planner, render, schema |
| 13 | |
| 14 | |
| 15 | def _item(item_id: str, source: str, title: str, url: str) -> schema.SourceItem: |
| 16 | return schema.SourceItem( |
| 17 | item_id=item_id, |
| 18 | source=source, |
| 19 | title=title, |
| 20 | body=f"Body for {title}", |
| 21 | url=url, |
| 22 | snippet=f"Evidence about {title}", |
| 23 | local_rank_score=0.9, |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | def _candidate(item: schema.SourceItem, score: float = 80.0) -> schema.Candidate: |
| 28 | return schema.Candidate( |
| 29 | candidate_id=f"cand-{item.item_id}", |
| 30 | item_id=item.item_id, |
| 31 | source=item.source, |
| 32 | title=item.title, |
| 33 | url=item.url, |
| 34 | snippet=item.snippet, |
| 35 | subquery_labels=["primary"], |
| 36 | native_ranks={item.source: 1}, |
| 37 | local_relevance=0.9, |
| 38 | freshness=90, |
| 39 | engagement=10, |
| 40 | source_quality=0.8, |
| 41 | rrf_score=0.1, |
| 42 | sources=[item.source], |
| 43 | source_items=[item], |
| 44 | final_score=score, |
| 45 | ) |
| 46 | |
| 47 | |
| 48 | def _report(*, drill: bool = False) -> schema.Report: |
| 49 | ban = _item( |
| 50 | "ban", |
| 51 | "reddit", |
| 52 | "OpenClaw API ban discussion", |
| 53 | "https://reddit.example/ban", |
| 54 | ) |
| 55 | policy = _item( |
| 56 | "policy", |
| 57 | "youtube", |
| 58 | "OpenClaw policy explained", |
| 59 | "https://youtube.example/policy", |
| 60 | ) |
| 61 | release = _item( |
| 62 | "release", |
| 63 | "hackernews", |
| 64 | "OpenClaw ships a new release", |
| 65 | "https://news.example/release", |
| 66 | ) |
| 67 | candidates = [_candidate(ban, 92), _candidate(policy, 85), _candidate(release, 70)] |
| 68 | clusters = [ |
| 69 | schema.Cluster( |
| 70 | cluster_id="cluster-1", |
| 71 | title="OpenClaw API ban discussion", |
| 72 | candidate_ids=[candidates[0].candidate_id, candidates[1].candidate_id], |
| 73 | representative_ids=[candidates[0].candidate_id], |
| 74 | sources=["reddit", "youtube"], |
| 75 | score=92, |
| 76 | ), |
| 77 | schema.Cluster( |
| 78 | cluster_id="cluster-2", |
| 79 | title="OpenClaw release notes", |
| 80 | candidate_ids=[candidates[2].candidate_id], |
| 81 | representative_ids=[candidates[2].candidate_id], |
| 82 | sources=["hackernews"], |
| 83 | score=70, |
| 84 | ), |
| 85 | ] |
| 86 | if drill: |
| 87 | deeper = _item( |
| 88 | "deeper", |
| 89 | "reddit", |
| 90 | "OpenClaw API policy enforcement details", |
| 91 | "https://reddit.example/deeper", |
| 92 | ) |
| 93 | # The first result repeats the cached URL; merge must keep one copy. |
| 94 | candidates = [_candidate(ban, 95), _candidate(deeper, 90)] |
| 95 | clusters = [ |
| 96 | schema.Cluster( |
| 97 | cluster_id="cluster-1", |
| 98 | title="OpenClaw API policy enforcement details", |
| 99 | candidate_ids=[candidate.candidate_id for candidate in candidates], |
| 100 | representative_ids=[candidate.candidate_id for candidate in candidates], |
| 101 | sources=["reddit"], |
| 102 | score=95, |
| 103 | ) |
| 104 | ] |
| 105 | items_by_source = {"reddit": [ban, deeper]} |
| 106 | else: |
| 107 | items_by_source = { |
| 108 | "reddit": [ban], |
| 109 | "youtube": [policy], |
| 110 | "hackernews": [release], |
| 111 | } |
| 112 | return schema.Report( |
| 113 | topic="OpenClaw API policy" if drill else "OpenClaw", |
| 114 | range_from="2026-06-10", |
| 115 | range_to="2026-07-10", |
| 116 | generated_at="2026-07-10T12:00:00+00:00", |
| 117 | provider_runtime=schema.ProviderRuntime( |
| 118 | reasoning_provider="local", |
| 119 | planner_model="mock-planner", |
| 120 | rerank_model="mock-reranker", |
| 121 | ), |
| 122 | query_plan=schema.QueryPlan( |
| 123 | intent="opinion", |
| 124 | freshness_mode="balanced_recent", |
| 125 | cluster_mode="debate", |
| 126 | raw_topic="OpenClaw", |
| 127 | subqueries=[ |
| 128 | schema.SubQuery( |
| 129 | label="primary", |
| 130 | search_query="OpenClaw", |
| 131 | ranking_query="What is happening with OpenClaw?", |
| 132 | sources=list(items_by_source), |
| 133 | ) |
| 134 | ], |
| 135 | source_weights={source: 1.0 for source in items_by_source}, |
| 136 | ), |
| 137 | clusters=clusters, |
| 138 | ranked_candidates=candidates, |
| 139 | items_by_source=items_by_source, |
| 140 | errors_by_source={}, |
| 141 | source_status={ |
| 142 | source: schema.SourceOutcome( |
| 143 | source=source, |
| 144 | state="ok", |
| 145 | items_returned=len(items), |
| 146 | ) |
| 147 | for source, items in items_by_source.items() |
| 148 | }, |
| 149 | ) |
| 150 | |
| 151 | |
| 152 | def test_cluster_resolution_by_index_and_number(): |
| 153 | report = _report() |
| 154 | assert planner.resolve_drill_clusters(report, "cluster 2")[0].cluster_id == "cluster-2" |
| 155 | assert planner.resolve_drill_clusters(report, "1")[0].cluster_id == "cluster-1" |
| 156 | |
| 157 | |
| 158 | def test_cluster_resolution_by_fuzzy_title_and_entities(): |
| 159 | matched = planner.resolve_drill_clusters( |
| 160 | _report(), |
| 161 | "what is behind the OpenClaw API ban?", |
| 162 | ) |
| 163 | assert [cluster.cluster_id for cluster in matched] == ["cluster-1"] |
| 164 | |
| 165 | |
| 166 | def test_cluster_resolution_no_match_prints_candidates(): |
| 167 | with pytest.raises(planner.DrillTargetError) as exc: |
| 168 | planner.resolve_drill_clusters(_report(), "quantum potato harvest") |
| 169 | message = str(exc.value) |
| 170 | assert "Available clusters" in message |
| 171 | assert "1. OpenClaw API ban discussion" in message |
| 172 | assert "2. OpenClaw release notes" in message |
| 173 | |
| 174 | |
| 175 | def test_build_drill_plan_only_uses_contributing_sources_and_cluster_terms(): |
| 176 | plan = planner.build_drill_plan(_report(), "cluster 1") |
| 177 | assert set(plan.source_weights) == {"reddit", "youtube"} |
| 178 | assert all(set(subquery.sources) == {"reddit", "youtube"} for subquery in plan.subqueries) |
| 179 | assert all("hackernews" not in subquery.sources for subquery in plan.subqueries) |
| 180 | assert "drill-mode" in plan.notes |
| 181 | assert any("openclaw" in subquery.search_query.lower() for subquery in plan.subqueries) |
| 182 | |
| 183 | |
| 184 | def test_build_drill_plan_keeps_the_polymarket_hints(): |
| 185 | report = _report() |
| 186 | hints = {"kind": "team", "aliases": [], "related": [{"name": "Yaxel Lendeborg", "relation": "player"}]} |
| 187 | report.query_plan.polymarket_hints = hints |
| 188 | |
| 189 | plan = planner.build_drill_plan(report, "cluster 1") |
| 190 | |
| 191 | assert plan.polymarket_hints == hints |
| 192 | assert plan.polymarket_hints is not hints |
| 193 | |
| 194 | |
| 195 | def _with_local_notes(report: schema.Report) -> schema.Candidate: |
| 196 | note = _item("notes", "corpus", "Local packet tracing notes", "corpus://notes") |
| 197 | private = _candidate(note) |
| 198 | cluster = report.clusters[0] |
| 199 | report.ranked_candidates.insert(0, private) |
| 200 | report.items_by_source["corpus"] = [note] |
| 201 | cluster.candidate_ids.insert(0, private.candidate_id) |
| 202 | cluster.representative_ids = [private.candidate_id] |
| 203 | cluster.title = note.title |
| 204 | cluster.sources.append("corpus") |
| 205 | return private |
| 206 | |
| 207 | |
| 208 | def test_mixed_drill_uses_a_public_title_when_the_representative_is_local(): |
| 209 | report = _report() |
| 210 | private = _with_local_notes(report) |
| 211 | |
| 212 | plan = planner.build_drill_plan(report, "cluster 1") |
| 213 | |
| 214 | assert set(plan.source_weights) == {"reddit", "youtube", "corpus"} |
| 215 | assert plan.subqueries[0].search_query == report.items_by_source["reddit"][0].title |
| 216 | assert all("packet tracing" not in query.ranking_query.lower() for query in plan.subqueries) |
| 217 | assert all(private.title not in query.search_query for query in plan.subqueries) |
| 218 | |
| 219 | |
| 220 | def test_mixed_drill_recovers_public_evidence_from_a_fused_candidate(): |
| 221 | report = _report() |
| 222 | private = _with_local_notes(report) |
| 223 | public = report.items_by_source["reddit"][0] |
| 224 | private.source_items.append(public) |
| 225 | private.sources.append(public.source) |
| 226 | report.clusters[0].candidate_ids = [private.candidate_id] |
| 227 | |
| 228 | plan = planner.build_drill_plan(report, "cluster 1") |
| 229 | |
| 230 | assert set(plan.source_weights) == {"reddit", "corpus"} |
| 231 | assert plan.subqueries[0].search_query == public.title |
| 232 | assert all(private.title not in query.ranking_query for query in plan.subqueries) |
| 233 | |
| 234 | |
| 235 | def test_corpus_only_drill_researches_local_files_with_remote_options_available(tmp_path, monkeypatch): |
| 236 | report = _report() |
| 237 | private = _with_local_notes(report) |
| 238 | report.clusters[0].candidate_ids = [private.candidate_id] |
| 239 | report.clusters[0].sources = ["corpus"] |
| 240 | plan = planner.build_drill_plan(report, "cluster 1") |
| 241 | notes = tmp_path / "notes" |
| 242 | notes.mkdir() |
| 243 | (notes / "Local packet tracing notes.md").write_text( |
| 244 | "OpenClaw local packet tracing notes explain how to verify packet flows.", |
| 245 | encoding="utf-8", |
| 246 | ) |
| 247 | forbid_remote = mock.Mock(side_effect=AssertionError("remote configuration should be unused")) |
| 248 | monkeypatch.setattr(pipeline.providers, "resolve_runtime", forbid_remote) |
| 249 | monkeypatch.setattr(pipeline, "available_sources", forbid_remote) |
| 250 | |
| 251 | result = pipeline.run( |
| 252 | topic=report.topic, |
| 253 | config={"_drill_mode": True}, |
| 254 | depth="deep", |
| 255 | requested_sources=list(plan.source_weights), |
| 256 | external_plan=schema.to_dict(plan), |
| 257 | corpus_dirs=[str(notes)], |
| 258 | corpus_all_time=True, |
| 259 | web_backend="keyless", |
| 260 | ) |
| 261 | |
| 262 | assert plan.subqueries[0].search_query == private.title |
| 263 | assert set(result.items_by_source) == {"corpus"} |
| 264 | assert [item.title for item in result.items_by_source["corpus"]] == [private.title] |
| 265 | assert result.provider_runtime.reasoning_provider == "local" |
| 266 | forbid_remote.assert_not_called() |
| 267 | |
| 268 | |
| 269 | @pytest.mark.parametrize("keep_local_candidate", [True, False]) |
| 270 | def test_legacy_corpus_drill_is_private_after_a_cache_round_trip(monkeypatch, capsys, keep_local_candidate): |
| 271 | report = _report() |
| 272 | private = _with_local_notes(report) |
| 273 | merged = pipeline.merge_drill_report(report, _report(drill=True), [report.clusters[0]], target="cluster 1") |
| 274 | merged.query_plan.subqueries.append(schema.SubQuery( |
| 275 | label="legacy", search_query=private.title, ranking_query=private.snippet, sources=["reddit", "corpus"], |
| 276 | )) |
| 277 | if not keep_local_candidate: |
| 278 | merged.ranked_candidates = [ |
| 279 | candidate for candidate in merged.ranked_candidates |
| 280 | if candidate.candidate_id != private.candidate_id |
| 281 | ] |
| 282 | merged.clusters[0].candidate_ids.remove(private.candidate_id) |
| 283 | merged.clusters[0].representative_ids.remove(private.candidate_id) |
| 284 | stored = schema.report_from_dict(schema.to_dict(merged)) |
| 285 | stored.source_status.pop("corpus", None) |
| 286 | assert stored.artifacts["drill_context"]["original_summary"] == private.snippet |
| 287 | |
| 288 | public = schema.without_sources(stored, {"corpus"}) |
| 289 | args = cli.build_parser().parse_args(["--drill", "cluster 1", "--emit=html", "--publish-html"]) |
| 290 | publish = mock.Mock(return_value={"url": "https://example.test/brief"}) |
| 291 | monkeypatch.setattr(cli, "publish_rendered_html", publish) |
| 292 | assert cli._render_save_and_print(args, stored, None, None, {}) == 0 |
| 293 | local = capsys.readouterr().out |
| 294 | published = publish.call_args.args[0] |
| 295 | |
| 296 | assert private.snippet in local |
| 297 | compact = render.render_compact(stored) |
| 298 | assert f"{render.PRIVATE_CORPUS_START}\n## Drill Follow-up" in compact |
| 299 | for markdown in (compact, render.render_full(stored)): |
| 300 | assert f"{render.PUBLIC_CLUSTERS_MARKER}\n## Ranked Evidence Clusters" in markdown |
| 301 | assert private.title not in published |
| 302 | assert private.snippet not in published |
| 303 | assert public.drill_of is None |
| 304 | assert "drill_context" not in public.artifacts |
| 305 | assert "drill_history" not in public.artifacts |
| 306 | assert not public.query_plan.subqueries |
| 307 | assert public.items_by_source["reddit"] |
| 308 | assert public.clusters[0].title in {candidate.title for candidate in public.ranked_candidates} |
| 309 | assert stored.drill_of == private.title |
| 310 | |
| 311 | |
| 312 | def test_merge_dedupes_new_results_preserves_other_clusters_and_renders_context(): |
| 313 | base = _report() |
| 314 | merged = pipeline.merge_drill_report( |
| 315 | base, |
| 316 | _report(drill=True), |
| 317 | [base.clusters[0]], |
| 318 | target="cluster 1", |
| 319 | ) |
| 320 | |
| 321 | assert merged.drill_of == "OpenClaw API ban discussion" |
| 322 | assert [cluster.cluster_id for cluster in merged.clusters] == ["cluster-1", "cluster-2"] |
| 323 | assert len([item for item in merged.items_by_source["reddit"] if item.url.endswith("/ban")]) == 1 |
| 324 | assert any(item.url.endswith("/deeper") for item in merged.items_by_source["reddit"]) |
| 325 | assert merged.artifacts["drill_context"]["new_items"] == 1 |
| 326 | assert len(merged.artifacts["drill_history"]) == 1 |
| 327 | output = render.render_compact(merged) |
| 328 | assert "## Drill Follow-up" in output |
| 329 | assert "### Original" in output |
| 330 | assert "### Deeper" in output |
| 331 | assert "### Original" in library.public_markdown(output) |
| 332 | public = schema.without_sources(merged, {"corpus"}) |
| 333 | assert public.artifacts["drill_context"] == merged.artifacts["drill_context"] |
| 334 | |
| 335 | |
| 336 | def test_public_drill_verdict_cannot_export_private_claims_or_corroboration(tmp_path, monkeypatch, capsys): |
| 337 | base = _report() |
| 338 | private = _with_local_notes(base) |
| 339 | private_item = private.source_items[0] |
| 340 | private_item.url = "https://example.test/saved-local-snapshot" |
| 341 | report = pipeline.merge_drill_report(base, _report(drill=True), [base.clusters[0]], target="cluster 1") |
| 342 | public = report.ranked_candidates[0] |
| 343 | verdict = schema.FreshnessVerdict( |
| 344 | claim_id="public", candidate_id=public.candidate_id, claim="Publicly corroborated status", |
| 345 | source=public.source, source_item_id=public.item_id, verdict="contradicted", |
| 346 | checked_at="2026-07-10", evidence_url="https://example.test/public-evidence", |
| 347 | ) |
| 348 | report.freshness_verdicts = [ |
| 349 | verdict, |
| 350 | replace( |
| 351 | verdict, claim_id="local-copy", evidence_url=private_item.url, |
| 352 | detail="Local snapshot corroboration", current_value="Local-only status", |
| 353 | ), |
| 354 | replace( |
| 355 | verdict, claim_id="legacy", evidence_url="corpus://older-removed-note", |
| 356 | evidence_timestamp="2026-07-09", detail="Archived local corroboration", |
| 357 | ), |
| 358 | replace( |
| 359 | verdict, claim_id="private-unsupported", candidate_id=private.candidate_id, |
| 360 | claim="Private unavailableclaim", source="corpus", source_item_id=private.item_id, |
| 361 | source_url=private_item.url, evidence_url="", verdict="unsupported", |
| 362 | ), |
| 363 | replace( |
| 364 | verdict, claim_id="private-contradicted", candidate_id=private.candidate_id, |
| 365 | claim="Private disputedclaim", source="corpus", source_item_id=private.item_id, |
| 366 | source_url=private_item.url, |
| 367 | ), |
| 368 | ] |
| 369 | args = cli.build_parser().parse_args(["--drill", "cluster 1", "--emit=html", "--publish-html"]) |
| 370 | publish = mock.Mock(return_value={"url": "https://example.test/brief"}) |
| 371 | monkeypatch.setattr(cli, "publish_rendered_html", publish) |
| 372 | assert cli._render_save_and_print(args, report, None, None, {}) == 0 |
| 373 | local = capsys.readouterr().out |
| 374 | published = publish.call_args.args[0] |
| 375 | |
| 376 | exported = schema.to_agent_export(report) |
| 377 | assert [row["claim_id"] for row in exported["freshness_verdicts"]] == ["public"] |
| 378 | assert "Local snapshot corroboration" in local |
| 379 | assert "Archived local corroboration" in local |
| 380 | assert "Local snapshot corroboration" not in published |
| 381 | assert "Archived local corroboration" not in published |
| 382 | assert "Publicly corroborated status" in published |
| 383 | assert "unavailableclaim" in local and "disputedclaim" in local |
| 384 | assert "unavailableclaim" not in published and "disputedclaim" not in published |
| 385 | |
| 386 | memory = tmp_path / "memory" |
| 387 | memory.mkdir() |
| 388 | raw = memory / "openclaw-raw.md" |
| 389 | raw.write_text(render.render_full(report), encoding="utf-8") |
| 390 | entry = library._parse_markdown(raw) |
| 391 | publish_many = mock.Mock(return_value={}) |
| 392 | monkeypatch.setattr("lib.html_publish.publish_html_documents", publish_many) |
| 393 | monkeypatch.setattr("lib.html_publish.publish_html", mock.Mock(return_value={"url": "https://example.test/index"})) |
| 394 | feed_args = cli.build_parser().parse_args(["library", "feed", "--save-dir", str(memory), "--publish"]) |
| 395 | assert cli._run_library_feed(feed_args, {}) == 0 |
| 396 | public_brief = publish_many.call_args.args[0][entry.entry_id] |
| 397 | local_brief = (memory / "briefs" / entry.output_name).read_text(encoding="utf-8") |
| 398 | assert "Publicly corroborated status" in public_brief |
| 399 | assert "unavailableclaim" in local_brief and "disputedclaim" in local_brief |
| 400 | assert "unavailableclaim" not in public_brief and "disputedclaim" not in public_brief |
| 401 | |
| 402 | db_path = tmp_path / "library.db" |
| 403 | no_store = tmp_path / "no-store.db" |
| 404 | library_index.sync_library(memory, tmp_path / "no-briefings", db_path=db_path) |
| 405 | assert library_index.search("corroborated status", db_path=db_path, store_db_path=no_store) |
| 406 | assert not library_index.search("unavailableclaim", db_path=db_path, store_db_path=no_store) |
| 407 | assert not library_index.search("disputedclaim", db_path=db_path, store_db_path=no_store) |
| 408 | |
| 409 | |
| 410 | def test_merge_dedupes_drill_candidates_against_untouched_clusters(): |
| 411 | base = _report() |
| 412 | drill_report = _report(drill=True) |
| 413 | rediscovered = copy.deepcopy(base.ranked_candidates[2]) |
| 414 | drill_report.ranked_candidates.append(rediscovered) |
| 415 | drill_report.clusters[0].candidate_ids.append(rediscovered.candidate_id) |
| 416 | |
| 417 | merged = pipeline.merge_drill_report( |
| 418 | base, |
| 419 | drill_report, |
| 420 | [base.clusters[0]], |
| 421 | target="cluster 1", |
| 422 | ) |
| 423 | |
| 424 | candidate_ids = [candidate.candidate_id for candidate in merged.ranked_candidates] |
| 425 | assert candidate_ids.count(rediscovered.candidate_id) == 1 |
| 426 | assert rediscovered.candidate_id not in merged.clusters[0].candidate_ids |
| 427 | assert rediscovered.candidate_id in merged.clusters[1].candidate_ids |
| 428 | |
| 429 | |
| 430 | def test_merge_retains_enriched_rediscovery_in_untouched_cluster(): |
| 431 | base = _report() |
| 432 | base.ranked_candidates[2].cluster_id = "cluster-2" |
| 433 | drill_report = _report(drill=True) |
| 434 | rediscovered = copy.deepcopy(base.ranked_candidates[2]) |
| 435 | rediscovered.snippet = "Enriched release evidence from the drill" |
| 436 | rediscovered.engagement = 321 |
| 437 | rediscovered.source_items[0].snippet = "Transcript-backed release evidence" |
| 438 | rediscovered.source_items[0].engagement = {"comments": 42} |
| 439 | rediscovered.source_items[0].metadata = { |
| 440 | "transcript": "Detailed release transcript", |
| 441 | "comments": ["Useful community context"], |
| 442 | } |
| 443 | drill_report.ranked_candidates.append(rediscovered) |
| 444 | |
| 445 | merged = pipeline.merge_drill_report( |
| 446 | base, |
| 447 | drill_report, |
| 448 | [base.clusters[0]], |
| 449 | target="cluster 1", |
| 450 | ) |
| 451 | |
| 452 | retained = next( |
| 453 | candidate |
| 454 | for candidate in merged.ranked_candidates |
| 455 | if candidate.candidate_id == rediscovered.candidate_id |
| 456 | ) |
| 457 | assert retained.cluster_id == base.ranked_candidates[2].cluster_id |
| 458 | assert retained.snippet == "Enriched release evidence from the drill" |
| 459 | assert retained.engagement == 321 |
| 460 | assert retained.source_items[0].metadata["transcript"] == "Detailed release transcript" |
| 461 | assert retained.source_items[0].engagement == {"comments": 42} |
| 462 | |
| 463 | |
| 464 | def test_merge_recomputes_attempted_source_health_from_retained_evidence(): |
| 465 | base = _report() |
| 466 | base.errors_by_source["reddit"] = "cached timeout" |
| 467 | base.source_status["reddit"] = schema.SourceOutcome( |
| 468 | source="reddit", |
| 469 | state=schema.RATE_LIMITED, |
| 470 | detail="cached timeout", |
| 471 | ) |
| 472 | base.warnings = [ |
| 473 | "Some sources failed: reddit", |
| 474 | "No candidates survived retrieval and ranking.", |
| 475 | ] |
| 476 | drill_report = _report(drill=True) |
| 477 | drill_report.source_status["youtube"] = schema.SourceOutcome( |
| 478 | source="youtube", |
| 479 | state=schema.NO_RESULTS, |
| 480 | items_returned=0, |
| 481 | ) |
| 482 | |
| 483 | merged = pipeline.merge_drill_report( |
| 484 | base, |
| 485 | drill_report, |
| 486 | [base.clusters[0]], |
| 487 | target="cluster 1", |
| 488 | ) |
| 489 | |
| 490 | assert "reddit" not in merged.errors_by_source |
| 491 | assert merged.source_status["reddit"].state == "ok" |
| 492 | assert merged.source_status["youtube"].state == "ok" |
| 493 | assert merged.source_status["youtube"].items_returned == 1 |
| 494 | assert not any("Some sources failed" in warning for warning in merged.warnings) |
| 495 | assert "No candidates survived retrieval and ranking." not in merged.warnings |
| 496 | |
| 497 | |
| 498 | def test_expired_cache_exits_cleanly_with_research_guidance(tmp_path: Path): |
| 499 | config_dir = tmp_path / "config" |
| 500 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 501 | cli._write_last_run("OpenClaw", _report()) |
| 502 | cache_path = config_dir / "last-report.json" |
| 503 | payload = json.loads(cache_path.read_text(encoding="utf-8")) |
| 504 | payload["timestamp"] = "2026-01-01T00:00:00+00:00" |
| 505 | cache_path.write_text(json.dumps(payload), encoding="utf-8") |
| 506 | |
| 507 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \ |
| 508 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 509 | mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline should not run")), \ |
| 510 | mock.patch.object(cli.sys, "argv", ["last30days.py", "--drill", "cluster 1"]): |
| 511 | stderr = io.StringIO() |
| 512 | with redirect_stderr(stderr): |
| 513 | rc = cli.main() |
| 514 | |
| 515 | assert rc == 2 |
| 516 | assert "run a research pass first" in stderr.getvalue() |
| 517 | |
| 518 | |
| 519 | def test_non_object_cache_is_unavailable_with_warning(tmp_path: Path): |
| 520 | config_dir = tmp_path / "config" |
| 521 | config_dir.mkdir() |
| 522 | (config_dir / "last-report.json").write_text("[]", encoding="utf-8") |
| 523 | |
| 524 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 525 | stderr = io.StringIO() |
| 526 | with redirect_stderr(stderr): |
| 527 | cached = cli._load_last_report_cache(None) |
| 528 | |
| 529 | assert cached is None |
| 530 | assert "Could not read report cache" in stderr.getvalue() |
| 531 | |
| 532 | |
| 533 | def test_drill_publish_html_requires_html_emit_before_dispatch(): |
| 534 | parser = cli.build_parser() |
| 535 | args = parser.parse_args(["--drill", "cluster 1", "--publish-html"]) |
| 536 | |
| 537 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 538 | mock.patch.object(cli, "_run_drill") as run_drill: |
| 539 | stderr = io.StringIO() |
| 540 | with redirect_stderr(stderr): |
| 541 | rc = cli._main(parser, args, []) |
| 542 | |
| 543 | assert rc == 2 |
| 544 | assert "--publish-html requires --emit=html" in stderr.getvalue() |
| 545 | run_drill.assert_not_called() |
| 546 | |
| 547 | |
| 548 | def test_drill_applies_config_backed_source_filters_before_dispatch(): |
| 549 | parser = cli.build_parser() |
| 550 | args = parser.parse_args([ |
| 551 | "--drill", "cluster 1", |
| 552 | "--dedicated-subreddits", "r/OpenClaw, OpenClawDev", |
| 553 | "--polymarket-keywords", "API, Policy", |
| 554 | ]) |
| 555 | |
| 556 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 557 | mock.patch.object(cli, "_run_drill", return_value=0) as run_drill: |
| 558 | assert cli._main(parser, args, []) == 0 |
| 559 | |
| 560 | drill_config = run_drill.call_args.args[1] |
| 561 | assert drill_config["_dedicated_subreddits"] == ["OpenClaw", "OpenClawDev"] |
| 562 | assert drill_config["_polymarket_keywords"] == ["api", "policy"] |
| 563 | |
| 564 | |
| 565 | def test_drill_inherits_cached_historical_window(tmp_path: Path): |
| 566 | config_dir = tmp_path / "config" |
| 567 | cached_report = _report() |
| 568 | cached_report.range_from = "2026-05-01" |
| 569 | cached_report.range_to = "2026-05-08" |
| 570 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 571 | cli._write_last_run("OpenClaw", cached_report) |
| 572 | |
| 573 | args = cli.build_parser().parse_args(["--drill", "cluster 1", "--mock"]) |
| 574 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \ |
| 575 | mock.patch.object(cli.pipeline, "diagnose", return_value={}), \ |
| 576 | mock.patch.object(cli.pipeline, "run", return_value=_report(drill=True)) as run_mock, \ |
| 577 | mock.patch.object(cli, "_show_runtime_ui"), \ |
| 578 | redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): |
| 579 | assert cli._run_drill(args, {}) == 0 |
| 580 | |
| 581 | assert run_mock.call_args.kwargs["lookback_days"] == 7 |
| 582 | assert run_mock.call_args.kwargs["as_of_date"] == "2026-05-08" |
| 583 | |
| 584 | |
| 585 | def test_drill_uses_cached_financial_topic_while_plan_stays_cluster_focused(tmp_path: Path): |
| 586 | config_dir = tmp_path / "config" |
| 587 | cached_report = _report() |
| 588 | stock_item = _item( |
| 589 | "now", |
| 590 | "stocktwits", |
| 591 | "AI agent rollout", |
| 592 | "https://stocktwits.example/now", |
| 593 | ) |
| 594 | stock_candidate = _candidate(stock_item, 95) |
| 595 | cached_report.topic = "ServiceNow $NOW stock" |
| 596 | cached_report.ranked_candidates = [stock_candidate] |
| 597 | cached_report.clusters = [schema.Cluster( |
| 598 | cluster_id="cluster-1", |
| 599 | title="AI agent rollout", |
| 600 | candidate_ids=[stock_candidate.candidate_id], |
| 601 | representative_ids=[stock_candidate.candidate_id], |
| 602 | sources=["stocktwits"], |
| 603 | score=95, |
| 604 | )] |
| 605 | cached_report.items_by_source = {"stocktwits": [stock_item]} |
| 606 | cached_report.query_plan.source_weights = {"stocktwits": 1.0} |
| 607 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 608 | cli._write_last_run(cached_report.topic, cached_report) |
| 609 | |
| 610 | args = cli.build_parser().parse_args(["--drill", "cluster 1", "--mock"]) |
| 611 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \ |
| 612 | mock.patch.object(cli.pipeline, "diagnose", return_value={}), \ |
| 613 | mock.patch.object(cli.pipeline, "run", return_value=_report(drill=True)) as run_mock, \ |
| 614 | mock.patch.object(cli, "_show_runtime_ui"), \ |
| 615 | redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): |
| 616 | assert cli._run_drill(args, {}) == 0 |
| 617 | |
| 618 | call = run_mock.call_args.kwargs |
| 619 | assert call["topic"] == "ServiceNow $NOW stock" |
| 620 | assert call["external_plan"]["subqueries"][0]["search_query"] == "AI agent rollout" |
| 621 | assert call["requested_sources"] == ["stocktwits"] |
| 622 | |
| 623 | |
| 624 | @pytest.mark.parametrize( |
| 625 | ("envelope_digest", "bound"), |
| 626 | [(None, False), ("a" * 64, False), ("a" * 64, True)], |
| 627 | ) |
| 628 | def test_cli_drill_runs_deep_updates_cache_and_can_chain(tmp_path: Path, envelope_digest, bound): |
| 629 | config_dir = tmp_path / "config" |
| 630 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 631 | assert cli._write_last_run("OpenClaw", _report(), x_envelope_sha256=envelope_digest) |
| 632 | |
| 633 | parser = cli.build_parser() |
| 634 | options = ["--drill", "cluster 1", "--mock"] |
| 635 | cache_path = config_dir / "last-report.json" |
| 636 | original_run_id = json.loads(cache_path.read_bytes())["run_id"] |
| 637 | if bound: |
| 638 | options.extend(["--followup-topic=openclaw", f"--followup-run={original_run_id}"]) |
| 639 | args = parser.parse_args(options) |
| 640 | drill_result = _report(drill=True) |
| 641 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \ |
| 642 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 643 | mock.patch.object(cli.pipeline, "diagnose", return_value={}), \ |
| 644 | mock.patch.object(cli.pipeline, "run", return_value=drill_result) as run_mock, \ |
| 645 | mock.patch.object(cli, "_show_runtime_ui"), \ |
| 646 | redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()) as stderr: |
| 647 | assert cli._main(parser, args, []) == 0 |
| 648 | |
| 649 | call = run_mock.call_args.kwargs |
| 650 | assert call["depth"] == "deep" |
| 651 | assert set(call["requested_sources"]) == {"reddit", "youtube"} |
| 652 | assert set(call["external_plan"]["subqueries"][0]["sources"]) == {"reddit", "youtube"} |
| 653 | |
| 654 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 655 | cached = cli._load_last_report_cache(None, x_envelope_sha256=envelope_digest) |
| 656 | assert cached is not None |
| 657 | assert len(cached[0].artifacts["drill_history"]) == 1 |
| 658 | drill_run_id = json.loads(cache_path.read_bytes())["run_id"] |
| 659 | assert drill_run_id != original_run_id |
| 660 | assert f"[last30days] Follow-up cache ID: {drill_run_id}\n" in stderr.getvalue() |
| 661 | |
| 662 | if bound: |
| 663 | args = parser.parse_args([*options[:-1], f"--followup-run={drill_run_id}"]) |
| 664 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \ |
| 665 | mock.patch.object(cli.pipeline, "diagnose", return_value={}), \ |
| 666 | mock.patch.object(cli.pipeline, "run", return_value=drill_result), \ |
| 667 | mock.patch.object(cli, "_show_runtime_ui"), \ |
| 668 | redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): |
| 669 | assert cli._run_drill(args, {}) == 0 |
| 670 | |
| 671 | with mock.patch.object(cli.env, "CONFIG_DIR", config_dir): |
| 672 | chained = cli._load_last_report_cache(None, x_envelope_sha256=envelope_digest) |
| 673 | assert chained is not None |
| 674 | assert len(chained[0].artifacts["drill_history"]) == 2 |
| 675 | |
| 676 | |
| 677 | @pytest.mark.parametrize("concurrent_write", ["research", "freshness"]) |
| 678 | def test_bound_drill_preserves_a_concurrent_cache_write(tmp_path, monkeypatch, capsys, concurrent_write): |
| 679 | monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path) |
| 680 | monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {}) |
| 681 | monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: {}) |
| 682 | monkeypatch.setattr(cli, "_show_runtime_ui", lambda *_args, **_kwargs: None) |
| 683 | report = _report() |
| 684 | cache_path = tmp_path / "last-report.json" |
| 685 | summary_path = tmp_path / "last-run.json" |
| 686 | digest = "a" * 64 |
| 687 | assert cli._write_last_run(report.topic, report, x_envelope_sha256=digest) |
| 688 | original_cache = cache_path.read_bytes() |
| 689 | run_id = json.loads(original_cache)["run_id"] |
| 690 | capsys.readouterr() |
| 691 | published = [] |
| 692 | |
| 693 | def publish_concurrent_result(*_args, **_kwargs): |
| 694 | if concurrent_write == "research": |
| 695 | replacement = _report() |
| 696 | replacement.range_from = "2026-05-01" |
| 697 | replacement.range_to = "2026-05-08" |
| 698 | with redirect_stderr(io.StringIO()): |
| 699 | assert cli._write_last_run(report.topic, replacement, x_envelope_sha256="b" * 64) |
| 700 | else: |
| 701 | cached = cli._load_last_report_cache(report.topic, x_envelope_sha256=digest) |
| 702 | assert cached is not None |
| 703 | cached.report.freshness_verdicts = [ |
| 704 | schema.FreshnessVerdict( |
| 705 | claim_id="claim-1", |
| 706 | candidate_id="cand-ban", |
| 707 | claim="OpenClaw API ban", |
| 708 | source="reddit", |
| 709 | source_item_id="ban", |
| 710 | verdict="current", |
| 711 | checked_at="2026-05-08T12:00:00Z", |
| 712 | ) |
| 713 | ] |
| 714 | assert cli._update_cached_freshness(cached) |
| 715 | published.append((cache_path.read_bytes(), summary_path.read_bytes())) |
| 716 | return _report(drill=True) |
| 717 | |
| 718 | parser = cli.build_parser() |
| 719 | args = parser.parse_args([ |
| 720 | "--drill=cluster 1", f"--followup-topic={report.topic}", f"--followup-run={run_id}", "--mock", |
| 721 | ]) |
| 722 | with mock.patch.object(cli.pipeline, "run", side_effect=publish_concurrent_result) as run: |
| 723 | assert cli._main(parser, args, []) == 0 |
| 724 | |
| 725 | run.assert_called_once() |
| 726 | [(published_cache, published_summary)] = published |
| 727 | assert published_cache != original_cache |
| 728 | replacement_id = json.loads(published_cache)["run_id"] |
| 729 | if concurrent_write == "research": |
| 730 | assert replacement_id != run_id |
| 731 | else: |
| 732 | assert replacement_id == run_id |
| 733 | assert cache_path.read_bytes() == published_cache |
| 734 | assert summary_path.read_bytes() == published_summary |
| 735 | captured = capsys.readouterr() |
| 736 | assert "Original" in captured.out and "Deeper" in captured.out |
| 737 | assert "Follow-up cache ID:" not in captured.err |
| 738 | |
| 739 | |
| 740 | @pytest.mark.parametrize("option", [["--drill", "cluster 1"], ["--verify-freshness"]]) |
| 741 | def test_bound_cached_followup_rejects_another_topic(tmp_path, monkeypatch, capsys, option): |
| 742 | monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path) |
| 743 | report = _report() |
| 744 | assert cli._write_last_run(report.topic, report) |
| 745 | cache = tmp_path / "last-report.json" |
| 746 | before = cache.read_bytes() |
| 747 | |
| 748 | parser = cli.build_parser() |
| 749 | args = parser.parse_args([*option, "--followup-topic=Another topic", "--mock"]) |
| 750 | with mock.patch.object(cli.pipeline, "run") as run, \ |
| 751 | mock.patch.object(cli, "_verify_report_set") as verify: |
| 752 | assert cli._main(parser, args, []) == 2 |
| 753 | |
| 754 | run.assert_not_called() |
| 755 | verify.assert_not_called() |
| 756 | assert cache.read_bytes() == before |
| 757 | assert "No fresh cached report for the requested topic" in capsys.readouterr().err |
| 758 | |
| 759 | |
| 760 | @pytest.mark.parametrize("option", [["--drill", "cluster 1"], ["--verify-freshness"]]) |
| 761 | def test_bound_cached_followup_rejects_a_replacement_for_the_same_topic(tmp_path, monkeypatch, capsys, option): |
| 762 | monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path) |
| 763 | report = _report() |
| 764 | cache = tmp_path / "last-report.json" |
| 765 | assert cli._write_last_run(report.topic, report) |
| 766 | run_id = json.loads(cache.read_bytes())["run_id"] |
| 767 | assert f"[last30days] Follow-up cache ID: {run_id}\n" in capsys.readouterr().err |
| 768 | |
| 769 | replacement = copy.deepcopy(report) |
| 770 | replacement.range_from = "2026-05-01" |
| 771 | replacement.range_to = "2026-05-08" |
| 772 | assert cli._write_last_run(replacement.topic, replacement) |
| 773 | before = cache.read_bytes() |
| 774 | assert json.loads(before)["run_id"] != run_id |
| 775 | |
| 776 | parser = cli.build_parser() |
| 777 | args = parser.parse_args([*option, f"--followup-topic={report.topic}", f"--followup-run={run_id}", "--mock"]) |
| 778 | with mock.patch.object(cli.pipeline, "run") as run, \ |
| 779 | mock.patch.object(cli, "_verify_report_set") as verify: |
| 780 | assert cli._main(parser, args, []) == 2 |
| 781 | |
| 782 | run.assert_not_called() |
| 783 | verify.assert_not_called() |
| 784 | assert cache.read_bytes() == before |
| 785 | assert "No fresh cached report for the requested run" in capsys.readouterr().err |
| 786 | |
| 787 | |
| 788 | @pytest.mark.parametrize("option", ["--drill=cluster 1", "--verify-freshness"]) |
| 789 | @pytest.mark.parametrize( |
| 790 | "new_input", |
| 791 | ["--x-posts=x.json", "--reddit-threads=-", "--shortform-urls=-", "--competitors-plan=plan.json", "--plan=-"], |
| 792 | ) |
| 793 | def test_cached_followup_rejects_new_evidence_inputs(option, new_input, capsys): |
| 794 | parser = cli.build_parser() |
| 795 | args = parser.parse_args([option, new_input]) |
| 796 | with mock.patch.object(cli.env, "get_config") as config, pytest.raises(SystemExit) as error: |
| 797 | cli._main(parser, args, []) |
| 798 | assert error.value.code == 2 |
| 799 | config.assert_not_called() |
| 800 | assert "do not accept new plans or envelope files" in capsys.readouterr().err |
| 801 | |
| 802 | |
| 803 | @pytest.mark.parametrize( |
| 804 | "options", |
| 805 | [ |
| 806 | ["topic", "--verify-freshness"], |
| 807 | ["--welcome"], |
| 808 | ["--drill=cluster 1", "--preflight"], |
| 809 | ["--verify-freshness", "--resolve-browser-consent"], |
| 810 | ], |
| 811 | ) |
| 812 | @pytest.mark.parametrize(("flag", "value"), [("--followup-topic", "topic"), ("--followup-run", "a" * 32)]) |
| 813 | def test_followup_selectors_are_only_for_a_cached_action(options, flag, value, capsys): |
| 814 | parser = cli.build_parser() |
| 815 | args = parser.parse_args([*options, f"{flag}={value}"]) |
| 816 | with mock.patch.object(cli.env, "get_config") as config, pytest.raises(SystemExit) as error: |
| 817 | cli._main(parser, args, []) |
| 818 | assert error.value.code == 2 |
| 819 | config.assert_not_called() |
| 820 | assert f"{flag} requires" in capsys.readouterr().err |
| 821 | |
| 822 | |
| 823 | @pytest.mark.parametrize("drill", [True, False]) |
| 824 | def test_drill_plan_does_not_gain_jobs_via_company_topic(monkeypatch, drill): |
| 825 | plan = schema.QueryPlan( |
| 826 | intent="general", |
| 827 | freshness_mode="balanced_recent", |
| 828 | cluster_mode="story", |
| 829 | raw_topic="OpenClaw", |
| 830 | notes=["drill-mode"] if drill else [], |
| 831 | subqueries=[ |
| 832 | schema.SubQuery( |
| 833 | label="drill", |
| 834 | search_query="OpenClaw api ban", |
| 835 | ranking_query="OpenClaw api ban", |
| 836 | sources=["youtube"], |
| 837 | ) |
| 838 | ], |
| 839 | source_weights={"youtube": 1.0}, |
| 840 | ) |
| 841 | monkeypatch.setattr(pipeline, "MOCK_AVAILABLE_SOURCES", ["youtube", "jobs"]) |
| 842 | report = pipeline.run( |
| 843 | topic="OpenClaw", config={}, depth="quick", mock=True, |
| 844 | external_plan=schema.to_dict(plan), web_backend="none", |
| 845 | as_of_date="2026-07-10", |
| 846 | ) |
| 847 | |
| 848 | expected = {"youtube"} |
| 849 | assert report.query_plan.subqueries |
| 850 | assert all(set(subquery.sources) == expected for subquery in report.query_plan.subqueries) |
| 851 | |
| 852 | |
| 853 | def test_merge_collapses_exact_url_rediscoveries(): |
| 854 | base = _report() |
| 855 | drill_report = _report(drill=True) |
| 856 | old = base.items_by_source["reddit"][0] |
| 857 | new = drill_report.items_by_source["reddit"][0] |
| 858 | old.body = "Initial rumor about the account restriction." |
| 859 | new.body = "Full interview transcript explains revised enforcement and appeal procedures." |
| 860 | new.snippet = "Appeals now receive human review." |
| 861 | new.metadata = {"top_comments": [{"text": "My appeal was approved."}]} |
| 862 | new.engagement = {"score": 321} |
| 863 | |
| 864 | merged = pipeline.merge_drill_report( |
| 865 | base, drill_report, [base.clusters[0]], target="cluster 1", |
| 866 | ) |
| 867 | |
| 868 | retained = [item for item in merged.items_by_source["reddit"] if item.url == old.url] |
| 869 | assert len(retained) == 1 |
| 870 | assert retained[0].body == "Full interview transcript explains revised enforcement and appeal procedures." |
| 871 | assert retained[0].snippet == "Appeals now receive human review." |
| 872 | assert retained[0].metadata == {"top_comments": [{"text": "My appeal was approved."}]} |
| 873 | assert retained[0].engagement == {"score": 321} |
| 874 | |
| 875 | |
| 876 | def test_write_last_run_returns_false_on_failure(monkeypatch, capsys): |
| 877 | import last30days as cli |
| 878 | from lib import env |
| 879 | |
| 880 | class ExplodingPath: |
| 881 | def mkdir(self, *a, **k): |
| 882 | raise OSError("disk full") |
| 883 | |
| 884 | monkeypatch.setattr(cli.env, "CONFIG_DIR", ExplodingPath()) |
| 885 | report = _report() |
| 886 | ok = cli._write_last_run("topic", report) |
| 887 | assert ok is False |
| 888 | assert "could not write run cache" in capsys.readouterr().err |
| 889 | |
| 890 | |
| 891 | def test_drill_gates_subreddit_context_on_source_allowlist(monkeypatch): |
| 892 | import io |
| 893 | from contextlib import redirect_stdout, redirect_stderr |
| 894 | from unittest import mock |
| 895 | import last30days as cli |
| 896 | from lib import schema |
| 897 | |
| 898 | report = _report() |
| 899 | # Force a non-Reddit single-source cluster and cached subreddit context. |
| 900 | report.artifacts["resolved"] = {"subreddits": ["LocalLLaMA", "MachineLearning"]} |
| 901 | for cluster in report.clusters: |
| 902 | cluster.sources = ["youtube"] |
| 903 | for candidate in report.ranked_candidates: |
| 904 | candidate.source = "youtube" |
| 905 | candidate.sources = ["youtube"] |
| 906 | for item in candidate.source_items: |
| 907 | item.source = "youtube" |
| 908 | |
| 909 | captured = {} |
| 910 | |
| 911 | def fake_run(**kwargs): |
| 912 | captured.update(kwargs) |
| 913 | return _report(drill=True) |
| 914 | |
| 915 | args = cli.build_parser().parse_args(["--drill", "cluster 1"]) |
| 916 | snapshot = cli._CachedReport(report, None, Path("/tmp/last-report.json"), b"", None) |
| 917 | with mock.patch.object(cli, "_load_last_report_cache", return_value=snapshot), \ |
| 918 | mock.patch.object(cli.pipeline, "diagnose", return_value={}), \ |
| 919 | mock.patch.object(cli.pipeline, "run", side_effect=lambda **k: fake_run(**k)), \ |
| 920 | mock.patch.object(cli.pipeline, "merge_drill_report", side_effect=lambda r, d, c, target: r), \ |
| 921 | mock.patch.object(cli, "_write_last_run", return_value=True), \ |
| 922 | mock.patch.object(cli, "_show_runtime_ui"), \ |
| 923 | redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): |
| 924 | cli._run_drill(args, {}) |
| 925 | |
| 926 | assert "reddit" not in (captured.get("requested_sources") or []) |
| 927 | assert captured.get("subreddits") is None |
| 928 | |
| 929 | |
| 930 | def test_drill_preserves_person_identity_anchors_without_aliasing(): |
| 931 | report = _report() |
| 932 | report.query_plan.person_identity_anchors = ['Northstar Labs', 'Cedar Ventures'] |
| 933 | drill_plan = planner.build_drill_plan(report, 'cluster 1') |
| 934 | assert drill_plan.person_identity_anchors == report.query_plan.person_identity_anchors |
| 935 | drill_plan.person_identity_anchors.append('Another Organization') |
| 936 | assert report.query_plan.person_identity_anchors == ['Northstar Labs', 'Cedar Ventures'] |
| 937 | |
| 938 | |
| 939 | def test_drill_keeps_a_person_run_gate(): |
| 940 | report = _report() |
| 941 | report.query_plan.person_run = True |
| 942 | assert planner.build_drill_plan(report, 'cluster 1').person_run is True |
| 943 |