返回 last30days-skill
test_grok_bot_host_contract.py
根目录 / tests / test_grok_bot_host_contract.py
1 """Contract tests for the Grok Bot host slice of SKILL.md (R4, R12, R16; AE9).
2
3 On a Grok Bot host the model-facing contract must drive X through the
4 official path only: the X connector lane first, the X API bearer or the xAI
5 key as backups, keys written only through the engine's ``setup --store-key``
6 path, and no browser-session step of any kind. These tests read SKILL.md as
7 text - the model's runtime contract - the way tests/test_onboarding_contract.py
8 and tests/test_codex_host_contract.py do, and slice the Grok Bot passages so a
9 word that is fine elsewhere (the cookie recipes for Linux / Mac mini) cannot
10 satisfy or fail an assertion here.
11 """
12
13 from __future__ import annotations
14
15 import re
16 import unittest
17 from pathlib import Path
18
19 from tests.skill_contract import reference_text
20
21 ROOT = Path(__file__).resolve().parents[1]
22 SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"
23 CONFIGURATION = ROOT / "CONFIGURATION.md"
24 AGENTS_MD = ROOT / "AGENTS.md"
25
26 FLOW_HEADING = "### Grok Bot Prose Flow"
27 RECIPE_MARKER = "Grok Bot X recipe"
28 RECIPE_END = "**Step 1: Run the research script"
29
30 # R4 vocabulary: none of it may appear in the Grok Bot flow (case-insensitive).
31 FORBIDDEN = (
32 "cookie",
33 "box-chrome",
34 "cdp",
35 "auth_token",
36 "ct0",
37 "bird",
38 "18800",
39 "xquik",
40 "grok login",
41 "from_browser",
42 "last30days_x_backend",
43 "askuserquestion",
44 )
45
46 LANE_TAGS = ("topic", "from", "mention", "related")
47 ROW_FIELDS = (
48 "id",
49 "author_handle",
50 "created_at",
51 "text",
52 "likes",
53 "reposts",
54 "replies",
55 "quotes",
56 )
57 KEY_TOKENS = ("X_BEARER_TOKEN", "XAI_API_KEY", "--x-posts", "envelope", ".json")
58
59 HEREDOC_RE = re.compile(r"<<-?\s*([^\s]+)")
60
61
62 def _text() -> str:
63 return SKILL_MD.read_text(encoding="utf-8")
64
65
66 def _slice_between(text: str, start_marker: str, end_marker: str) -> str:
67 start = text.find(start_marker)
68 assert start != -1, f"missing marker: {start_marker!r}"
69 end = text.find(end_marker, start + len(start_marker))
70 assert end != -1, f"missing end marker after {start_marker!r}: {end_marker!r}"
71 return text[start:end]
72
73
74 def _grok_flow(text: str) -> str:
75 """The Grok Bot Prose Flow, from its heading to the next ### heading."""
76 start = text.find(FLOW_HEADING)
77 assert start != -1, f"missing {FLOW_HEADING!r}"
78 match = re.search(r"^### ", text[start + len(FLOW_HEADING):], flags=re.MULTILINE)
79 assert match is not None, "no ### heading follows the Grok Bot Prose Flow"
80 return text[start : start + len(FLOW_HEADING) + match.start()]
81
82
83 def _recipe(text: str) -> str:
84 assert RECIPE_MARKER in text, f"missing {RECIPE_MARKER!r}"
85 return text[text.index(RECIPE_MARKER):]
86
87
88 def _guaranteed_band(text: str) -> str:
89 return "\n".join(text.splitlines()[:420])
90
91
92 def _extras_passages(text: str) -> dict[str, str]:
93 step0 = text
94 assert "## Step 0: First-Run Setup Wizard" in step0
95 modal = _slice_between(step0, "### Claude Code Modal Flow", "### Non-Modal Prose Flow")
96 prose = _slice_between(step0, "### Non-Modal Prose Flow", FLOW_HEADING)
97 manual = step0[step0.index("### Manual Setup Guide") :]
98 modal_extras = _slice_between(modal, "**Extras-host X login", "**macOS browser-data permission remediation")
99 prose_extras = _slice_between(prose, "**Extras hosts", " - On **no**")
100 manual_extras = _slice_between(manual, "**X on Linux / Mac mini (repair).**", "**Reddit (free")
101 return {"modal": modal_extras, "prose": prose_extras, "manual": manual_extras}
102
103
104 def _forbidden_hits(slice_text: str) -> list[str]:
105 lowered = slice_text.lower()
106 return [word for word in FORBIDDEN if word in lowered]
107
108
109 class TestGrokBotProseFlow(unittest.TestCase):
110 def setUp(self):
111 self.text = reference_text("setup-wizard")
112 self.flow = _grok_flow(self.text)
113
114 def test_flow_is_the_third_step0_branch(self):
115 step0 = self.text
116 split = _slice_between(step0, "**Platform split", "### Claude Code Modal Flow")
117 self.assertIn("Grok Bot Prose Flow", split)
118 # Cursor stays a Non-Modal host; it is not routed to the Grok Bot flow.
119 self.assertIn("Cursor", _slice_between(step0, "### Non-Modal Prose Flow", FLOW_HEADING))
120 self.assertNotIn("Cursor", self.flow)
121
122 def test_flow_has_no_r4_vocabulary(self):
123 self.assertEqual([], _forbidden_hits(self.flow))
124
125 def test_flow_names_the_official_contract(self):
126 for token in (
127 "LAST30DAYS_HOST=grok-bot",
128 "LAST30DAYS_X_HOST_LANE=1",
129 "X_BEARER_TOKEN",
130 "XAI_API_KEY",
131 "--x-posts",
132 "search_posts_all",
133 "generated_at",
134 "window-unsupported",
135 "setup --store-key",
136 "about the last week",
137 "SETUP_COMPLETE=true",
138 "X_DECLINED=grok-bot",
139 ):
140 self.assertIn(token, self.flow, token)
141
142 def test_flow_names_the_call_counts_and_lanes(self):
143 self.assertRegex(self.flow, r"10\s*/\s*30\s*/\s*60")
144 self.assertRegex(self.flow, r"\b8\b.*\b5\b.*\b3\b")
145 for lane in LANE_TAGS:
146 self.assertIn(f"`{lane}`", self.flow, lane)
147 for field in ROW_FIELDS:
148 self.assertIn(f"`{field}`", self.flow, field)
149
150 def test_flow_names_the_x_for_grok_bot_plugin(self):
151 """The connector is the marketplace "X for Grok Bot" plugin: the flow
152 names it and keys the lane on its post-search tools, not on one
153 tool name alone (search_posts_all stays as the example)."""
154 self.assertIn('"X for Grok Bot"', self.flow)
155 self.assertIn("search_posts_all", self.flow)
156 rule = _guaranteed_band(_text())
157 self.assertIn('"X for Grok Bot"', rule)
158
159 def test_connector_step_precedes_bearer_offer(self):
160 connector = self.flow.index("search_posts_all")
161 bearer = self.flow.index("X_BEARER_TOKEN")
162 self.assertLess(connector, bearer)
163
164 def test_built_in_x_tools_come_before_the_plugin_and_need_no_setup(self):
165 native = self.flow.index("namespace `x`")
166 plugin = self.flow.index('"X for Grok Bot"')
167 bearer = self.flow.index("X_BEARER_TOKEN")
168 self.assertLess(native, plugin)
169 self.assertLess(plugin, bearer)
170 self.assertIn("nothing to configure", self.flow)
171 self.assertIn("only when neither is present", self.flow)
172
173 def test_lane_signal_is_exported_only_after_a_fetch_returned_posts(self):
174 self.assertIn("only in an engine shell whose fetch returned posts", self.flow)
175
176 def test_bearer_coverage_caveat_never_implies_parity(self):
177 self.assertIn(
178 "recent posts, about the last week, unless your X developer project has full-archive access",
179 self.flow,
180 )
181 self.assertIn("X developer console", self.flow)
182 self.assertIn("console.x.ai", self.flow)
183
184 def test_key_persistence_only_through_engine_and_masked(self):
185 self.assertIn("setup --store-key", self.flow)
186 self.assertIn("=****", self.flow)
187 self.assertIn("never echo the value back", self.flow)
188 for line in self.flow.splitlines():
189 if not re.search(r"\b(echo|printf)\b", line):
190 continue
191 writes = re.search(r"\b(echo|printf)\b[^\n]*(>>|>|\|)", line)
192 if writes and any(token in line for token in KEY_TOKENS):
193 self.fail(f"a shell write of a key or the envelope: {line.strip()!r}")
194
195 def test_every_heredoc_in_flow_uses_single_quoted_delimiter(self):
196 for delim in HEREDOC_RE.findall(self.flow):
197 self.assertTrue(delim.startswith("'"), f"unquoted heredoc delimiter {delim!r}")
198
199 def test_flow_declines_write_marker_and_has_no_modals(self):
200 self.assertIn("X_DECLINED=grok-bot", self.flow)
201 self.assertNotIn("AskUserQuestion", self.flow)
202
203
204 class TestGuaranteedLoadedRule(unittest.TestCase):
205 def setUp(self):
206 self.band = _guaranteed_band(_text())
207
208 def test_rule_lives_in_the_guaranteed_loaded_band(self):
209 self.assertIn("LAST30DAYS_HOST=grok-bot", self.band)
210 self.assertIn("LAST30DAYS_X_HOST_LANE=1", self.band)
211 self.assertIn("never place post text unquoted", self.band.lower())
212 self.assertIn("CURSOR_AGENT", self.band)
213
214 def test_rule_is_not_keyed_on_cursor_agent_alone(self):
215 start = self.band.index("LAST30DAYS_HOST=grok-bot")
216 rule = self.band[max(0, start - 600) : start + 1200]
217 self.assertIn("CURSOR_AGENT", rule)
218 self.assertRegex(rule, r"(?i)not .*CURSOR_AGENT.*alone|CURSOR_AGENT.*alone")
219
220
221 class TestConnectorRecipe(unittest.TestCase):
222 def setUp(self):
223 self.recipe = _recipe(reference_text("grok-bot-x"))
224
225 def test_recipe_precedes_the_engine_command(self):
226 text = reference_text("research-runbook")
227 research = text[text.index("## Research Execution") :]
228 self.assertLess(research.index("grok-bot-x.md"), research.index(RECIPE_END))
229 self.assertIn("before", research[:research.index(RECIPE_END)].lower())
230
231 def test_recipe_names_counts_window_and_status(self):
232 for token in (
233 "search_posts_all",
234 "-is:retweet",
235 "window-unsupported",
236 "partial",
237 "generated_at",
238 "last30days-x-posts/1",
239 "--x-posts",
240 "x_posts",
241 "--competitors-plan",
242 "X via X connector",
243 "LAW 9",
244 "stderr",
245 ):
246 self.assertIn(token, self.recipe, token)
247 self.assertRegex(self.recipe, r"10 .*30 .*60")
248 for lane in LANE_TAGS:
249 self.assertIn(f'"lane": "{lane}"', self.recipe, lane)
250 for field in ROW_FIELDS:
251 self.assertIn(f'"{field}"', self.recipe, field)
252
253 def test_recipe_forbids_raw_tool_output_in_error(self):
254 self.assertIn("never raw tool output", self.recipe)
255 for category in ("credits", "not-connected", "unavailable"):
256 self.assertIn(category, self.recipe)
257
258 def test_recipe_heredocs_are_single_quoted_and_no_echo_writes(self):
259 for delim in HEREDOC_RE.findall(self.recipe):
260 self.assertTrue(delim.startswith("'"), f"unquoted heredoc delimiter {delim!r}")
261 for line in self.recipe.splitlines():
262 if re.search(r"\b(echo|printf)\b[^\n]*(>>|>|\|)", line) and any(
263 token in line for token in KEY_TOKENS
264 ):
265 self.fail(f"a shell write of the envelope: {line.strip()!r}")
266
267 def test_recipe_heredoc_sentinel_is_per_run_and_json_is_one_line(self):
268 """Post text is attacker-controlled: a fixed public sentinel could be
269 echoed by a post to close the heredoc early. The recipe demands a
270 per-run nonce in both sentinel lines and single-line JSON."""
271 delims = HEREDOC_RE.findall(self.recipe)
272 self.assertTrue(any("X_POSTS_EOF_{X_POSTS_NONCE}" in d for d in delims), delims)
273 self.assertNotIn("<<'X_POSTS_EOF'", self.recipe)
274 self.assertIn("\nX_POSTS_EOF_{X_POSTS_NONCE}\n", self.recipe)
275 self.assertIn("ONE line", self.recipe)
276 self.assertIn("random", self.recipe)
277
278 def test_recipe_has_no_r4_vocabulary(self):
279 self.assertEqual([], _forbidden_hits(self.recipe))
280
281 def test_recipe_names_both_host_lanes_by_source_before_the_engine_chain(self):
282 plugin = self.recipe.index('"X for Grok Bot"')
283 native = self.recipe.index("namespace `x`")
284 bearer = self.recipe.index("X_BEARER_TOKEN")
285 self.assertLess(native, plugin)
286 self.assertLess(plugin, bearer)
287 self.assertIn("never by its name", self.recipe)
288 for token in ('"provider": "x-native"', '"x-connector"', "X via Grok Bot X"):
289 self.assertIn(token, self.recipe, token)
290
291 def test_recipe_pages_recency_to_the_depth_count(self):
292 for token in ("`recency`", "next_token", "max_results", "ONE envelope call", "note_tweet"):
293 self.assertIn(token, self.recipe, token)
294 for metric in ("like_count", "retweet_count", "reply_count", "quote_count"):
295 self.assertIn(metric, self.recipe, metric)
296
297 def test_recipe_samples_popular_posts_across_the_whole_window(self):
298 self.assertIn("popular pass", self.recipe)
299 popular = self.recipe[self.recipe.index("popular pass"):]
300 popular = popular[: popular.index("\n")]
301 self.assertIn("first topic query only", popular)
302 self.assertIn("10 equal slices", popular)
303 self.assertIn("`relevancy`", popular)
304 self.assertIn("ONE envelope call", popular)
305
306 def test_recipe_keeps_the_envelope_inside_engine_limits(self):
307 self.assertIn("500 posts per call", self.recipe)
308 self.assertIn("1,000 posts and 20 calls in total", self.recipe)
309 self.assertIn("drop discovered-author calls first", self.recipe)
310
311 def test_comparison_uses_envelopes_only_when_every_entity_has_posts(self):
312 self.assertIn("only when every entity's fetch returned posts", self.recipe)
313
314 def test_comparison_paces_tool_calls_under_the_per_minute_limit(self):
315 self.assertIn("no minute holds more than 30 tool calls", self.recipe)
316 self.assertIn("popular pass for the main entity only", self.recipe)
317
318 def test_recipe_gives_discovered_authors_full_handle_lanes(self):
319 authors = self.recipe[self.recipe.index("**Discovered authors.**"):]
320 authors = authors[: authors.index("\n - ")]
321 self.assertIn("`from` call", authors)
322 self.assertIn("8 posts", authors)
323 self.assertIn("`mention` call", authors)
324 self.assertIn("5 posts", authors)
325 self.assertIn("`--x-related`", authors)
326
327 def test_related_calls_are_only_for_handles_the_user_passed(self):
328 self.assertIn("Per handle the user explicitly passed with `--x-related`", self.recipe)
329 self.assertIn("A discovered author never gets a `related` call.", self.recipe)
330 self.assertIn("These are a discovered author's only calls.", self.recipe)
331
332 def test_recipe_window_uses_the_engines_utc_date(self):
333 self.assertIn("today's UTC date", self.recipe)
334
335 def test_recipe_exports_the_lane_only_after_posts_came_back(self):
336 self.assertIn("only when a lane returned posts", self.recipe)
337 self.assertIn("unset LAST30DAYS_X_HOST_LANE", self.recipe)
338
339
340 class TestExtrasPassagesRescoped(unittest.TestCase):
341 def test_extras_passages_no_longer_name_grok_bot(self):
342 for name, passage in _extras_passages(reference_text("setup-wizard")).items():
343 self.assertNotIn("Grok Bot", passage, f"{name} extras passage still names Grok Bot")
344 self.assertIn("grok-bot", passage, f"{name} extras passage does not exclude the grok-bot host")
345
346 def test_manual_repair_heading_rescoped(self):
347 text = reference_text("setup-wizard")
348 self.assertIn("**X on Linux / Mac mini (repair).**", text)
349 self.assertNotIn("X on Linux / Grok Bot / Mac mini", text)
350
351
352 class TestManualSetupGuide(unittest.TestCase):
353 def setUp(self):
354 step0 = reference_text("setup-wizard")
355 self.manual = step0[step0.index("### Manual Setup Guide") :]
356
357 def test_bearer_bullet_comes_first_in_x_section(self):
358 x_section = _slice_between(self.manual, "**X/Twitter (pick one", "**X on Linux / Mac mini (repair).**")
359 bullets = [line for line in x_section.splitlines() if line.startswith("- ")]
360 self.assertTrue(bullets, "no X bullets in the Manual Setup Guide")
361 self.assertIn("X_BEARER_TOKEN", bullets[0])
362 self.assertIn("about a week", bullets[0])
363
364 def test_grok_bot_repair_paragraph_is_official_only(self):
365 para = _slice_between(self.manual, "**X on a Grok Bot (repair).**", "**X on Linux / Mac mini (repair).**")
366 self.assertEqual([], _forbidden_hits(para))
367 for token in ("connect X", "X_BEARER_TOKEN", "about the last week", "XAI_API_KEY", "top up"):
368 self.assertIn(token, para, token)
369
370
371 class TestSecurityAndFrontmatter(unittest.TestCase):
372 def test_frontmatter_optional_env_lists_bearer(self):
373 text = _text()
374 frontmatter = text[: text.index("---", 3)]
375 self.assertIn("- X_BEARER_TOKEN", frontmatter)
376
377 def test_security_section_lists_x_api_and_envelope(self):
378 text = _text()
379 security = text[text.index("## Security & Permissions") :]
380 self.assertIn("api.x.com", security)
381 self.assertIn("--x-posts", security)
382 self.assertIn("X connector", security)
383 self.assertIn("X_BEARER_TOKEN", security)
384 self.assertIn("sent only in the Authorization header", security)
385 self.assertIn("no X backend is called", security)
386
387 def test_post_write_checks_never_remove_required_sections_or_quotes(self):
388 text = reference_text("grok-bot-x")
389 self.assertIn("6. **Checks after writing.**", text)
390 self.assertIn("may never remove a section `synthesis.md` requires", text)
391 self.assertIn("a quote copied verbatim from the raw file", text)
392 self.assertIn("when a check and the template disagree, the template wins", text)
393
394
395 class TestConfigurationGrokBotSubsection(unittest.TestCase):
396 def test_configuration_grok_bot_subsection_has_no_r4_vocabulary(self):
397 text = CONFIGURATION.read_text(encoding="utf-8")
398 match = re.search(r"^(#{2,4}) [^\n]*Grok Bot[^\n]*$", text, flags=re.MULTILINE)
399 if match is None:
400 self.skipTest("CONFIGURATION.md has no Grok Bot subsection yet")
401 level = len(match.group(1))
402 rest = text[match.end() :]
403 nxt = re.search(rf"^#{{1,{level}}} ", rest, flags=re.MULTILINE)
404 section = rest if nxt is None else rest[: nxt.start()]
405 self.assertEqual([], _forbidden_hits(section))
406
407
408 class TestAgentsMd(unittest.TestCase):
409 def test_agents_md_names_three_branches(self):
410 text = AGENTS_MD.read_text(encoding="utf-8")
411 self.assertIn("Step 0 has THREE branches", text)
412 self.assertIn("Grok Bot Prose Flow", text)
413 self.assertNotIn("Step 0 has TWO branches", text)
414
415
416 if __name__ == "__main__":
417 unittest.main()
418
418 lines PYTHON