返回 last30days-skill
test_grok_surfacing.py
根目录 / tests / test_grok_surfacing.py
1 """grok must be visible as an opt-in backup, not as a default.
2
3 Grok is demoted to opt-in only: a leftover ~/.grok/auth.json must never steal
4 the X lane. The default auto chain is bird → xai → xurl → xquik. Pin
5 LAST30DAYS_X_BACKEND=grok to enable grok explicitly.
6 """
7
8 import inspect
9 from pathlib import Path
10 from unittest import mock
11
12 from lib import backends, doctor, health, quality_nudge
13
14 REPO = Path(__file__).resolve().parent.parent
15
16
17 def test_doctor_does_not_auto_select_grok_unpinned():
18 """Doctor must NOT report 'will use: grok' for unpinned runs.
19 Grok is opt-in only; a leftover auth.json must never steal the X lane."""
20 src = inspect.getsource(doctor._x_record)
21 # The old code would check grok_x.has_stored_auth() and set status="ok"
22 # with record["will_use"]="grok" when grok was available unpinned. That
23 # promotion block is removed: no "has_stored_auth()" call that sets
24 # will_use to grok for unpinned runs.
25 #
26 # Comments may mention "will use: grok" to explain what we DON'T do, so
27 # check for the old logic pattern: has_stored_auth -> grok promotion.
28 assert "has_stored_auth" not in src
29
30
31 def test_doctor_mentions_grok_as_opt_in():
32 """Doctor comments explain that grok is opt-in only."""
33 src = inspect.getsource(doctor._x_record)
34 assert "opt-in" in src.lower()
35
36
37 def test_quality_nudge_does_not_turn_optional_x_into_a_grok_prompt():
38 src = inspect.getsource(quality_nudge)
39 assert "grok_cli_missing" not in src
40 # Unconfigured/declined X is an optional omission, never a setup nudge...
41 assert 'optional_omitted.append("x")' in src
42 assert '"cookies_missing"' not in src
43 # ...but a configured X that errored still surfaces its repair.
44 assert '"cookies_expired"' in src
45
46
47 def test_configuration_documents_the_grok_path_as_opt_in():
48 text = (REPO / "CONFIGURATION.md").read_text()
49 assert "Grok CLI (opt-in backup)" in text
50 assert "grok login" in text
51 # Document that grok requires a pin.
52 assert "LAST30DAYS_X_BACKEND=grok" in text
53
54
55 def test_configuration_pin_row_lists_opt_ins_last():
56 """Pin row shows all backends with the opt-ins (grok, xapi) last."""
57 text = (REPO / "CONFIGURATION.md").read_text()
58 # Auto-chain order first, then the opt-in backends.
59 assert "`bird` / `xai` / `xurl` / `xquik` / `grok` / `xapi`" in text
60
61
62 def test_configuration_does_not_claim_grok_is_free():
63 text = (REPO / "CONFIGURATION.md").read_text()
64 section = text[text.index("Grok CLI (opt-in backup)"):][:1200]
65 assert "draws on your Grok plan" in section or "draw on your Grok plan" in section
66
67
68 def test_configuration_documents_bird_first_chain():
69 """Auto chain is bird first: cookies beat XAI_API_KEY."""
70 text = (REPO / "CONFIGURATION.md").read_text()
71 assert "bird first" in text.lower() or "bird (browser cookies) → xai" in text.lower()
72
73
74 def test_configuration_chain_paragraph_keeps_bird_first_and_adds_grok_bot_exception():
75 """Ordinary hosts keep bird first; the Grok Bot exception is the official chain."""
76 text = (REPO / "CONFIGURATION.md").read_text()
77 start = text.index("**X backend priority (bird first).**")
78 paragraph = text[start:text.index("\n", start)]
79 assert "bird (browser cookies) → xai (API key) → xurl (OAuth2 CLI) → xquik (API key)" in paragraph
80 assert "Grok Bot" in paragraph
81 assert "xapi" in paragraph and "xai" in paragraph and "xurl" in paragraph
82 assert "X connector" in paragraph
83 # Grok CLI stays an opt-in backup on every host.
84 assert "leftover grok login never steals the X lane" in paragraph
85
86
87 def test_changelog_fragments_exist_and_changelog_is_untouched():
88 frags = list((REPO / "changelog.d").glob("*grok*")) + \
89 list((REPO / "changelog.d").glob("*bird*"))
90 if not frags:
91 # Release PRs consume fragments into CHANGELOG.md via towncrier.
92 changelog = (REPO / "CHANGELOG.md").read_text()
93 # Old text or new text about X backend changes.
94 assert "X search now works with no X credential" in changelog or "bird first" in changelog.lower()
95 return
96 assert frags, "feature PRs add a changelog.d fragment"
97
98
99 def test_official_x_api_fragments_exist_and_changelog_is_untouched():
100 """U8: two orphan fragments carry the change; CHANGELOG.md is release-owned."""
101 changed = REPO / "changelog.d" / "+grok-bot-official-x-api.changed.md"
102 added = REPO / "changelog.d" / "+x-api-backend-and-host-lane.added.md"
103 changelog = (REPO / "CHANGELOG.md").read_text()
104 if not changed.exists() and not added.exists():
105 # A release consumed the fragments into CHANGELOG.md via towncrier.
106 assert "X connector" in changelog and "xapi" in changelog
107 return
108 assert changed.exists() and added.exists(), "both U8 fragments must ship together"
109 changed_text = changed.read_text().strip()
110 added_text = added.read_text().strip()
111 assert changed_text and added_text
112 # Fragment bodies are not pasted into CHANGELOG.md by hand.
113 assert changed_text.splitlines()[0] not in changelog
114 assert added_text.splitlines()[0] not in changelog
115 for text in (changed_text, added_text):
116 lowered = text.lower()
117 # R20/R21: the fragments never name the legacy backends, cookies,
118 # a pin as an override path, or why the feature exists.
119 for banned in ("bird", "xquik", "grok cli", "cookie", "override", "xai's request", "marketplace"):
120 assert banned not in lowered, f"fragment names {banned!r}"
121
122
123 # --- SKILL.md unlock surfaces ---------------------------------------------
124
125 def _skill_md():
126 from tests.skill_contract import reference_text
127
128 return reference_text("setup-wizard")
129
130
131 def test_skill_md_does_not_check_grok_first():
132 """Grok is opt-in only: SKILL.md should NOT check for grok before cookies."""
133 text = _skill_md()
134 # The old "Check for a Grok path before asking for cookies" should be removed.
135 assert "Check for a Grok path before asking for cookies" not in text
136
137
138 def test_skill_md_presents_grok_as_opt_in_backup():
139 """SKILL.md presents grok as an opt-in backup, not a primary option."""
140 text = _skill_md()
141 assert "Grok CLI is an opt-in backup" in text
142 # Should mention the pin requirement.
143 assert "LAST30DAYS_X_BACKEND=grok" in text
144
145
146 def test_skill_md_replaces_just_in_time_unlock_with_optional_omission():
147 """A useful report ends without a second X consent or key prompt."""
148 from tests.skill_contract import contract_documents, reference_text
149
150 for name, document in contract_documents().items():
151 assert "Just-in-time X unlock" not in document, name
152 text = reference_text("synthesis")
153 section = text[text.index("Optional X omission"):][:1200]
154 assert "finish the useful findings first" in section
155 assert "Do not open a modal" in section
156
157
158 def test_skill_md_keeps_grok_paid_caveat_in_explicit_setup_path():
159 text = _skill_md()
160 section = text[text.index("Grok CLI is an opt-in backup"):][:1200]
161 assert "Do not call it free" in section
162
163
164 # --- Doctor grok-only unpinned behavior (R3/R8) -----------------------------
165
166
167 def test_doctor_grok_only_unpinned_is_not_tier_error():
168 """Unpinned grok-only is unconfigured (tier off), NOT broken (tier error).
169
170 R3: unpinned grok is 'available, unused — pin LAST30DAYS_X_BACKEND=grok'
171 R8: grok-only unpinned = X unconfigured / skipped, not auth-failed or broken
172 """
173 from lib import grok_x
174
175 config = {} # No pin, no auto-chain credentials
176 bird_status = {
177 "installed": False,
178 "authenticated": False,
179 "username": "",
180 "can_install": False,
181 }
182 # Grok is the only backend with OK status; all auto-chain backends are MISSING.
183 with (
184 mock.patch.object(grok_x, "binary_path", return_value="/usr/bin/grok"),
185 mock.patch.object(grok_x, "has_stored_auth", return_value=True),
186 mock.patch.object(grok_x, "stored_auth_status", return_value=(grok_x.AUTH_OK, "", None)),
187 mock.patch("lib.backends.which", return_value="/usr/bin/grok"),
188 mock.patch("lib.bird_x.get_bird_status", return_value=bird_status),
189 mock.patch("lib.bird_x.is_bird_installed", return_value=False),
190 mock.patch("lib.xurl_x.has_stored_auth", return_value=False),
191 ):
192 record = doctor._x_record(config)
193 # Must NOT be tier error / NOT WORKING.
194 assert record["tier"] != "error", "grok-only unpinned must not be tier error"
195 # Should be unconfigured (tier off).
196 assert record["status"] == "unconfigured"
197 assert record["tier"] == "off"
198 # Note should mention grok is available but requires a pin.
199 assert "grok" in record["note"].lower()
200 assert "pin" in record["note"].lower() or "LAST30DAYS_X_BACKEND" in record["note"]
201
202
203 def test_doctor_grok_error_unpinned_is_not_tier_error():
204 """Unpinned grok ERROR (broken store) is unconfigured, NOT tier error.
205
206 When grok's auth store is unreadable/corrupt, doctor should NOT report X
207 as NOT WORKING with a `grok login` prescription. An unused opt-in backend
208 with a broken store is still unused — tier off, not tier error.
209 """
210 from lib import grok_x
211
212 config = {} # No pin, no auto-chain credentials
213 bird_status = {
214 "installed": False,
215 "authenticated": False,
216 "username": "",
217 "can_install": False,
218 }
219 # Grok has ERROR status (unreadable store); all auto-chain backends MISSING.
220 with (
221 mock.patch.object(grok_x, "binary_path", return_value="/usr/bin/grok"),
222 mock.patch.object(grok_x, "has_stored_auth", return_value=False),
223 mock.patch.object(
224 grok_x, "stored_auth_status",
225 return_value=(grok_x.AUTH_ERROR, "store unreadable", None),
226 ),
227 mock.patch("lib.backends.which", return_value="/usr/bin/grok"),
228 mock.patch("lib.bird_x.get_bird_status", return_value=bird_status),
229 mock.patch("lib.bird_x.is_bird_installed", return_value=False),
230 mock.patch("lib.xurl_x.has_stored_auth", return_value=False),
231 ):
232 record = doctor._x_record(config)
233 # Must NOT be tier error / NOT WORKING.
234 assert record["tier"] != "error", "grok ERROR unpinned must not be tier error"
235 # Should be unconfigured (tier off).
236 assert record["status"] == "unconfigured"
237 assert record["tier"] == "off"
238 # Note should mention grok is unused/opt-in; should NOT prescribe grok login.
239 assert "grok" in record["note"].lower()
240 assert "opt-in" in record["note"].lower() or "unused" in record["note"].lower()
241 # Fix should be empty (no grok login prescription for unused opt-in).
242 assert record["fix"] == ""
243
244
245 def test_doctor_grok_store_with_pending_bird_predicts_bird():
246 """Unpinned + grok store + pending browser auth -> doctor predicts bird.
247
248 When bird is installed and browser-cookie extraction is configured,
249 doctor should predict bird (pending-cookie usable), NOT report X as
250 unconfigured due to an unused grok store. Pending bird takes precedence.
251 """
252 from lib import env, grok_x
253
254 config = {} # No pin, no static AUTH_TOKEN/CT0
255 bird_status = {
256 "installed": True, # Bird IS installed
257 "authenticated": False, # No static cookies in config
258 "username": "",
259 "can_install": True,
260 }
261 # Grok has OK status; bird is pending (installed, FROM_BROWSER configured).
262 with (
263 mock.patch.object(grok_x, "binary_path", return_value="/usr/bin/grok"),
264 mock.patch.object(grok_x, "has_stored_auth", return_value=True),
265 mock.patch.object(grok_x, "stored_auth_status", return_value=(grok_x.AUTH_OK, "", None)),
266 mock.patch("lib.backends.which", return_value="/usr/bin/grok"),
267 mock.patch("lib.bird_x.get_bird_status", return_value=bird_status),
268 mock.patch("lib.bird_x.is_bird_installed", return_value=True),
269 mock.patch("lib.xurl_x.has_stored_auth", return_value=False),
270 # Simulate x_pending_browser_auth returning True (bird pending)
271 mock.patch.object(env, "x_pending_browser_auth", return_value=True),
272 ):
273 record = doctor._x_record(config)
274 # Doctor should predict bird (pending), NOT report X as unconfigured.
275 assert record["tier"] != "off", "pending bird should not be tier off"
276 assert record["status"] != "unconfigured", "pending bird should not be unconfigured"
277 # Should be OK tier with bird prediction.
278 assert record["tier"] == "ok"
279 assert record["status"] == health.OK
280 assert "bird" in record["note"].lower()
281 assert "browser cookies" in record["note"].lower() or "cookie" in record["note"].lower()
282
283
284 def test_doctor_grok_does_not_hide_xurl_error():
285 """Unpinned + grok store + xurl ERROR -> doctor keeps xurl error, not unconfigured.
286
287 When an auto-chain backend (xurl) is configured but broken, doctor must
288 report that error with its repair guidance. Unused grok must NOT swallow
289 the genuine auto-chain failure.
290 """
291 from lib import backends as _backends
292 from lib import grok_x
293
294 config = {} # No pin
295 bird_status = {
296 "installed": False,
297 "authenticated": False,
298 "username": "",
299 "can_install": False,
300 }
301
302 # Mock xurl probe to return ERROR status
303 def mock_probe_xurl(config):
304 return _backends.BackendFinding(
305 name="xurl",
306 status=health.ERROR,
307 detail="store unreadable",
308 prescription="xurl auth oauth2 login",
309 requires="xurl CLI installed + OAuth2 login",
310 )
311
312 # Intercept _run_probe to inject xurl ERROR
313 original_run_probe = _backends._run_probe
314
315 def patched_run_probe(spec, config):
316 if spec.name == "xurl":
317 return mock_probe_xurl(config)
318 return original_run_probe(spec, config)
319
320 # Grok has OK status; xurl has ERROR (unreadable store).
321 # All other auto-chain backends are MISSING.
322 with (
323 mock.patch.object(grok_x, "binary_path", return_value="/usr/bin/grok"),
324 mock.patch.object(grok_x, "has_stored_auth", return_value=True),
325 mock.patch.object(grok_x, "stored_auth_status", return_value=(grok_x.AUTH_OK, "", None)),
326 mock.patch("lib.backends.which", side_effect=lambda cmd: "/usr/bin/grok" if cmd == "grok" else None),
327 mock.patch("lib.bird_x.get_bird_status", return_value=bird_status),
328 mock.patch("lib.bird_x.is_bird_installed", return_value=False),
329 mock.patch.object(_backends, "_run_probe", patched_run_probe),
330 ):
331 record = doctor._x_record(config)
332
333 # Doctor should NOT report X as unconfigured.
334 assert record["tier"] != "off", "xurl error must not be hidden by unused grok"
335 assert record["status"] != "unconfigured", "xurl error must not become unconfigured"
336 # Should keep the error tier and xurl repair guidance.
337 assert record["tier"] == "error"
338 # The fix should contain xurl repair guidance, not be empty.
339 assert record["fix"], "xurl repair guidance must not be cleared"
340 assert "xurl" in record["fix"].lower() or "oauth" in record["fix"].lower()
341
342
343 def test_doctor_pending_bird_does_not_hide_xurl_error():
344 """Unpinned + FROM_BROWSER + bird installed + xurl ERROR -> keeps xurl error.
345
346 Pending bird must NOT replace a record with a configured auto-chain backend
347 in ERROR. Doctor should report the xurl error with its repair guidance,
348 NOT report X as OK via pending bird.
349 """
350 from lib import backends as _backends
351 from lib import env, grok_x
352
353 config = {} # No pin, no static AUTH_TOKEN/CT0
354 bird_status = {
355 "installed": True, # Bird IS installed (for pending bird)
356 "authenticated": False, # No static cookies
357 "username": "",
358 "can_install": True,
359 }
360
361 # Mock xurl probe to return ERROR status
362 def mock_probe_xurl(config):
363 return _backends.BackendFinding(
364 name="xurl",
365 status=health.ERROR,
366 detail="store unreadable",
367 prescription="xurl auth oauth2 login",
368 requires="xurl CLI installed + OAuth2 login",
369 )
370
371 original_run_probe = _backends._run_probe
372
373 def patched_run_probe(spec, config):
374 if spec.name == "xurl":
375 return mock_probe_xurl(config)
376 return original_run_probe(spec, config)
377
378 # x_pending_browser_auth returns True (bird pending), but xurl has ERROR.
379 with (
380 mock.patch.object(grok_x, "binary_path", return_value=None),
381 mock.patch.object(grok_x, "has_stored_auth", return_value=False),
382 mock.patch("lib.backends.which", return_value=None),
383 mock.patch("lib.bird_x.get_bird_status", return_value=bird_status),
384 mock.patch("lib.bird_x.is_bird_installed", return_value=True),
385 mock.patch.object(env, "x_pending_browser_auth", return_value=True),
386 mock.patch.object(_backends, "_run_probe", patched_run_probe),
387 ):
388 record = doctor._x_record(config)
389
390 # Doctor should NOT report X as OK via pending bird.
391 assert record["tier"] != "ok", "xurl error must not be hidden by pending bird"
392 assert record["status"] != health.OK, "xurl error must not become OK"
393 # Should keep the error tier and xurl repair guidance.
394 assert record["tier"] == "error"
395 assert record["fix"], "xurl repair guidance must not be cleared"
396 assert "xurl" in record["fix"].lower() or "oauth" in record["fix"].lower()
397
397 lines PYTHON