返回 last30days-skill
test_pr29_doctor_backends_providers_health_ui.py
根目录 / tests / test_pr29_doctor_backends_providers_health_ui.py
1 """Regression tests for PR 29 (HIGH-055, 056, 070, 072, 074, 076).
2
3 Covers:
4 - HIGH-055: Safe stderr writes & ASCII fallbacks in lib/log.py and lib/ui.py
5 - HIGH-056: Resolved path execution in lib/health.py for Windows .cmd/.bat shims
6 - HIGH-070: X pin diagnostics in lib/doctor.py & lib/env.py
7 - HIGH-072: Doctor parity with pipeline.available_sources() & EXCLUDE_SOURCES
8 - HIGH-074: Pin whitespace stripping, Grok Bot explicit pin propagation, parallel-mcp
9 - HIGH-076: Gemini thinking-part skipping & OpenAI/OpenRouter extraction fixes
10 """
11
12 from __future__ import annotations
13
14 import ast
15 import io
16 import json
17 import os
18 import stat
19 import subprocess
20 import sys
21 from contextlib import redirect_stderr, redirect_stdout
22 from pathlib import Path
23 from unittest import mock
24
25 import pytest
26
27 from lib import backends, brightdata, doctor, env, grok_x, health, log, pipeline, providers, trustpilot, ui
28
29
30 REPO_ROOT = Path(__file__).resolve().parent.parent
31 LIB_DIR = REPO_ROOT / "skills" / "last30days" / "scripts" / "lib"
32
33
34 def _narrow_stream(encoding: str) -> tuple[io.BytesIO, io.TextIOWrapper]:
35 buf = io.BytesIO()
36 wrapper = io.TextIOWrapper(buf, encoding=encoding, errors="strict", write_through=True)
37 return buf, wrapper
38
39
40 def _probe_dep(status_map=None, default_status=health.MISSING):
41 status_map = status_map or {}
42
43 def fake(name, timeout=health.PROBE_TIMEOUT):
44 status = status_map.get(name, default_status)
45 if status == health.OK:
46 return health.DependencyProbe(name=name, status=health.OK, detail=f"{name} 1.0.0")
47 return health.DependencyProbe(
48 name=name,
49 status=status,
50 detail=f"{name} simulated {status}",
51 prescription=f"install {name}" if status == health.MISSING else f"reinstall {name}",
52 owner_pkg_manager="brew",
53 )
54
55 return fake
56
57
58 class _HermeticDoctor:
59 def __init__(self, probe_map=None, default_status=health.MISSING):
60 ytdlp_ok = (probe_map or {}).get("yt-dlp", default_status) == health.OK
61 self._patches = [
62 mock.patch("lib.health.probe_dependency", _probe_dep(probe_map, default_status)),
63 mock.patch("lib.env.is_ytdlp_available", return_value=ytdlp_ok),
64 mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=ytdlp_ok),
65 mock.patch("lib.digg.cli_searches_all_topics", return_value=True),
66 mock.patch("lib.bird_x.is_bird_installed", return_value=False),
67 mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),
68 mock.patch(
69 "lib.bird_x.get_bird_status",
70 return_value={"installed": False, "authenticated": False, "username": None, "can_install": True},
71 ),
72 mock.patch("lib.xurl_x.is_available", side_effect=AssertionError("no live xurl")),
73 mock.patch("lib.xurl_x.has_stored_auth", return_value=False),
74 mock.patch("lib.xurl_x.stored_auth_status", return_value=("missing", "no token store")),
75 mock.patch("lib.backends.which", lambda name: None),
76 mock.patch("lib.doctor._count_saved_briefs", return_value=0),
77 mock.patch("lib.doctor._last_report_path", return_value=None),
78 mock.patch("lib.doctor._probe_sources", return_value={}),
79 mock.patch("lib.library_index.fts5_available", return_value=True),
80 mock.patch.dict(os.environ, {}, clear=False),
81 ]
82
83 def __enter__(self):
84 for p in self._patches:
85 p.start()
86 os.environ.pop("CLAUDECODE", None)
87 return self
88
89 def __exit__(self, *exc):
90 for p in reversed(self._patches):
91 p.stop()
92 return False
93
94
95 # ---------------------------------------------------------------------------
96 # HIGH-055: Safe stderr writes & ASCII fallbacks in log.py and ui.py
97 # ---------------------------------------------------------------------------
98
99
100 class TestHigh055StderrEncodingSafety:
101 @pytest.mark.parametrize("encoding", ["cp1252", "ascii"])
102 def test_log_debug_and_source_log_survive_narrow_encodings(self, encoding, monkeypatch):
103 buf, stream = _narrow_stream(encoding)
104 monkeypatch.setenv("LAST30DAYS_DEBUG", "1")
105 with redirect_stderr(stream):
106 log.debug("小红书 search ✓ 🔥 — status")
107 log.source_log("Xiaohongshu", "Fetched ⏳ 3 posts ✓ 你好", tty_only=False)
108 text = buf.getvalue().decode(encoding)
109 assert "[DEBUG]" in text
110 assert "[Xiaohongshu]" in text
111 assert "Fetched" in text
112 assert "3 posts" in text
113
114 @pytest.mark.parametrize("encoding", ["cp1252", "ascii"])
115 def test_buffered_non_write_through_narrow_stream_does_not_crash_on_flush(self, encoding):
116 buf = io.BytesIO()
117 buffered = io.TextIOWrapper(
118 buf, encoding=encoding, errors="strict", line_buffering=False, write_through=False
119 )
120 log.safe_stderr_write("✓ 小红书 🔥\n", stream=buffered, flush=True)
121 text = buf.getvalue().decode(encoding)
122 assert "?" in text and text.endswith("\n")
123
124 def test_safe_stderr_write_handles_broken_pipe_oserror_none_and_bad_codec(self):
125 class _BrokenPipeStream:
126 encoding = "utf-8"
127
128 def write(self, _text):
129 raise BrokenPipeError("pipe closed")
130
131 def flush(self):
132 raise OSError("flush failed")
133
134 class _BadCodecStream:
135 encoding = "nonexistent-codec-xyz"
136
137 def __init__(self):
138 self.chunks = []
139
140 def write(self, text):
141 if not text.isascii():
142 raise UnicodeEncodeError("ascii", text, 0, 1, "not ascii")
143 self.chunks.append(text)
144
145 def flush(self):
146 pass
147
148 log.safe_stderr_write("✓ hello", stream=None)
149 log.safe_stderr_write("✓ hello", stream=_BrokenPipeStream())
150 bad = _BadCodecStream()
151 log.safe_stderr_write("✓ hello 🔥", stream=bad)
152 assert "".join(bad.chunks) == "? hello ?"
153
154 class _NonStringEncodingStream:
155 encoding = 123
156
157 def __init__(self):
158 self.chunks = []
159
160 def write(self, text):
161 self.chunks.append(text)
162
163 def flush(self):
164 pass
165
166 non_str = _NonStringEncodingStream()
167 log.safe_stderr_write("✓ ok", stream=non_str)
168 assert "".join(non_str.chunks) == "✓ ok"
169 assert ui._stderr_supports_utf8(non_str) is True
170
171 def test_source_log_tty_only_contract_preserved(self):
172 buf = io.StringIO()
173 with redirect_stderr(buf):
174 log.source_log("Test", "suppressed", tty_only=True)
175 log.source_log("Test", "visible", tty_only=False)
176 assert buf.getvalue() == "[Test] visible\n"
177
178 @pytest.mark.parametrize("encoding", ["cp1252", "ascii"])
179 def test_ui_spinner_and_progress_display_use_ascii_fallback_without_crash(self, encoding):
180 buf, stream = _narrow_stream(encoding)
181 with redirect_stderr(stream), mock.patch.object(ui, "IS_TTY", False):
182 spinner = ui.Spinner("小红书 working 🔥")
183 spinner.start()
184 spinner.update("step 2 ✓")
185 spinner.stop("done ✓")
186
187 display = ui.ProgressDisplay("小红书 AI 🔥", show_banner=True)
188 display.show_complete(source_counts={"reddit": 2, "x": 1}, display_sources=["reddit", "x"])
189 display.show_cached(age_hours=1.5)
190 display.show_error("failed 你好")
191 display.show_web_only_complete()
192 display.show_promo("both", {"available_sources": ["reddit", "grounding"]})
193 display.show_promo("x")
194 display.show_bird_auth_help()
195 ui.print_phase("done", "phase ✓ 🔥")
196 text = buf.getvalue().decode(encoding)
197 assert "-> " in text
198 assert "[ok] done" in text
199 assert "[ok] Research complete" in text
200 assert "[x] Error:" in text
201 assert "Tip:" in text
202 assert "Reddit [ok], X [x]" in text
203
204 @pytest.mark.parametrize("encoding", ["cp1252", "ascii"])
205 def test_ui_tty_spinner_and_diagnostic_banner_survive_narrow_encodings(self, encoding):
206 buf, stream = _narrow_stream(encoding)
207 diag = {
208 "available_sources": ["reddit", "xiaohongshu"],
209 "has_scrapecreators": False,
210 "bird_installed": True,
211 "x_backend": None,
212 "native_web_backend": None,
213 }
214 with redirect_stderr(stream), mock.patch.object(ui, "IS_TTY", True):
215 spinner = ui.Spinner("working 🔥")
216 spinner.running = True
217 # Run a single frame of _spin without background sleep
218 with mock.patch.object(ui.time, "sleep", side_effect=lambda _: setattr(spinner, "running", False)):
219 spinner._spin()
220 spinner.stop("finished")
221 ui.show_diagnostic_banner(diag)
222 with redirect_stderr(stream), mock.patch.object(ui, "IS_TTY", False):
223 ui.show_diagnostic_banner(diag)
224 text = buf.getvalue().decode(encoding)
225 assert "|" in text
226 assert "+-----------------------------------------------------+" in text
227 assert "[ok] Reddit" in text
228 assert "[x] X/Twitter" in text
229 assert "[!] Web" in text
230
231 def test_no_raw_sys_stderr_write_calls_in_ui_or_log(self):
232 for mod_name in ("ui.py", "log.py"):
233 tree = ast.parse((LIB_DIR / mod_name).read_text(encoding="utf-8"), filename=mod_name)
234 raw_writes = []
235 for node in ast.walk(tree):
236 if (
237 isinstance(node, ast.Call)
238 and isinstance(node.func, ast.Attribute)
239 and node.func.attr == "write"
240 and isinstance(node.func.value, ast.Attribute)
241 and node.func.value.attr == "stderr"
242 and isinstance(node.func.value.value, ast.Name)
243 and node.func.value.value.id == "sys"
244 ):
245 raw_writes.append(node.lineno)
246 assert raw_writes == [], f"raw sys.stderr.write found in {mod_name}: {raw_writes}"
247
248
249 # ---------------------------------------------------------------------------
250 # HIGH-056: health.py executes resolved path for Windows .cmd/.bat shims
251 # ---------------------------------------------------------------------------
252
253
254 class TestHigh056WindowsCmdHealthProbe:
255 @pytest.fixture(autouse=True)
256 def _clear_cache(self):
257 health.clear_dependency_probe_cache()
258 yield
259 health.clear_dependency_probe_cache()
260
261 @pytest.mark.parametrize(
262 "name,resolved,expected_args",
263 [
264 ("grok", r"C:\Users\dev\AppData\Roaming\npm\grok.cmd", ["--version"]),
265 ("brightdata", r"C:\Users\dev\AppData\Roaming\npm\brightdata.cmd", ["--version"]),
266 ("ffmpeg", r"C:\tools\ffmpeg.bat", ["-version"]),
267 ],
268 )
269 def test_probe_dependency_executes_resolved_cmd_shim_path(self, name, resolved, expected_args):
270 seen_cmds = []
271
272 def windows_createprocess_sim(cmd, **kwargs):
273 seen_cmds.append(cmd)
274 # Simulate Windows CreateProcessW without shell=True: extensionless names fail!
275 if not cmd[0].lower().endswith((".cmd", ".bat", ".exe")):
276 raise FileNotFoundError(f"WinError 2: cannot exec bare {cmd[0]!r}")
277 return subprocess.CompletedProcess(args=cmd, returncode=0, stdout=f"{name} 2.0.0\n", stderr="")
278
279 with mock.patch.object(health.shutil, "which", return_value=resolved), \
280 mock.patch.object(health.subproc, "run_with_timeout", side_effect=windows_createprocess_sim):
281 probe = health.probe_dependency(name)
282
283 assert probe.status == health.OK
284 assert probe.ok is True
285 assert "2.0.0" in probe.detail
286 assert seen_cmds == [[resolved, *expected_args]]
287
288 def test_probe_command_executes_resolved_path(self):
289 resolved = r"C:\Users\dev\AppData\Roaming\npm\grok.cmd"
290 fake = subprocess.CompletedProcess(args=[resolved, "--version"], returncode=0, stdout="1.0.0", stderr="")
291 with mock.patch.object(health.shutil, "which", return_value=resolved), \
292 mock.patch.object(health.subprocess, "run", return_value=fake) as run_mock:
293 res = health.probe_command(["grok", "--version"])
294 assert res.state == health.OK
295 assert run_mock.call_args.args[0] == [resolved, "--version"]
296
297 @pytest.mark.skipif(sys.platform == "win32", reason="POSIX executable path-with-spaces test")
298 def test_probe_dependency_runs_real_posix_binary_in_dir_with_spaces(self, tmp_path, monkeypatch):
299 spaced_dir = tmp_path / "dir with spaces"
300 spaced_dir.mkdir()
301 binary = spaced_dir / "fakecli"
302 binary.write_text("#!/bin/sh\necho fakecli 1.2.3\n", encoding="utf-8")
303 binary.chmod(binary.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
304 monkeypatch.setenv("PATH", f"{spaced_dir}{os.pathsep}/bin{os.pathsep}/usr/bin")
305 probe = health.probe_dependency("fakecli")
306 assert probe.status == health.OK
307 assert probe.ok is True
308 assert "1.2.3" in probe.detail
309
310
311 # ---------------------------------------------------------------------------
312 # HIGH-070: X pin diagnostics in doctor.py and env.py
313 # ---------------------------------------------------------------------------
314
315
316 class TestHigh070XPinDiagnostics:
317 @pytest.mark.parametrize("pin", ["xai", "xquik", "xurl", "grok", "xapi"])
318 def test_unconfigured_non_bird_pin_never_overwritten_with_will_use_bird(self, pin):
319 config = {
320 "LAST30DAYS_X_BACKEND": pin,
321 "FROM_BROWSER": "chrome",
322 "BROWSER_CONSENT": "true",
323 "_BROWSER_COOKIE_MODE": "plan_only",
324 }
325 with _HermeticDoctor(), mock.patch("lib.bird_x.is_bird_installed", return_value=True):
326 assert env.x_pending_browser_auth(config, local_only=True) is False
327 assert env.x_backend_chain(config, local_only=True) == []
328 record = doctor._x_record(config)
329
330 assert record["pinned"] is True
331 assert record["active_backend"] is None
332 assert record["tier"] == doctor.TIER_ERROR
333 assert record["status"] == health.MISSING
334 assert "will use: bird" not in (record.get("note") or "")
335 assert "browser cookies" not in (record.get("note") or "").lower()
336
337 def test_pinned_bird_with_pending_browser_auth_and_xai_key_succeeds(self):
338 config = {
339 "LAST30DAYS_X_BACKEND": "bird",
340 "FROM_BROWSER": "chrome",
341 "BROWSER_CONSENT": "true",
342 "_BROWSER_COOKIE_MODE": "plan_only",
343 "XAI_API_KEY": "dummy-xai-key",
344 }
345 with _HermeticDoctor(probe_map={"node": health.OK}), \
346 mock.patch("lib.bird_x.is_bird_installed", return_value=True):
347 assert env.x_pending_browser_auth(config, local_only=True) is True
348 record = doctor._x_record(config)
349
350 assert record["pinned"] is True
351 assert record["status"] == health.OK
352 assert record["tier"] == doctor.TIER_OK
353 assert "will use: bird" in record["note"]
354 assert "browser cookies" in record["note"].lower()
355 assert record["fix"] == ""
356 assert record["detail"] == ""
357
358 @pytest.mark.parametrize(
359 "extra_cfg",
360 [
361 {"LAST30DAYS_X_BACKEND": "bird", "XAI_API_KEY": "dummy-xai-key"},
362 {},
363 ],
364 )
365 def test_pending_bird_with_broken_node_is_never_marked_ready(self, extra_cfg):
366 """node on PATH (is_bird_installed=True) but probe_dependency('node') fails -> BROKEN, not OK."""
367 config = {
368 "FROM_BROWSER": "chrome",
369 "BROWSER_CONSENT": "true",
370 "_BROWSER_COOKIE_MODE": "plan_only",
371 **extra_cfg,
372 }
373 with _HermeticDoctor(probe_map={"node": health.BROKEN}), \
374 mock.patch("lib.bird_x.is_bird_installed", return_value=True):
375 record = doctor._x_record(config)
376 auth_path = doctor._x_auth_path(config)
377 avail = pipeline.available_sources(config, local_only=True)
378 report = doctor.build_report(config)
379
380 assert record["status"] == health.BROKEN
381 assert record["tier"] == doctor.TIER_ERROR
382 assert record["active_backend"] is None
383 assert "will use: bird" not in (record.get("note") or "")
384 assert "node" in record["detail"].lower()
385 assert "reinstall node" in record["fix"].lower()
386 bird_entry = next(b for b in record["backends"] if b["name"] == "bird")
387 assert bird_entry["status"] == health.BROKEN
388 assert "x" not in avail
389 assert "x" not in (report["permissions"].get("network") or {}).get("available_sources", [])
390 if not extra_cfg:
391 assert auth_path["armed"] is False
392
393 def test_pinned_bird_with_broken_node_keeps_broken_error_even_with_from_browser(self):
394 config = {
395 "LAST30DAYS_X_BACKEND": "bird",
396 "AUTH_TOKEN": "dummy-auth",
397 "CT0": "dummy-ct0",
398 "FROM_BROWSER": "chrome",
399 "BROWSER_CONSENT": "true",
400 "_BROWSER_COOKIE_MODE": "plan_only",
401 "XAI_API_KEY": "dummy-xai-key",
402 }
403 with _HermeticDoctor(probe_map={"node": health.BROKEN}), \
404 mock.patch("lib.bird_x.is_bird_installed", return_value=True):
405 record = doctor._x_record(config)
406
407 assert record["pinned"] is True
408 assert record["status"] == health.BROKEN
409 assert record["tier"] == doctor.TIER_ERROR
410 assert "node" in record["fix"].lower()
411
412 def test_chained_record_blames_pinned_backend_not_broken_grok_or_bird(self):
413 config = {
414 "LAST30DAYS_X_BACKEND": "xquik",
415 "XAI_API_KEY": "dummy-xai-key",
416 }
417 with _HermeticDoctor(), \
418 mock.patch("lib.backends.which", lambda n: "/usr/bin/grok" if n == "grok" else None), \
419 mock.patch("lib.grok_audit.cached_status", return_value=None), \
420 mock.patch(
421 "lib.grok_x.stored_auth_status",
422 return_value=(grok_x.AUTH_ERROR, "corrupt grok auth.json", None),
423 ):
424 record = doctor._x_record(config)
425
426 assert record["pinned"] is True
427 assert record["status"] == health.MISSING
428 assert record["tier"] == doctor.TIER_ERROR
429 assert "XQUIK_API_KEY" in record["requires"]
430 assert "XQUIK_API_KEY" in record["detail"]
431 assert "XQUIK_API_KEY" in record["fix"]
432 assert "grok" not in record["detail"].lower()
433 assert "grok" not in record["fix"].lower()
434 assert "bird" not in record["requires"].lower()
435
436 def test_chained_record_blames_pinned_backend_when_all_backends_missing(self):
437 config = {"LAST30DAYS_X_BACKEND": "xquik"}
438 with _HermeticDoctor():
439 record = doctor._x_record(config)
440
441 assert record["pinned"] is True
442 assert record["status"] == health.MISSING
443 assert record["tier"] == doctor.TIER_ERROR
444 assert "XQUIK_API_KEY" in record["requires"]
445 assert "XQUIK_API_KEY" in record["detail"]
446 assert "XQUIK_API_KEY" in record["fix"]
447
448
449 # ---------------------------------------------------------------------------
450 # HIGH-072: Doctor parity with pipeline.available_sources() & EXCLUDE_SOURCES
451 # ---------------------------------------------------------------------------
452
453
454 class TestHigh072DoctorPipelineParityAndExclude:
455 def test_pinterest_respects_include_sources(self):
456 with _HermeticDoctor():
457 no_key = doctor.build_report({})["sources"]["pinterest"]
458 key_only = doctor.build_report(
459 {"SCRAPECREATORS_API_KEY": "dummy-sc"}
460 )["sources"]["pinterest"]
461 substring = doctor.build_report(
462 {"SCRAPECREATORS_API_KEY": "dummy-sc", "INCLUDE_SOURCES": "notpinterest"}
463 )["sources"]["pinterest"]
464 opted_in = doctor.build_report(
465 {"SCRAPECREATORS_API_KEY": "dummy-sc", "INCLUDE_SOURCES": "tiktok,instagram,pinterest"}
466 )["sources"]["pinterest"]
467
468 assert no_key["status"] == "unconfigured" and no_key["tier"] == doctor.TIER_OFF
469 assert key_only["status"] == "opt-in" and key_only["audit_state"] == doctor.AUDIT_COULD_BE_ON
470 assert substring["status"] == "opt-in"
471 assert opted_in["status"] == health.OK and opted_in["tier"] == doctor.TIER_OK
472 assert "pinterest" in pipeline.available_sources(
473 {"SCRAPECREATORS_API_KEY": "dummy-sc", "INCLUDE_SOURCES": "tiktok,instagram,pinterest"}
474 )
475
476 def test_trustpilot_respects_include_sources_and_downgrades_when_cannot_run(self):
477 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}), \
478 mock.patch("lib.trustpilot.can_run_now") as can_run:
479 direct_not_opted_in = doctor._trustpilot_record({})
480 can_run.assert_not_called()
481 assert direct_not_opted_in["status"] == "opt-in"
482 assert direct_not_opted_in["tier"] == doctor.TIER_OFF
483
484 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}), \
485 mock.patch(
486 "lib.trustpilot.can_run_now",
487 return_value={"can_run": False, "session_fresh": False, "cached_companies": 0},
488 ):
489 not_opted_in = doctor.build_report({})["sources"]["trustpilot"]
490 assert not_opted_in["status"] == "opt-in"
491 assert not_opted_in["tier"] == doctor.TIER_OFF
492 assert not_opted_in["audit_state"] == doctor.AUDIT_COULD_BE_ON
493
494 # Even if a live CLI probe returns ok, un-opted-in Trustpilot stays COULD BE ON.
495 doctor._apply_probe({"sources": {"trustpilot": not_opted_in}}, {"trustpilot": {"ok": True, "probed": True}})
496 assert not_opted_in["audit_state"] == doctor.AUDIT_COULD_BE_ON
497
498 # Opted in, but no fresh session and no cached companies -> DEGRADED / NOT WORKING even after probe!
499 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}), \
500 mock.patch(
501 "lib.trustpilot.can_run_now",
502 return_value={"can_run": False, "session_fresh": False, "cached_companies": 0},
503 ):
504 cannot_run = doctor.build_report({"INCLUDE_SOURCES": "trustpilot"})["sources"]["trustpilot"]
505 assert cannot_run["status"] == health.DEGRADED
506 assert cannot_run["tier"] == doctor.TIER_WARN
507 assert cannot_run["audit_state"] == doctor.AUDIT_NOT_WORKING
508 assert "auth login" in cannot_run["fix"]
509 assert "cannot run now" in cannot_run["note"]
510 doctor._apply_probe({"sources": {"trustpilot": cannot_run}}, {"trustpilot": {"ok": True, "probed": True}})
511 assert cannot_run["audit_state"] == doctor.AUDIT_NOT_WORKING
512
513 # Opted in + fresh session -> OK!
514 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}), \
515 mock.patch(
516 "lib.trustpilot.can_run_now",
517 return_value={"can_run": True, "session_fresh": True, "cached_companies": 0},
518 ):
519 ready = doctor.build_report({"INCLUDE_SOURCES": "trustpilot"})["sources"]["trustpilot"]
520 assert ready["status"] == health.OK
521 assert ready["tier"] == doctor.TIER_OK
522
523 def test_amazon_respects_include_sources_and_probe_does_not_promote(self):
524 with _HermeticDoctor(probe_map={brightdata.CLI_BIN: health.OK}), \
525 mock.patch("lib.brightdata.has_credentials", return_value=True):
526 not_opted = doctor.build_report({})["sources"]["amazon"]
527 opted = doctor.build_report({"INCLUDE_SOURCES": "amazon"})["sources"]["amazon"]
528
529 assert not_opted["status"] == "opt-in"
530 assert not_opted["tier"] == doctor.TIER_OFF
531 assert not_opted["audit_state"] == doctor.AUDIT_COULD_BE_ON
532 assert "INCLUDE_SOURCES" in not_opted["fix"]
533 doctor._apply_probe({"sources": {"amazon": not_opted}}, {"amazon": {"ok": True, "probed": True}})
534 assert not_opted["audit_state"] == doctor.AUDIT_COULD_BE_ON
535
536 assert opted["status"] == health.OK
537 assert opted["tier"] == doctor.TIER_OK
538
539 def test_xiaohongshu_respects_include_sources(self):
540 # Direct record check proves _xiaohongshu_record makes no network calls.
541 direct_not_opted = doctor._xiaohongshu_record({"XIAOHONGSHU_API_BASE": "http://localhost:18060"})
542 direct_opted = doctor._xiaohongshu_record(
543 {"XIAOHONGSHU_API_BASE": "http://localhost:18060", "INCLUDE_SOURCES": "xiaohongshu"}
544 )
545 assert direct_not_opted["status"] == "opt-in"
546 assert direct_opted["status"] == health.OK
547
548 with _HermeticDoctor(), mock.patch("lib.env.is_xiaohongshu_available", return_value=True):
549 not_opted = doctor.build_report(
550 {"XIAOHONGSHU_API_BASE": "http://localhost:18060"}
551 )["sources"]["xiaohongshu"]
552 opted = doctor.build_report(
553 {"XIAOHONGSHU_API_BASE": "http://localhost:18060", "INCLUDE_SOURCES": "xiaohongshu"}
554 )["sources"]["xiaohongshu"]
555
556 assert not_opted["status"] == "opt-in"
557 assert not_opted["tier"] == doctor.TIER_OFF
558 assert not_opted["audit_state"] == doctor.AUDIT_COULD_BE_ON
559 assert "INCLUDE_SOURCES" in not_opted["fix"]
560 assert opted["status"] == health.OK
561 assert opted["tier"] == doctor.TIER_OK
562
563 def test_techmeme_parity_and_outdated_upgrade_guidance(self):
564 install = health.pp_install_cmd("techmeme")
565 outdated_probe = health.DependencyProbe(
566 name="techmeme-pp-cli",
567 status=health.OK,
568 outdated=True,
569 detail="2026.9.1 (older than 2026.11.1; reads only first 10 results)",
570 prescription=install,
571 )
572 with _HermeticDoctor(), \
573 mock.patch(
574 "lib.health.probe_dependency",
575 side_effect=lambda name, timeout=health.PROBE_TIMEOUT: (
576 outdated_probe if name == "techmeme-pp-cli" else _probe_dep()(name, timeout)
577 ),
578 ):
579 report = doctor.build_report({})
580 text = doctor.render_text(report)
581 rec = report["sources"]["techmeme"]
582 assert rec["status"] == health.OK
583 assert rec["fix"] == install
584 assert "older than 2026.11.1" in rec["note"]
585 assert install in text
586
587 def test_exclude_sources_marks_excluded_and_skips_live_probes(self):
588 config = {"EXCLUDE_SOURCES": "reddit, hackernews, grounding"}
589 with _HermeticDoctor():
590 report = doctor.build_report(config)
591
592 for src in ("reddit", "hackernews", "web"):
593 rec = report["sources"][src]
594 assert rec["status"] == "excluded", src
595 assert rec["tier"] == doctor.TIER_OFF, src
596 assert rec["audit_state"] == doctor.AUDIT_COULD_BE_ON, src
597 assert "EXCLUDE_SOURCES" in rec["note"], src
598 # Non-excluded source stays active
599 assert report["sources"]["polymarket"]["status"] == health.OK
600 assert report["sources"]["polymarket"]["audit_state"] == doctor.AUDIT_WORKING
601
602 # Direct _probe_source skips excluded source
603 assert doctor._probe_source("hackernews", config, 5) is None
604
605 # _probe_sources never invokes _probe_source for excluded sources
606 probed_names = []
607
608 def record_probe(name, cfg, timeout):
609 probed_names.append(name)
610 return {"ok": True, "detail": "ok", "probed": True}
611
612 with mock.patch("lib.doctor._probe_source", side_effect=record_probe):
613 results = doctor._probe_sources(config, timeout=5)
614
615 assert "reddit" not in probed_names
616 assert "hackernews" not in probed_names
617 assert "reddit" not in results
618 assert "hackernews" not in results
619 assert "polymarket" in results
620
621 def test_doctor_run_probe_omits_excluded_sources_from_probe_metadata(self):
622 config = {"EXCLUDE_SOURCES": "reddit,hackernews"}
623 stdout = io.StringIO()
624 stderr = io.StringIO()
625 with _HermeticDoctor(), \
626 mock.patch("lib.doctor._write_cache", return_value=False), \
627 redirect_stdout(stdout), redirect_stderr(stderr):
628 rc = doctor.run(config, emit_json=True, probe=True)
629 assert rc == 0
630 payload = json.loads(stdout.getvalue())
631 assert "reddit" not in payload["probe"]["sources"]
632 assert "hackernews" not in payload["probe"]["sources"]
633 assert payload["sources"]["reddit"]["status"] == "excluded"
634 assert payload["sources"]["hackernews"]["status"] == "excluded"
635
636 @pytest.mark.parametrize("token", ["web", "grounding"])
637 def test_web_and_grounding_exclusion_parity_between_doctor_and_pipeline(self, token):
638 config = {"BRAVE_API_KEY": "dummy-brave", "EXCLUDE_SOURCES": token}
639 assert {"web", "grounding"} <= env.exclude_sources(config)
640 assert {"web", "grounding"} <= pipeline._excluded_sources(config)
641 assert "grounding" not in pipeline.available_sources(config)
642 with _HermeticDoctor():
643 report = doctor.build_report(config)
644 web_rec = report["sources"]["web"]
645 assert web_rec["status"] == "excluded"
646 assert web_rec["tier"] == doctor.TIER_OFF
647 assert web_rec["audit_state"] == doctor.AUDIT_COULD_BE_ON
648 assert f"({token})" in web_rec["note"]
649 assert f"remove {token} from EXCLUDE_SOURCES" in web_rec["fix"]
650
651 @pytest.mark.parametrize("raw_exclude", ["web,grounding", "grounding, web"])
652 def test_web_and_grounding_both_excluded_lists_both_tokens_in_fix(self, raw_exclude):
653 config = {"BRAVE_API_KEY": "dummy-brave", "EXCLUDE_SOURCES": raw_exclude}
654 assert env.excluded_source_tokens("web", config) == ["web", "grounding"]
655 with _HermeticDoctor():
656 web_rec = doctor.build_report(config)["sources"]["web"]
657 assert web_rec["status"] == "excluded"
658 assert "web" in web_rec["note"] and "grounding" in web_rec["note"]
659 assert "web" in web_rec["fix"] and "grounding" in web_rec["fix"]
660 assert "remove web and grounding from EXCLUDE_SOURCES" in web_rec["fix"]
661
662 def test_excluded_xiaohongshu_never_contacts_service_in_doctor_or_pipeline(self):
663 config = {
664 "XIAOHONGSHU_API_BASE": "http://localhost:18060",
665 "INCLUDE_SOURCES": "xiaohongshu",
666 "EXCLUDE_SOURCES": "xiaohongshu",
667 }
668 with mock.patch(
669 "lib.env.is_xiaohongshu_available",
670 side_effect=AssertionError("excluded xiaohongshu must never be probed"),
671 ) as xhs_probe:
672 avail_live = pipeline.available_sources(config)
673 with _HermeticDoctor():
674 avail_local = pipeline.available_sources(config, local_only=True)
675 report = doctor.build_report(config)
676 xhs_probe.assert_not_called()
677 assert "xiaohongshu" not in avail_live
678 assert "xiaohongshu" not in avail_local
679 assert report["sources"]["xiaohongshu"]["status"] == "excluded"
680 assert report["sources"]["xiaohongshu"]["tier"] == doctor.TIER_OFF
681
682 def test_trustpilot_no_browser_reports_disabled_instead_of_login_fix(self, monkeypatch):
683 config = {
684 "INCLUDE_SOURCES": "trustpilot",
685 trustpilot.NO_BROWSER_ENV: "1",
686 }
687 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}), \
688 mock.patch("lib.pipeline.which", lambda name: f"/usr/bin/{name}"), \
689 mock.patch("lib.trustpilot.can_run_now") as can_run:
690 rec = doctor._trustpilot_record(config)
691 avail = pipeline.available_sources(config, local_only=True)
692 can_run.assert_not_called()
693 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}), \
694 mock.patch("lib.pipeline.which", lambda name: f"/usr/bin/{name}"), \
695 mock.patch(
696 "lib.trustpilot.can_run_now",
697 return_value={"can_run": False, "session_fresh": False, "cached_companies": 0},
698 ):
699 report = doctor.build_report(config)
700 assert rec["status"] == "excluded"
701 assert rec["tier"] == doctor.TIER_OFF
702 assert trustpilot.NO_BROWSER_ENV in rec["note"]
703 assert trustpilot.NO_BROWSER_ENV in rec["fix"]
704 assert "auth login" not in rec["fix"]
705 assert "trustpilot" not in avail
706 assert "trustpilot" not in (report["permissions"].get("network") or {}).get("available_sources", [])
707 assert doctor._config_fingerprint({"INCLUDE_SOURCES": "trustpilot"}) != (
708 doctor._config_fingerprint(config)
709 )
710
711 # Also honored when set only in process environment.
712 monkeypatch.setenv(trustpilot.NO_BROWSER_ENV, "1")
713 with _HermeticDoctor(probe_map={"trustpilot-pp-cli": health.OK}):
714 env_rec = doctor._trustpilot_record({"INCLUDE_SOURCES": "trustpilot"})
715 assert env_rec["status"] == "excluded"
716 assert trustpilot.NO_BROWSER_ENV in env_rec["note"]
717 assert "auth login" not in env_rec["fix"]
718
719
720 # ---------------------------------------------------------------------------
721 # HIGH-074: Pin whitespace stripping, Grok Bot explicit pin, parallel-mcp
722 # ---------------------------------------------------------------------------
723
724
725 class TestHigh074BackendsPinAndParallelMcp:
726 def test_whitespace_padded_env_pins_match_runtime(self):
727 config_xai = {"LAST30DAYS_X_BACKEND": " xai ", "XAI_API_KEY": "dummy-xai"}
728 res_xai = backends.resolve("x", config_xai)
729 assert res_xai.pinned is True
730 assert res_xai.pin == "xai"
731 assert res_xai.active_backend == "xai" == env.x_backend_chain(config_xai)[0]
732
733 config_grok_bot_bird = {
734 "LAST30DAYS_HOST": "grok-bot",
735 "LAST30DAYS_X_BACKEND": " bird ",
736 "AUTH_TOKEN": "dummy-auth",
737 "CT0": "dummy-ct0",
738 }
739 with mock.patch("lib.bird_x.is_bird_installed", return_value=True), \
740 mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None), \
741 mock.patch("lib.health.probe_dependency", _probe_dep({"node": health.OK})):
742 res_bird = backends.resolve("x", config_grok_bot_bird)
743 chain_bird = env.x_backend_chain(config_grok_bot_bird)
744 assert res_bird.pinned is True
745 assert res_bird.pin == "bird"
746 assert res_bird.active_backend == "bird" == chain_bird[0]
747
748 config_reddit = {
749 "LAST30DAYS_REDDIT_BACKEND": " SCRAPECREATORS ",
750 "SCRAPECREATORS_API_KEY": "dummy-sc",
751 }
752 res_reddit = backends.resolve("reddit", config_reddit)
753 assert res_reddit.pinned is True
754 assert res_reddit.pin == "scrapecreators"
755 assert env.reddit_scrapecreators_primary(config_reddit) is True
756
757 def test_explicit_pin_propagated_into_specs_for_policy_on_grok_bot(self):
758 config = {
759 "LAST30DAYS_HOST": "grok-bot",
760 "AUTH_TOKEN": "dummy-auth",
761 "CT0": "dummy-ct0",
762 "XAI_API_KEY": "dummy-xai",
763 }
764 with mock.patch("lib.bird_x.is_bird_installed", return_value=True), \
765 mock.patch("lib.health.probe_dependency", _probe_dep({"node": health.OK})):
766 res = backends.resolve("x", config, pin=" bird ")
767 assert res.pinned is True
768 assert res.pin == "bird"
769 assert res.active_backend == "bird"
770 assert "bird" in res.chain
771
772 with mock.patch("lib.backends.which", lambda n: "/usr/bin/grok" if n == "grok" else None), \
773 mock.patch("lib.grok_audit.cached_status", return_value=None), \
774 mock.patch(
775 "lib.grok_x.stored_auth_status",
776 return_value=(grok_x.AUTH_OK, "signed in", None),
777 ):
778 res_grok = backends.resolve("x", {"LAST30DAYS_HOST": "grok-bot"}, pin=" GROK ")
779 assert res_grok.pinned is True
780 assert res_grok.pin == "grok"
781 assert res_grok.active_backend == "grok"
782
783 def test_parallel_mcp_registered_opt_in_and_resolvable_when_pinned(self):
784 assert "parallel-mcp" in backends.WEB_BACKEND_ORDER
785 web_desc = backends.get_descriptor("web")
786 spec = next(s for s in web_desc.backends if s.name == "parallel-mcp")
787 assert spec.opt_in is True
788 assert spec.paid is False
789
790 # Never auto-selected when unpinned (keyless or native search).
791 unpinned = backends.resolve("web", {})
792 assert unpinned.active_backend == "keyless"
793 native = backends.resolve("web", {"LAST30DAYS_NATIVE_SEARCH": "1"})
794 assert native.active_backend is None
795
796 # Pinned (including with surrounding whitespace / mixed case) resolves cleanly.
797 pinned = backends.resolve("web", {}, pin=" Parallel-MCP ")
798 assert pinned.pinned is True
799 assert pinned.pin == "parallel-mcp"
800 assert pinned.active_backend == "parallel-mcp"
801 assert pinned.tier == backends.TIER_OK
802 assert "will use: parallel-mcp" in pinned.summary
803 assert "--web-backend" in pinned.summary
804
805 # Optional PARALLEL_API_KEY is surfaced cleanly without requiring it.
806 pinned_keyed = backends.resolve("web", {"PARALLEL_API_KEY": "dummy-parallel"}, pin="parallel-mcp")
807 finding = next(f for f in pinned_keyed.findings if f.name == "parallel-mcp")
808 assert "PARALLEL_API_KEY present" in finding.detail
809
810
811 # ---------------------------------------------------------------------------
812 # HIGH-076: Gemini thinking parts & OpenAI/OpenRouter extraction fixes
813 # ---------------------------------------------------------------------------
814
815
816 class TestHigh076ProviderTextExtraction:
817 def test_extract_gemini_text_skips_thought_parts_and_joins_answer_parts(self):
818 payload = {
819 "candidates": [
820 {
821 "content": {
822 "parts": [
823 {"thought": True, "text": "Let me reason about {\"wrong\": true} first."},
824 {"text": '{"intent": '},
825 {"thought": False, "text": '"how_to", "count": 2}'},
826 ]
827 }
828 }
829 ]
830 }
831 extracted = providers.extract_gemini_text(payload)
832 assert extracted == '{"intent": "how_to", "count": 2}'
833 assert providers.extract_json(extracted) == {"intent": "how_to", "count": 2}
834
835 def test_extract_gemini_text_thought_only_returns_empty_and_falls_to_next_candidate(self):
836 thought_only = {
837 "candidates": [
838 {"content": {"parts": [{"thought": True, "text": "only thinking"}]}},
839 ]
840 }
841 assert providers.extract_gemini_text(thought_only) == ""
842
843 second_candidate = {
844 "candidates": [
845 {"content": {"parts": [{"thought": True, "text": "thinking"}]}},
846 {"content": {"parts": [{"text": "real answer"}]}},
847 ]
848 }
849 assert providers.extract_gemini_text(second_candidate) == "real answer"
850
851 def test_extract_openai_text_does_not_short_circuit_on_empty_output_text(self):
852 payload = {
853 "output_text": "",
854 "output": [
855 {"type": "message", "content": [{"type": "output_text", "text": '{"ok": 1}'}]}
856 ],
857 }
858 assert providers.extract_openai_text(payload) == '{"ok": 1}'
859
860 payload_ws = {
861 "output_text": " \n ",
862 "choices": [{"message": {"content": "from choices"}}],
863 }
864 assert providers.extract_openai_text(payload_ws) == "from choices"
865
866 def test_extract_openai_text_skips_reasoning_blocks_and_prefers_output_text(self):
867 payload = {
868 "output_text": "",
869 "output": [
870 {
871 "type": "reasoning",
872 "id": "rs_1",
873 "summary": [{"type": "summary_text", "text": "Internal reasoning"}],
874 "content": [{"type": "reasoning_text", "text": "Do not return this"}],
875 },
876 {"type": "thinking", "text": "Top-level thinking block"},
877 {"thought": True, "text": "Top-level thought item"},
878 {
879 "type": "message",
880 "content": [
881 {"type": "reasoning_text", "text": "hidden thought"},
882 {"type": "output_text", "text": '{"answer": '},
883 {"type": "output_text", "text": '"final"}'},
884 ],
885 },
886 ],
887 }
888 extracted = providers.extract_openai_text(payload)
889 assert extracted == '{"answer": "final"}'
890 assert providers.extract_json(extracted) == {"answer": "final"}
891
892 def test_extract_openai_text_handles_list_typed_message_content_and_empty_item_text(self):
893 payload = {
894 "choices": [
895 {
896 "text": "",
897 "message": {
898 "role": "assistant",
899 "content": [
900 {"type": "thinking", "text": "private thoughts"},
901 {"type": "text", "text": "hello "},
902 {"type": "text", "text": "openrouter"},
903 ],
904 },
905 }
906 ]
907 }
908 assert providers.extract_openai_text(payload) == "hello openrouter"
909
910 def test_generate_json_works_end_to_end_on_gemini_thinking_and_openai_reasoning(self):
911 gemini = providers.GeminiClient("dummy-gemini-key")
912 gemini_resp = {
913 "candidates": [
914 {
915 "content": {
916 "parts": [
917 {"thought": True, "text": "Thinking about schema..."},
918 {"text": '{"scores": [10, 20]}'},
919 ]
920 }
921 }
922 ]
923 }
924 with mock.patch.object(providers.http, "post", return_value=gemini_resp):
925 assert gemini.generate_json(providers.GEMINI_PRO, "score") == {"scores": [10, 20]}
926
927 openai = providers.OpenAIClient("dummy-openai-key")
928 openai_resp = {
929 "output_text": "",
930 "output": [
931 {"type": "reasoning", "content": [{"type": "reasoning_text", "text": "thinking"}]},
932 {"type": "message", "content": [{"type": "output_text", "text": '{"scores": [30]}'}]},
933 ],
934 }
935 with mock.patch.object(providers.http, "post", return_value=openai_resp):
936 assert openai.generate_json(providers.OPENAI_DEFAULT, "score") == {"scores": [30]}
937
938 def test_extract_openai_text_survives_non_hashable_type_values(self):
939 outer_non_hashable = {
940 "output": [
941 {"type": ["reasoning"], "content": [{"type": {"kind": "x"}, "text": ""}]},
942 {
943 "type": {"role": "assistant"},
944 "content": [
945 {"type": ["meta"], "text": "fallback-part"},
946 {"type": "output_text", "text": '{"ok": true}'},
947 ],
948 },
949 ]
950 }
951 assert providers.extract_openai_text(outer_non_hashable) == '{"ok": true}'
952
953 fallback_only = {
954 "choices": [
955 {
956 "type": ["choice"],
957 "message": {
958 "content": [
959 {"type": {"kind": "x"}, "text": "valid"},
960 ]
961 },
962 }
963 ]
964 }
965 assert providers.extract_openai_text(fallback_only) == "valid"
966
966 lines PYTHON