返回 last30days-skill
test_diagnose_compat.py
根目录 / tests / test_diagnose_compat.py
1 """Characterization tests freezing the legacy --diagnose / --preflight JSON shapes.
2
3 U4 of the doctor plan (R2): `--diagnose` and `--preflight` become frozen-shape
4 aliases once `doctor` lands. These snapshots freeze the CURRENT shapes so the
5 doctor work can prove it changed neither. Additions to the legacy shapes are
6 prohibited — new data appears only in `doctor --json` — so the key-set
7 assertions below use exact equality, not superset checks.
8
9 The two real consumers, each with an explicit test:
10
11 1. The Go MCP `preflight` tool (mcp/internal/tools/preflight.go) invokes
12 `--preflight --preflight-report-on-save-dir <dir> --emit=json` and passes
13 engine stdout through VERBATIM (`mcplib.NewToolResultText(res.Stdout)`).
14 The engine side of that contract is asserted here: the exact invocation,
15 the frozen top-level key set, the nested shapes, the conditional-writes
16 entry for the report-on-save dir, and the byte format
17 (json.dumps(..., indent=2, sort_keys=True) + newline).
18
19 2. SKILL.md reads `--diagnose`'s `available_sources` array (the engine's
20 authoritative source list). Asserted: the key exists, is a list of
21 source-name strings.
22
23 There is no SessionStart hook; last-run.json is not consumed at session start.
24
25 NOTE: snapshots re-recorded against the committed v3.10.0 baseline
26 (origin/main a5b3ca1, post-v3.9.x source wave: arxiv/techmeme/stocktwits/
27 trustpilot + the x_pending_browser_auth diag flag). The SHAPES here must
28 otherwise stay frozen; re-record only when a committed baseline legitimately
29 changes them.
30 """
31
32 import contextlib
33 import io
34 import json
35 import sys
36 import tempfile
37 import unittest
38 from contextlib import redirect_stderr, redirect_stdout
39 from pathlib import Path
40 from unittest import mock
41
42 import last30days as cli
43
44 # Source names the engine can emit in available_sources today (v3.10.0).
45 KNOWN_SOURCE_NAMES = {
46 "reddit", "x", "youtube", "tiktok", "instagram", "hackernews", "bluesky",
47 "truthsocial", "polymarket", "grounding", "xiaohongshu", "github",
48 "perplexity", "threads", "pinterest", "digg", "jobs", "linkedin",
49 "arxiv", "techmeme", "news_rss", "stocktwits", "trustpilot", "dripstack",
50 }
51
52 # ---------------------------------------------------------------------------
53 # Frozen shapes (exact key sets — additions to legacy JSON are prohibited).
54 # ---------------------------------------------------------------------------
55
56 DIAGNOSE_TOP_KEYS = {
57 "providers",
58 "local_mode",
59 "reasoning_provider",
60 "x_backend",
61 "bird_installed",
62 "bird_authenticated",
63 "bird_username",
64 "xquik_available",
65 "xquik_working",
66 "xquik_status",
67 "native_web_backend",
68 "native_search",
69 "has_scrapecreators",
70 "has_github",
71 "brightdata_installed",
72 "brightdata_authenticated",
73 "trustpilot_can_run",
74 "x_pending_browser_auth",
75 "available_sources",
76 "safe",
77 "config_source",
78 "ignored_project_config",
79 "ignored_project_config_keys",
80 "ignored_endpoint_overrides",
81 "browser_cookies",
82 "external_commands",
83 "credential_destinations",
84 "local_writes",
85 "permission_preflight",
86 }
87
88 DIAGNOSE_PROVIDERS_KEYS = {"google", "openai", "xai", "openrouter", "perplexity"}
89 DIAGNOSE_BROWSER_COOKIES_KEYS = {"mode", "browsers", "reads_values"}
90 DIAGNOSE_EXTERNAL_COMMANDS_KEYS = {
91 "yt-dlp", "digg-pp-cli", "arxiv-pp-cli", "techmeme-pp-cli", "trustpilot-pp-cli",
92 "brightdata", "gh",
93 }
94 DIAGNOSE_CREDENTIAL_DESTINATIONS_KEYS = {"global_env"}
95
96 PREFLIGHT_TOP_KEYS = {
97 "status",
98 "safe",
99 "local_reads",
100 "local_writes",
101 "conditional_writes",
102 "external_commands",
103 "credentials",
104 "network",
105 "action_items",
106 }
107 PREFLIGHT_LOCAL_READS_KEYS = {
108 "config_source",
109 "secret_stores",
110 "corpus_dirs",
111 "project_config",
112 "browser_cookies",
113 }
114 PREFLIGHT_PROJECT_CONFIG_KEYS = {"status", "trusted", "ignored_path", "ignored_keys"}
115 PREFLIGHT_BROWSER_COOKIES_KEYS = {"status", "mode", "browsers", "reads_values"}
116 PREFLIGHT_CREDENTIALS_KEYS = {
117 "google", "openai", "xai", "openrouter", "perplexity", "scrapecreators", "github",
118 # Computed inside permission_preflight from config, never surfaced through
119 # diagnose.providers (whose key set above stays frozen).
120 "x_bearer", "x_cookies", "brave", "exa", "serper", "parallel", "bluesky",
121 "truthsocial", "apify", "xquik", "brightdata", "groq", "deepline",
122 "hosted_api", "publish_password",
123 }
124 PREFLIGHT_NETWORK_KEYS = {
125 "available_sources", "hosted_mode", "native_search", "endpoint_overrides",
126 "ignored_endpoint_overrides",
127 }
128
129
130 FAKE_KEYLESS_CONFIG: dict = {}
131
132 # Obvious dummies only (repo security hygiene): used to prove key-presence
133 # booleans stay booleans and no credential value ever reaches legacy JSON.
134 FAKE_KEYED_CONFIG = {
135 "SCRAPECREATORS_API_KEY": "dummy-sc-key-not-real-000",
136 "XAI_API_KEY": "dummy-xai-key-not-real-000",
137 "BRAVE_API_KEY": "dummy-brave-key-not-real-000",
138 }
139
140
141 _BIRD_STATUS_KEYLESS = {
142 "installed": False,
143 "authenticated": False,
144 "username": None,
145 "can_install": True,
146 }
147
148
149 def _run_cli(
150 argv: list[str],
151 config: dict,
152 *,
153 extra_patches: tuple = (),
154 patch_has_stored_auth: bool = True,
155 ) -> tuple[int, str]:
156 """Run cli.main() in-process with a controlled config; return (rc, stdout).
157
158 `extra_patches` are additional `mock.patch(...)` context managers layered
159 on top of the common safe-path mock stack (e.g. to fake xurl's on-disk
160 token store instead of stubbing `has_stored_auth` directly).
161 `patch_has_stored_auth=False` omits the default `has_stored_auth` stub so
162 a caller-supplied patch (or the real function) can take its place.
163 """
164 with contextlib.ExitStack() as stack:
165 stack.enter_context(mock.patch.object(cli.env, "get_config", return_value=dict(config)))
166 stack.enter_context(mock.patch("lib.bird_x.get_bird_status", return_value=_BIRD_STATUS_KEYLESS))
167 stack.enter_context(mock.patch("lib.bird_x.is_bird_installed", return_value=False))
168 stack.enter_context(mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None))
169 stack.enter_context(mock.patch(
170 "lib.xurl_x.is_available",
171 side_effect=AssertionError(
172 "--diagnose/--preflight are safe paths and must not run the "
173 "live `xurl whoami` network check"
174 ),
175 ))
176 if patch_has_stored_auth:
177 stack.enter_context(mock.patch("lib.xurl_x.has_stored_auth", return_value=False))
178 for patch in extra_patches:
179 stack.enter_context(patch)
180 stack.enter_context(mock.patch.object(sys, "argv", ["last30days.py"] + argv))
181 stdout = io.StringIO()
182 stderr = io.StringIO()
183 with redirect_stdout(stdout), redirect_stderr(stderr):
184 rc = cli.main()
185 return rc, stdout.getvalue()
186
187
188 class DiagnoseShapeCompat(unittest.TestCase):
189 """Freeze the --diagnose JSON shape (snapshot: pre-v3.9.0 baseline)."""
190
191 def _diagnose(self, config: dict) -> dict:
192 rc, out = _run_cli(["--diagnose"], config)
193 self.assertEqual(0, rc)
194 return json.loads(out)
195
196 def test_top_level_key_set_is_frozen(self):
197 payload = self._diagnose(FAKE_KEYLESS_CONFIG)
198 self.assertEqual(DIAGNOSE_TOP_KEYS, set(payload.keys()))
199
200 def test_top_level_key_set_is_frozen_with_keys_configured(self):
201 payload = self._diagnose(FAKE_KEYED_CONFIG)
202 self.assertEqual(DIAGNOSE_TOP_KEYS, set(payload.keys()))
203
204 def test_nested_shapes_are_frozen(self):
205 payload = self._diagnose(FAKE_KEYLESS_CONFIG)
206 self.assertEqual(DIAGNOSE_PROVIDERS_KEYS, set(payload["providers"].keys()))
207 self.assertEqual(
208 DIAGNOSE_BROWSER_COOKIES_KEYS, set(payload["browser_cookies"].keys())
209 )
210 self.assertEqual(
211 DIAGNOSE_EXTERNAL_COMMANDS_KEYS, set(payload["external_commands"].keys())
212 )
213 self.assertEqual(
214 DIAGNOSE_CREDENTIAL_DESTINATIONS_KEYS,
215 set(payload["credential_destinations"].keys()),
216 )
217 # The embedded permission preflight carries the same frozen shape the
218 # --preflight alias emits.
219 self.assertEqual(
220 PREFLIGHT_TOP_KEYS, set(payload["permission_preflight"].keys())
221 )
222
223 def test_key_presence_fields_are_booleans_never_values(self):
224 payload = self._diagnose(FAKE_KEYED_CONFIG)
225 self.assertIs(True, payload["has_scrapecreators"])
226 for value in payload["providers"].values():
227 self.assertIsInstance(value, bool)
228 raw = json.dumps(payload)
229 for secret in FAKE_KEYED_CONFIG.values():
230 self.assertNotIn(secret, raw)
231
232 def test_diagnose_runs_safe_mode(self):
233 payload = self._diagnose(FAKE_KEYLESS_CONFIG)
234 self.assertIs(True, payload["safe"])
235
236 def test_skill_md_consumer_available_sources_array(self):
237 """Consumer (b): SKILL.md reads `available_sources` as the engine's
238 authoritative list of source names."""
239 payload = self._diagnose(FAKE_KEYLESS_CONFIG)
240 self.assertIn("available_sources", payload)
241 sources = payload["available_sources"]
242 self.assertIsInstance(sources, list)
243 self.assertTrue(sources, "available_sources must never be empty (reddit/hn are free)")
244 for name in sources:
245 self.assertIsInstance(name, str)
246 self.assertIn(name, KNOWN_SOURCE_NAMES)
247 # Free sources are always present even in a keyless environment.
248 for free in ("reddit", "hackernews", "polymarket", "github"):
249 self.assertIn(free, sources)
250
251
252 class DiagnoseXurlAuthWiring(unittest.TestCase):
253 """Regression for #978 / PR #1027: prove `--diagnose`'s `x_backend` and
254 `available_sources` reflect xurl_x.stored_auth_status()'s corrected
255 directory-layout detection end-to-end through the real CLI entrypoint,
256 not just at the `has_stored_auth()` unit level (test_xurl_x.py) or a
257 mocked wiring level (test_env_v3.py). Neither of those proves the two
258 compose correctly through `pipeline.diagnose()` into the exact
259 `available_sources` array SKILL.md reads.
260
261 Scope: this covers the AUTH_OK / AUTH_MISSING distinction only.
262 `has_stored_auth()` collapses AUTH_ERROR (permission-denied store) to
263 the same `False` as AUTH_MISSING, so a permission-denied store is not
264 separately observable through `--diagnose`/`available_sources` -- only
265 `doctor`'s `backends._probe_xurl` surfaces the typed AUTH_ERROR. Not
266 covered here; that distinction is doctor-only by the current design."""
267
268 def setUp(self):
269 self._tmp = tempfile.TemporaryDirectory()
270 self.addCleanup(self._tmp.cleanup)
271 self.fake_home = Path(self._tmp.name)
272 self.store = self.fake_home / ".xurl"
273 boom = mock.patch(
274 "subprocess.run",
275 side_effect=AssertionError(
276 "--diagnose is a safe path and must not spawn any subprocess"
277 ),
278 )
279 boom.start()
280 self.addCleanup(boom.stop)
281
282 def _diagnose_with_store(self, auth_yml_content: str | None) -> dict:
283 """Run `--diagnose` with `Path.home()` pointed at a fake home dir
284 holding a real `~/.xurl/auth.yml` (current directory layout);
285 `auth_yml_content=None` leaves no store at all. `Path.home()` -- not
286 `token_store_path()` -- is what's faked, so this exercises
287 `token_store_path()`'s own directory-layout logic instead of
288 bypassing it; a pre-fix `token_store_path()` returning the bare
289 `~/.xurl` directory would make this fail exactly as it did for #978.
290
291 `Path.home` is a shared class attribute, so this patch also redirects
292 any other lib module's `Path.home()` call for the duration of the
293 CLI invocation (e.g. `brightdata.gate_status`). That's inert today:
294 the paired `shutil.which` patch below makes `brightdata.is_installed()`
295 return False, short-circuiting `has_credentials()` before it would
296 reach `Path.home()`. If that short-circuit is ever removed, re-check
297 whether another module's home-relative lookup needs isolating too."""
298 if auth_yml_content is not None:
299 self.store.mkdir(exist_ok=True)
300 (self.store / "auth.yml").write_text(auth_yml_content, encoding="utf-8")
301 rc, out = _run_cli(
302 ["--diagnose"],
303 FAKE_KEYLESS_CONFIG,
304 patch_has_stored_auth=False,
305 extra_patches=(
306 mock.patch("lib.xurl_x.Path.home", return_value=self.fake_home),
307 mock.patch(
308 "lib.xurl_x.shutil.which",
309 side_effect=lambda name: "/usr/local/bin/xurl" if name == "xurl" else None,
310 ),
311 ),
312 )
313 self.assertEqual(0, rc)
314 return json.loads(out)
315
316 def test_new_layout_auth_yml_makes_xurl_the_reported_backend(self):
317 payload = self._diagnose_with_store("bearer_token:\n bearer: dummy-not-real\n")
318 self.assertEqual("xurl", payload["x_backend"])
319 self.assertIn("x", payload["available_sources"])
320
321 def test_no_store_leaves_xurl_unreported(self):
322 payload = self._diagnose_with_store(None)
323 self.assertNotEqual("xurl", payload["x_backend"])
324 self.assertFalse(
325 payload["x_pending_browser_auth"],
326 "no browser-cookie config in this test, so pending-auth must be False",
327 )
328 self.assertNotIn("x", payload["available_sources"])
329
330
331 class PreflightShapeCompat(unittest.TestCase):
332 """Freeze the --preflight JSON shape (snapshot: pre-v3.9.0 baseline)."""
333
334 MCP_SAVE_DIR = "/tmp/last30days-mcp-save-dir"
335
336 def _preflight_mcp_invocation(self, config: dict) -> tuple[str, dict]:
337 # Consumer (a): mcp/internal/tools/preflight.go builds exactly
338 # ["--preflight", "--preflight-report-on-save-dir", mcpSaveDir()]
339 # plus "--emit=json" for format=json, and passes stdout through
340 # verbatim. Mirror that invocation exactly.
341 rc, out = _run_cli(
342 [
343 "--preflight",
344 "--preflight-report-on-save-dir",
345 self.MCP_SAVE_DIR,
346 "--emit=json",
347 ],
348 config,
349 )
350 self.assertEqual(0, rc)
351 return out, json.loads(out)
352
353 def test_mcp_passthrough_top_level_key_set_is_frozen(self):
354 _, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)
355 self.assertEqual(PREFLIGHT_TOP_KEYS, set(payload.keys()))
356
357 def test_mcp_passthrough_top_level_key_set_is_frozen_with_keys(self):
358 _, payload = self._preflight_mcp_invocation(FAKE_KEYED_CONFIG)
359 self.assertEqual(PREFLIGHT_TOP_KEYS, set(payload.keys()))
360
361 def test_mcp_passthrough_nested_shapes_are_frozen(self):
362 _, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)
363 self.assertEqual(PREFLIGHT_LOCAL_READS_KEYS, set(payload["local_reads"].keys()))
364 self.assertEqual(
365 PREFLIGHT_PROJECT_CONFIG_KEYS,
366 set(payload["local_reads"]["project_config"].keys()),
367 )
368 self.assertEqual(
369 PREFLIGHT_BROWSER_COOKIES_KEYS,
370 set(payload["local_reads"]["browser_cookies"].keys()),
371 )
372 self.assertEqual(PREFLIGHT_CREDENTIALS_KEYS, set(payload["credentials"].keys()))
373 for entry in payload["credentials"].values():
374 self.assertEqual({"present", "label"}, set(entry.keys()))
375 self.assertIsInstance(entry["present"], bool)
376 self.assertEqual(PREFLIGHT_NETWORK_KEYS, set(payload["network"].keys()))
377 self.assertIsInstance(payload["network"]["available_sources"], list)
378
379 def test_mcp_passthrough_reports_conditional_write_for_save_dir(self):
380 # With --preflight-report-on-save-dir and no --save-dir, the report
381 # dir appears as a conditional write — the MCP tool relies on this to
382 # explain what a save WOULD touch.
383 _, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)
384 self.assertIn(
385 {"kind": "report_on_save", "path": self.MCP_SAVE_DIR},
386 payload["conditional_writes"],
387 )
388
389 def test_mcp_passthrough_byte_format_is_stable(self):
390 # The Go tool surfaces stdout verbatim, so the serialization format
391 # (indent=2, sort_keys=True, trailing newline) is part of the contract.
392 out, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)
393 self.assertEqual(json.dumps(payload, indent=2, sort_keys=True) + "\n", out)
394
395 def test_no_secret_values_in_preflight_output(self):
396 out, _ = self._preflight_mcp_invocation(FAKE_KEYED_CONFIG)
397 for secret in FAKE_KEYED_CONFIG.values():
398 self.assertNotIn(secret, out)
399
400
401 if __name__ == "__main__":
402 unittest.main()
403
403 lines PYTHON