| 1 | import os |
| 2 | import subprocess |
| 3 | from pathlib import Path |
| 4 | |
| 5 | import pytest |
| 6 | |
| 7 | from lib import grok_audit, grok_x |
| 8 | |
| 9 | |
| 10 | @pytest.mark.parametrize("version", [ |
| 11 | "grok 1.0.41 (5b807183dd79) [stable]", |
| 12 | "grok 1.0.44 (5b807183dd79)", |
| 13 | "grok 1.0.45 (0123456789ab)", |
| 14 | "grok 1.0.46 (unknown) [stable]", |
| 15 | "grok 1.0.46 (2765805b9442) [beta]", |
| 16 | "grok 1.0.70 (f50904eaee6c) [alpha]", |
| 17 | "grok 1.0.46-dev (modified)", |
| 18 | "unexpected version output", |
| 19 | "", |
| 20 | ]) |
| 21 | def test_build_below_floor_or_off_stable_never_receives_credentials(monkeypatch, version): |
| 22 | calls = [] |
| 23 | staged = [] |
| 24 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 25 | monkeypatch.setattr(grok_x, "_stage_child_home", lambda path: staged.append(path)) |
| 26 | |
| 27 | def fake_run(cmd, **kwargs): |
| 28 | calls.append((cmd, kwargs)) |
| 29 | return subprocess.CompletedProcess(cmd, 0, version, "") |
| 30 | |
| 31 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 32 | response = grok_x._invoke("private research query", 60) |
| 33 | assert "unsupported grok CLI version" in response.get("error", "") |
| 34 | assert staged == [] |
| 35 | assert [cmd for cmd, _ in calls] == [["/usr/bin/grok", "--version"]] |
| 36 | assert calls[0][1]["timeout"] <= 5 |
| 37 | assert "private research query" not in str(calls) |
| 38 | |
| 39 | |
| 40 | @pytest.mark.parametrize("failure", ["nonzero", "timeout", "oserror"]) |
| 41 | def test_failed_version_check_never_stages_credentials(monkeypatch, failure): |
| 42 | staged = [] |
| 43 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 44 | monkeypatch.setattr(grok_x, "_stage_child_home", lambda path: staged.append(path)) |
| 45 | |
| 46 | def fake_run(cmd, **kwargs): |
| 47 | assert cmd == ["/usr/bin/grok", "--version"] |
| 48 | if failure == "timeout": |
| 49 | raise subprocess.TimeoutExpired(cmd, 5) |
| 50 | if failure == "oserror": |
| 51 | raise OSError("cannot launch fixture") |
| 52 | return subprocess.CompletedProcess(cmd, 1, "grok 1.0.46 (2765805b9442) [stable]", "failure") |
| 53 | |
| 54 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 55 | response = grok_x._invoke("private research query", 60) |
| 56 | assert "version" in response.get("error", "") |
| 57 | assert staged == [] |
| 58 | |
| 59 | |
| 60 | @pytest.mark.parametrize("version", [ |
| 61 | "grok 1.0.46 (2765805b9442)", |
| 62 | "grok 1.0.46 (2765805b9442) [stable]", |
| 63 | "grok 1.0.70 (f50904eaee6c)", |
| 64 | "grok 1.1.0 (0123456789ab) [stable]", |
| 65 | ]) |
| 66 | def test_audited_build_runs_x_with_only_staged_auth(monkeypatch, tmp_path, version): |
| 67 | store = tmp_path / ".grok" / "auth.json" |
| 68 | store.parent.mkdir() |
| 69 | store.write_text('{"key": "dummy-offline-key"}') |
| 70 | monkeypatch.setattr(grok_x, "token_store_path", lambda: store) |
| 71 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 72 | monkeypatch.setenv("XAI_API_KEY", "dummy-unrelated-key") |
| 73 | calls = [] |
| 74 | |
| 75 | def fake_run(cmd, **kwargs): |
| 76 | calls.append(cmd) |
| 77 | child_home = Path(kwargs["env"]["HOME"]) |
| 78 | assert "XAI_API_KEY" not in kwargs["env"] |
| 79 | if cmd == ["/usr/bin/grok", "--version"]: |
| 80 | assert not (child_home / ".grok" / "auth.json").exists() |
| 81 | return subprocess.CompletedProcess(cmd, 0, version + "\n", "") |
| 82 | assert (child_home / ".grok" / "auth.json").read_text() == store.read_text() |
| 83 | assert cmd[1:3] == ["-p", "Use x_keyword_search for OpenAI"] |
| 84 | assert "--tools" not in cmd |
| 85 | assert "--disable-web-search" in cmd |
| 86 | assert "x_search" not in cmd[cmd.index("--disallowed-tools") + 1].split(",") |
| 87 | return subprocess.CompletedProcess(cmd, 0, '{"text":"fixture X response"}', "") |
| 88 | |
| 89 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 90 | assert grok_x._invoke("Use x_keyword_search for OpenAI", 60) == { |
| 91 | "text": '{"text":"fixture X response"}', |
| 92 | } |
| 93 | assert len(calls) == 2 |
| 94 | |
| 95 | |
| 96 | @pytest.mark.parametrize("spent", [4, 10]) |
| 97 | def test_preflight_time_counts_toward_research_timeout(monkeypatch, tmp_path, spent): |
| 98 | clock = [100.0] |
| 99 | calls = [] |
| 100 | monkeypatch.setattr(grok_x.time, "monotonic", lambda: clock[0]) |
| 101 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 102 | monkeypatch.setattr(grok_x, "token_store_path", lambda: tmp_path / ".grok" / "auth.json") |
| 103 | |
| 104 | def fake_run(cmd, **kwargs): |
| 105 | calls.append(cmd) |
| 106 | if "--version" in cmd: |
| 107 | assert kwargs["timeout"] == 5 |
| 108 | clock[0] += spent |
| 109 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.46 (2765805b9442) [stable]", "") |
| 110 | assert kwargs["timeout"] == 10 - spent |
| 111 | return subprocess.CompletedProcess(cmd, 0, "fixture response", "") |
| 112 | |
| 113 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 114 | response = grok_x._invoke("X query", 10) |
| 115 | if spent < 10: |
| 116 | assert response == {"text": "fixture response"} |
| 117 | assert len(calls) == 2 |
| 118 | else: |
| 119 | assert "timed out" in response.get("error", "") |
| 120 | assert len(calls) == 1 |
| 121 | |
| 122 | |
| 123 | def test_search_reports_unsupported_build_as_source_failure(monkeypatch): |
| 124 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 125 | |
| 126 | def fake_run(cmd, **kwargs): |
| 127 | assert cmd == ["/usr/bin/grok", "--version"] |
| 128 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.45 (0123456789ab) [stable]", "") |
| 129 | |
| 130 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 131 | result = grok_x.search_x("OpenAI", "2026-07-14", "2026-08-13", depth="quick") |
| 132 | assert result["items"] == [] |
| 133 | assert "unsupported grok CLI version" in result.get("error", "") |
| 134 | |
| 135 | |
| 136 | def test_search_reports_profile_write_failure(monkeypatch, tmp_path): |
| 137 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 138 | monkeypatch.setattr(grok_x, "token_store_path", lambda: tmp_path / "missing" / "auth.json") |
| 139 | |
| 140 | def fake_run(cmd, **kwargs): |
| 141 | assert cmd == ["/usr/bin/grok", "--version"] |
| 142 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.46 (2765805b9442) [stable]", "") |
| 143 | |
| 144 | def denied(*args, **kwargs): |
| 145 | raise PermissionError("cannot write agent profile") |
| 146 | |
| 147 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 148 | monkeypatch.setattr(Path, "write_text", denied) |
| 149 | result = grok_x.search_x("OpenAI", "2026-07-14", "2026-08-13", depth="quick") |
| 150 | assert result["items"] == [] |
| 151 | assert "cannot write agent profile" in result.get("error", "") |
| 152 | |
| 153 | |
| 154 | @pytest.mark.skipif(os.name == "nt", reason="The POSIX Grok installer uses a versioned symlink") |
| 155 | def test_updater_symlink_cannot_change_build_after_version_check(monkeypatch, tmp_path): |
| 156 | audited = tmp_path / "grok-1.0.46" |
| 157 | future = tmp_path / "grok-future" |
| 158 | audited.touch() |
| 159 | future.touch() |
| 160 | launcher = tmp_path / "grok" |
| 161 | launcher.symlink_to(audited) |
| 162 | monkeypatch.setattr(grok_x, "binary_path", lambda: str(launcher)) |
| 163 | monkeypatch.setattr(grok_x, "token_store_path", lambda: tmp_path / ".grok" / "auth.json") |
| 164 | calls = [] |
| 165 | |
| 166 | def fake_run(cmd, **kwargs): |
| 167 | calls.append(cmd) |
| 168 | if "--version" in cmd: |
| 169 | launcher.unlink() |
| 170 | launcher.symlink_to(future) |
| 171 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.46 (2765805b9442)", "") |
| 172 | assert cmd[0] == str(audited) |
| 173 | return subprocess.CompletedProcess(cmd, 0, "fixture response", "") |
| 174 | |
| 175 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 176 | assert grok_x._invoke("X query", 10) == {"text": "fixture response"} |
| 177 | assert calls[0] == [str(audited), "--version"] |
| 178 | |
| 179 | |
| 180 | @pytest.mark.parametrize("verdict, message", [ |
| 181 | (grok_audit.Verdict(grok_audit.FAIL, "executed a forced shell command"), |
| 182 | "failed the grok tool-boundary audit (executed a forced shell command)"), |
| 183 | (grok_audit.Verdict(grok_audit.INCONCLUSIVE, "audit timed out"), |
| 184 | "could not complete the grok tool-boundary audit (audit timed out); it will retry next run"), |
| 185 | ]) |
| 186 | def test_build_without_a_passing_audit_never_receives_credentials(monkeypatch, verdict, message): |
| 187 | staged = [] |
| 188 | calls = [] |
| 189 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 190 | monkeypatch.setattr(grok_x, "_stage_child_home", lambda path: staged.append(path)) |
| 191 | monkeypatch.setattr(grok_audit, "verdict_for", lambda *args: verdict) |
| 192 | |
| 193 | def fake_run(cmd, **kwargs): |
| 194 | calls.append(cmd) |
| 195 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.70 (f50904eaee6c)", "") |
| 196 | |
| 197 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 198 | response = grok_x._invoke("private research query", 60) |
| 199 | assert message in response.get("error", "") |
| 200 | assert response.get("no_retry") is True |
| 201 | assert staged == [] |
| 202 | assert calls == [["/usr/bin/grok", "--version"]] |
| 203 | |
| 204 | |
| 205 | def test_rejected_build_is_not_retried_per_query(monkeypatch): |
| 206 | calls = [] |
| 207 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 208 | |
| 209 | def fake_run(cmd, **kwargs): |
| 210 | calls.append(cmd) |
| 211 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.45 (0123456789ab)", "") |
| 212 | |
| 213 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 214 | items, error, revoked = grok_x._run_query("OpenAI", "2026-07-14", "2026-08-13") |
| 215 | assert (items, revoked) == ([], False) |
| 216 | assert "unsupported grok CLI version" in error |
| 217 | assert len(calls) == 1 |
| 218 | |
| 219 | |
| 220 | @pytest.mark.skipif(os.name == "nt", reason="The npm launcher is a POSIX node script here") |
| 221 | def test_npm_launcher_runs_the_native_build_it_resolves(monkeypatch, tmp_path): |
| 222 | package = tmp_path / "node_modules" / "@xai-official" / "grok" |
| 223 | (package / "bin").mkdir(parents=True) |
| 224 | (package / "package.json").write_text('{"name": "@xai-official/grok", "version": "1.0.70"}') |
| 225 | launcher = package / "bin" / "grok" |
| 226 | launcher.write_text("#!/usr/bin/env node\nrequire('./grok-bootstrap.js');\n") |
| 227 | native = tmp_path / "grok-home" / "bin" / "grok-1.0.70" |
| 228 | native.parent.mkdir(parents=True) |
| 229 | native.write_bytes(b"native build") |
| 230 | monkeypatch.setenv("GROK_HOME", str(tmp_path / "grok-home")) |
| 231 | monkeypatch.setattr(grok_x, "binary_path", lambda: str(launcher)) |
| 232 | monkeypatch.setattr(grok_x, "token_store_path", lambda: tmp_path / ".grok" / "auth.json") |
| 233 | audited = [] |
| 234 | monkeypatch.setattr(grok_audit, "verdict_for", |
| 235 | lambda binary, line, deadline: audited.append((binary, line)) or grok_audit.Verdict(grok_audit.PASS)) |
| 236 | calls = [] |
| 237 | |
| 238 | def fake_run(cmd, **kwargs): |
| 239 | calls.append(cmd[0]) |
| 240 | if "--version" in cmd: |
| 241 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.70 (f50904eaee6c)", "") |
| 242 | return subprocess.CompletedProcess(cmd, 0, "fixture response", "") |
| 243 | |
| 244 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run) |
| 245 | assert grok_x._invoke("X query", 10) == {"text": "fixture response"} |
| 246 | assert calls == [str(native), str(native)] |
| 247 | assert audited == [(str(native), "grok 1.0.70 (f50904eaee6c)")] |
| 248 | |
| 249 | |
| 250 | @pytest.mark.parametrize("verdict", [ |
| 251 | grok_audit.Verdict(grok_audit.FAIL, "executed a forced shell command"), |
| 252 | grok_audit.Verdict(grok_audit.INCONCLUSIVE, "audit timed out"), |
| 253 | ]) |
| 254 | def test_unpassed_audit_surfaces_as_an_error_not_an_empty_window(monkeypatch, verdict): |
| 255 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 256 | monkeypatch.setattr(grok_audit, "verdict_for", lambda *args: verdict) |
| 257 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", lambda cmd, **kwargs: subprocess.CompletedProcess( |
| 258 | cmd, 0, "grok 1.0.70 (f50904eaee6c)", "")) |
| 259 | result = grok_x.search_x("OpenAI", "2026-07-14", "2026-08-13", depth="quick") |
| 260 | assert result["items"] == [] |
| 261 | assert "tool-boundary audit" in result.get("error", "") |
| 262 | |
| 263 | |
| 264 | def test_native_resolution_error_returns_a_grok_failure(monkeypatch): |
| 265 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok") |
| 266 | |
| 267 | def boom(*args, **kwargs): |
| 268 | raise PermissionError("read-only config dir") |
| 269 | |
| 270 | monkeypatch.setattr(grok_audit, "resolve_native", boom) |
| 271 | response = grok_x._invoke("X query", 10) |
| 272 | assert "native grok binary" in response["error"] |
| 273 | assert response["no_retry"] is True |
| 274 |