返回 last30days-skill
test_permission_preflight.py
根目录 / tests / test_permission_preflight.py
1 """Tests for the safe permission preflight contract."""
2
3 from __future__ import annotations
4
5 import io
6 import json
7 import sys
8 from contextlib import redirect_stderr, redirect_stdout
9 from pathlib import Path
10 from unittest import mock
11
12 import last30days as cli
13 import pytest
14
15 from lib import agentcookie, chrome_cdp, cookie_extract, corpus, env, permission_preflight, pipeline, providers
16
17 DEFAULT_SAVE_DIR = "~" + "/Documents/Last30Days"
18
19
20 def _diag(**overrides):
21 base = {
22 "providers": {
23 "google": False,
24 "openai": False,
25 "xai": False,
26 "openrouter": False,
27 "perplexity": False,
28 },
29 "has_scrapecreators": False,
30 "has_github": False,
31 "available_sources": ["reddit", "hackernews", "polymarket"],
32 "safe": True,
33 "config_source": "env_only",
34 "ignored_project_config": None,
35 "ignored_project_config_keys": [],
36 "ignored_endpoint_overrides": [],
37 "browser_cookies": {"mode": "plan_only", "browsers": [], "reads_values": False},
38 "external_commands": {"yt-dlp": False, "digg-pp-cli": False, "gh": False},
39 "credential_destinations": {"global_env": None},
40 "local_writes": [],
41 "native_search": False,
42 }
43 base.update(overrides)
44 return base
45
46
47 def _diag_with_preflight(config=None, **overrides):
48 config = config or {}
49 diag = _diag(**overrides)
50 diag["permission_preflight"] = permission_preflight.build(config, diag)
51 return diag
52
53
54 def test_preflight_reports_safe_browser_default_without_cookie_values():
55 diag = _diag()
56 preflight = permission_preflight.build({}, diag)
57
58 assert preflight["status"] == "ready"
59 assert preflight["action_items"] == []
60 browser = preflight["local_reads"]["browser_cookies"]
61 assert browser == {
62 "status": "off",
63 "mode": "plan_only",
64 "browsers": [],
65 "reads_values": False,
66 }
67 text = permission_preflight.render_text(preflight)
68 assert "Browser cookies: off" in text
69 assert "cookie values" not in text
70
71
72 def test_preflight_reports_configured_browser_without_reading_values():
73 diag = _diag(
74 browser_cookies={"mode": "plan_only", "browsers": ["firefox"], "reads_values": False}
75 )
76 preflight = permission_preflight.build({"FROM_BROWSER": "firefox"}, diag)
77
78 browser = preflight["local_reads"]["browser_cookies"]
79 assert browser["status"] == "enabled_by_config"
80 assert browser["browsers"] == ["firefox"]
81 assert browser["reads_values"] is False
82 assert "preflight did not read cookie values" in permission_preflight.render_text(preflight)
83
84
85 def test_preflight_reports_conditional_report_on_save_without_definite_write():
86 preflight = permission_preflight.build(
87 {},
88 _diag(),
89 report_on_save_dir=DEFAULT_SAVE_DIR,
90 )
91
92 assert preflight["local_writes"] == []
93 assert preflight["conditional_writes"] == [
94 {"kind": "report_on_save", "path": DEFAULT_SAVE_DIR}
95 ]
96 rendered = permission_preflight.render_text(preflight)
97 assert "none planned" in rendered
98 assert f"Report (if saved): {DEFAULT_SAVE_DIR}" in rendered
99
100
101 def test_preflight_prefers_definite_save_dir_over_conditional_report_on_save(tmp_path):
102 save_dir = tmp_path / "reports"
103 preflight = permission_preflight.build(
104 {},
105 _diag(),
106 planned_save_dir=str(save_dir),
107 report_on_save_dir=DEFAULT_SAVE_DIR,
108 )
109
110 assert preflight["local_writes"] == [{"kind": "report", "path": str(save_dir)}]
111 assert preflight["conditional_writes"] == []
112
113
114 def test_preflight_dedupes_env_save_dir_against_conditional_report_on_save():
115 preflight = permission_preflight.build(
116 {"LAST30DAYS_MEMORY_DIR": DEFAULT_SAVE_DIR},
117 _diag(local_writes=[{"kind": "report", "path": DEFAULT_SAVE_DIR}]),
118 report_on_save_dir=DEFAULT_SAVE_DIR,
119 )
120
121 assert preflight["local_writes"] == [{"kind": "report", "path": DEFAULT_SAVE_DIR}]
122 assert preflight["conditional_writes"] == []
123
124
125 def test_preflight_project_config_not_active_is_not_trusted_with_trust_env():
126 preflight = permission_preflight.build(
127 {"LAST30DAYS_TRUST_PROJECT_CONFIG": "1"},
128 _diag(config_source="env_only", ignored_project_config=None),
129 )
130
131 project = preflight["local_reads"]["project_config"]
132 assert project["status"] == "not_active"
133 assert project["trusted"] is False
134
135
136 def test_preflight_reports_ignored_project_config_without_secret_values(tmp_path, monkeypatch):
137 project_env = tmp_path / ".claude" / "last30days.env"
138 project_env.parent.mkdir()
139 project_env.write_text(
140 "OPENAI_BASE_URL=https://attacker.example\nOPENAI_API_KEY=sk-not-reported\n",
141 encoding="utf-8",
142 )
143 monkeypatch.chdir(tmp_path)
144 monkeypatch.setattr(env, "CONFIG_FILE", None)
145 monkeypatch.setenv("OPENAI_API_KEY", "sk-global")
146 monkeypatch.delenv("LAST30DAYS_TRUST_PROJECT_CONFIG", raising=False)
147
148 with mock.patch.object(env, "_load_keychain", return_value={}), \
149 mock.patch.object(env, "_load_pass", return_value={}):
150 config = env.get_config(
151 policy=env.ConfigLoadPolicy(
152 browser_cookies="plan_only",
153 inspect_ignored_project_config=True,
154 )
155 )
156 diag = pipeline.diagnose(config, safe=True)
157
158 preflight = diag["permission_preflight"]
159 assert preflight["local_reads"]["project_config"]["status"] == "ignored_untrusted"
160 assert preflight["network"]["ignored_endpoint_overrides"] == ["OPENAI_BASE_URL"]
161 rendered = permission_preflight.render_text(preflight)
162 assert "Project config: ignored untrusted file" in rendered
163 assert "OPENAI_API_KEY" in rendered
164 assert "sk-not-reported" not in str(preflight)
165 assert "sk-global" not in str(preflight)
166 assert "sk-not-reported" not in rendered
167 assert "sk-global" not in rendered
168
169
170 def test_preflight_lists_active_provider_base_url_overrides():
171 config = {
172 "OPENAI_BASE_URL": "https://gateway.test/v1",
173 "OPENROUTER_BASE_URL": "https://gateway.test/v1",
174 "XAI_BASE_URL": "https://gateway.test/v1",
175 }
176 preflight = permission_preflight.build(config, _diag())
177
178 assert preflight["network"]["endpoint_overrides"] == [
179 "OPENAI_BASE_URL",
180 "OPENROUTER_BASE_URL",
181 "XAI_BASE_URL",
182 ]
183 rendered = permission_preflight.render_text(preflight)
184 assert "OPENROUTER_BASE_URL" in rendered
185 assert "gateway.test" not in rendered
186
187
188 def test_cli_preflight_propagates_file_endpoint_overrides(tmp_path, monkeypatch, capsys):
189 config_file = tmp_path / ".env"
190 config_file.write_text(
191 "XAI_BASE_URL=https://x-gateway.test/v1\n"
192 "OPENROUTER_BASE_URL=https://router-gateway.test/v1\n",
193 encoding="utf-8",
194 )
195 monkeypatch.chdir(tmp_path)
196 monkeypatch.setattr(env, "CONFIG_FILE", config_file)
197 for key in ("OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL"):
198 monkeypatch.setenv(key, "")
199 monkeypatch.setattr(sys, "argv", ["last30days.py", "--preflight", "--emit=json"])
200
201 with mock.patch.object(env, "_load_keychain", return_value={}), \
202 mock.patch.object(env, "_load_pass", return_value={}):
203 assert cli.main() == 0
204
205 preflight = json.loads(capsys.readouterr().out)
206 assert preflight["network"]["endpoint_overrides"] == [
207 "OPENROUTER_BASE_URL", "XAI_BASE_URL",
208 ]
209 assert providers.resolve_endpoint("XAI_BASE_URL", providers.XAI_RESPONSES_URL) == (
210 "https://x-gateway.test/v1/responses"
211 )
212 assert providers.resolve_endpoint("OPENROUTER_BASE_URL", providers.OPENROUTER_URL) == (
213 "https://router-gateway.test/v1/chat/completions"
214 )
215
216
217 def test_cli_preflight_rejects_file_override_without_leaking_it(tmp_path, monkeypatch, capsys):
218 secret = "dummy-secret-do-not-report"
219 config_file = tmp_path / ".env"
220 config_file.write_text(
221 f"OPENROUTER_BASE_URL=http://{secret}@gateway.example/v1?token={secret}\n",
222 encoding="utf-8",
223 )
224 monkeypatch.chdir(tmp_path)
225 monkeypatch.setattr(env, "CONFIG_FILE", config_file)
226 for key in ("OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL"):
227 monkeypatch.setenv(key, "")
228 monkeypatch.setattr(sys, "argv", ["last30days.py", "--preflight", "--emit=json"])
229
230 with mock.patch.object(env, "_load_keychain", return_value={}), \
231 mock.patch.object(env, "_load_pass", return_value={}):
232 assert cli.main() == 0
233
234 captured = capsys.readouterr()
235 preflight = json.loads(captured.out)
236 assert preflight["status"] == "action_needed"
237 assert preflight["network"]["endpoint_overrides"] == []
238 assert preflight["network"]["ignored_endpoint_overrides"] == ["OPENROUTER_BASE_URL"]
239 assert secret not in captured.out + captured.err
240 assert providers.resolve_endpoint("OPENROUTER_BASE_URL", providers.OPENROUTER_URL) == (
241 providers.OPENROUTER_URL
242 )
243 assert secret not in capsys.readouterr().err
244
245
246 def test_diagnose_uses_preflight_endpoint_override_key_set():
247 ignored_keys = sorted(permission_preflight.ENDPOINT_OVERRIDE_KEYS) + ["UNRELATED_KEY"]
248 diag = pipeline.diagnose(
249 {
250 "_IGNORED_PROJECT_CONFIG_KEYS": ignored_keys,
251 "_BROWSER_COOKIE_MODE": "off",
252 "_BROWSER_COOKIE_BROWSERS": [],
253 },
254 safe=True,
255 )
256
257 assert sorted(diag["ignored_endpoint_overrides"]) == sorted(
258 permission_preflight.ENDPOINT_OVERRIDE_KEYS
259 )
260
261
262 def test_cli_preflight_uses_plan_only_policy_and_does_not_run_research(monkeypatch):
263 seen: dict[str, object] = {}
264
265 def fake_get_config(*, policy):
266 seen["policy"] = policy
267 return {"_BROWSER_COOKIE_MODE": policy.browser_cookies, "_BROWSER_COOKIE_BROWSERS": []}
268
269 with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \
270 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag_with_preflight()) as diagnose, \
271 mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("research should not run")), \
272 mock.patch.object(sys, "argv", ["last30days.py", "--preflight"]):
273 stdout = io.StringIO()
274 stderr = io.StringIO()
275 with redirect_stdout(stdout), redirect_stderr(stderr):
276 assert cli.main() == 0
277
278 assert seen["policy"].browser_cookies == "plan_only"
279 assert seen["policy"].inspect_ignored_project_config is True
280 diagnose.assert_called_once()
281 assert "last30days preflight" in stdout.getvalue()
282 assert "Local writes:" in stdout.getvalue()
283
284
285 def test_cli_preflight_keeps_diagnosed_sources_with_research_write_plan(monkeypatch):
286 embedded = permission_preflight.build({}, _diag())
287 diag = _diag(permission_preflight=embedded)
288 with mock.patch.object(cli.env, "get_config", return_value={}), \
289 mock.patch.object(cli.pipeline, "diagnose", return_value=diag), \
290 mock.patch.object(sys, "argv", ["last30days.py", "--preflight", "--emit=json"]):
291 stdout = io.StringIO()
292 stderr = io.StringIO()
293 with redirect_stdout(stdout), redirect_stderr(stderr):
294 assert cli.main() == 0
295
296 payload = json.loads(stdout.getvalue())
297 assert payload["network"] == embedded["network"]
298 assert payload["local_writes"] == [
299 {"kind": "research_cache", "path": str(env.CONFIG_DIR / name)}
300 for name in ("last-run.json", "last-report.json")
301 ]
302
303
304 def test_cli_preflight_reports_explicit_save_dir(monkeypatch, tmp_path):
305 save_dir = tmp_path / "reports"
306 with mock.patch.object(cli.env, "get_config", return_value={}), \
307 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag_with_preflight()), \
308 mock.patch.object(sys, "argv", ["last30days.py", "--preflight", "--save-dir", str(save_dir)]):
309 stdout = io.StringIO()
310 stderr = io.StringIO()
311 with redirect_stdout(stdout), redirect_stderr(stderr):
312 assert cli.main() == 0
313
314 assert str(save_dir) in stdout.getvalue()
315 assert "report" in stdout.getvalue()
316
317
318 def test_cli_preflight_reports_conditional_save_dir(monkeypatch):
319 with mock.patch.object(cli.env, "get_config", return_value={}), \
320 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag_with_preflight()), \
321 mock.patch.object(
322 sys,
323 "argv",
324 [
325 "last30days.py",
326 "--preflight",
327 "--preflight-report-on-save-dir",
328 DEFAULT_SAVE_DIR,
329 ],
330 ):
331 stdout = io.StringIO()
332 stderr = io.StringIO()
333 with redirect_stdout(stdout), redirect_stderr(stderr):
334 assert cli.main() == 0
335
336 assert f"Report (if saved): {DEFAULT_SAVE_DIR}" in stdout.getvalue()
337
338
339 @pytest.mark.parametrize(
340 ("browser_guard", "x_browser", "reddit_consent", "expected"),
341 [
342 ([], "firefox", "false", ["firefox"]),
343 ([], "", "true", ["firefox"]),
344 ([], "off", "true", []),
345 (["--no-browser-cookies"], "firefox", "true", []),
346 ],
347 )
348 def test_cli_preflight_forecasts_browser_policy_without_reading_cookies(
349 monkeypatch, capsys, browser_guard, x_browser, reddit_consent, expected,
350 ):
351 monkeypatch.setenv("FROM_BROWSER", x_browser)
352 monkeypatch.setenv("BROWSER_CONSENT", "true" if x_browser else "false")
353 monkeypatch.setenv("REDDIT_BROWSER_CONSENT", reddit_consent)
354 monkeypatch.setenv("REDDIT_FROM_BROWSER", "firefox")
355 monkeypatch.setenv("BROWSER_CDP_URL", "https://localhost:9222")
356 monkeypatch.setattr(
357 sys, "argv", ["last30days.py", "--preflight", "--emit=json", *browser_guard]
358 )
359
360 with mock.patch.object(cookie_extract, "extract_cookies", side_effect=AssertionError("cookie read")):
361 assert cli.main() == 0
362
363 browser = json.loads(capsys.readouterr().out)["local_reads"]["browser_cookies"]
364 assert browser["browsers"] == expected
365 assert browser["status"] == ("enabled_by_config" if expected else "off")
366 assert browser["reads_values"] is False
367
368
369 @pytest.mark.parametrize("scope", ["excluded", "search_without_reddit", "scrapecreators_primary"])
370 def test_cli_preflight_omits_reddit_browser_when_research_will_not_use_it(monkeypatch, capsys, scope):
371 monkeypatch.setenv("BROWSER_CONSENT", "false")
372 monkeypatch.setenv("REDDIT_BROWSER_CONSENT", "true")
373 monkeypatch.setenv("REDDIT_FROM_BROWSER", "firefox")
374 args = ["last30days.py", "--preflight", "--emit=json"]
375 if scope == "excluded":
376 monkeypatch.setenv("EXCLUDE_SOURCES", "reddit")
377 elif scope == "search_without_reddit":
378 args.append("--search=hackernews")
379 else:
380 monkeypatch.setenv(env.REDDIT_BACKEND_PIN_VAR, "scrapecreators")
381 monkeypatch.setenv("SCRAPECREATORS_API_KEY", "dummy-key")
382 monkeypatch.setattr(sys, "argv", args)
383 monkeypatch.setattr(env, "read_reddit_session_cookie", lambda *_args: pytest.fail("cookie read"))
384
385 assert cli.main() == 0
386
387 browser = json.loads(capsys.readouterr().out)["local_reads"]["browser_cookies"]
388 assert browser["status"] == "off"
389 assert browser["browsers"] == []
390
391
392 @pytest.mark.parametrize(
393 ("config", "denied", "expected"),
394 [
395 ({"AGENTCOOKIE": "on"}, False, ["agentcookie (if available)"]),
396 ({"BROWSER_CONSENT": "true", "AGENTCOOKIE": "off"}, False, ["Chrome CDP (if available)"]),
397 ({"BROWSER_CONSENT": "true", "AGENTCOOKIE": "off", "BROWSER_CDP_URL": "https://localhost:9222"}, False, []),
398 ({"BROWSER_CONSENT": "true"}, False, ["agentcookie (if available)", "Chrome CDP (if available)"]),
399 ({"BROWSER_CONSENT": "true"}, True, []),
400 ({"AGENTCOOKIE": "on", "BROWSER_CONSENT": "false"}, False, []),
401 ({"AGENTCOOKIE": "on", "FROM_BROWSER": "off"}, False, []),
402 ],
403 )
404 def test_cli_preflight_forecasts_conditional_x_cookie_routes_without_contact(
405 monkeypatch, capsys, config, denied, expected,
406 ):
407 for key, value in config.items():
408 monkeypatch.setenv(key, value)
409 reachables = agentcookie.shutil.which
410 monkeypatch.setattr(agentcookie.shutil, "which", lambda name: "/agentcookie" if name == "agentcookie" else reachables(name))
411 monkeypatch.setattr(env, "x_extras_enabled", lambda _config: True)
412 monkeypatch.setattr(agentcookie, "read_x_cookies", lambda *_args: pytest.fail("sidecar contact"))
413 monkeypatch.setattr(chrome_cdp, "read_x_cookies", lambda *_args: pytest.fail("CDP contact"))
414 args = ["last30days.py", "--preflight", "--emit=json"]
415 if denied:
416 args.append("--no-browser-cookies")
417 monkeypatch.setattr(sys, "argv", args)
418
419 assert cli.main() == 0
420
421 browser = json.loads(capsys.readouterr().out)["local_reads"]["browser_cookies"]
422 assert browser["browsers"] == expected
423 assert browser["reads_values"] is False
424
425
426 def test_cli_preflight_forecasts_disabled_export_and_local_persistence(monkeypatch, capsys, tmp_path):
427 report_dir = tmp_path / "configured reports"
428 config_dir = tmp_path / "app config"
429 monkeypatch.setattr(env, "CONFIG_DIR", config_dir)
430 monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", str(report_dir))
431 monkeypatch.setenv("LAST30DAYS_STORE", "1")
432 monkeypatch.setattr(
433 sys, "argv",
434 ["last30days.py", "--preflight", "--emit=json", "--save-dir", ""],
435 )
436
437 assert cli.main() == 0
438
439 payload = json.loads(capsys.readouterr().out)
440 planned_paths = {Path(write["path"]) for write in payload["local_writes"]}
441 assert config_dir / "last-run.json" in planned_paths
442 assert config_dir / "last-report.json" in planned_paths
443 assert any(path.name == "research.db" for path in planned_paths)
444 assert report_dir not in planned_paths
445 assert not config_dir.exists()
446 assert not report_dir.exists()
447
448
449 @pytest.mark.parametrize("export_enabled", [True, False])
450 def test_cli_preflight_requires_mcp_save_for_research_persistence(
451 monkeypatch, capsys, tmp_path, export_enabled,
452 ):
453 import store
454
455 config_dir = tmp_path / "app config"
456 engine_dir = tmp_path / "installed engine"
457 report_dir = tmp_path / "configured reports"
458 default_db = tmp_path / "default store" / "research.db"
459 corpus_dir = tmp_path / "notes"
460 corpus_dir.mkdir()
461 saved_reports = str(report_dir) if export_enabled else ""
462 monkeypatch.setattr(env, "CONFIG_DIR", config_dir)
463 monkeypatch.setattr(store, "DB_PATH", default_db)
464 monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", str(report_dir))
465 monkeypatch.setenv("LAST30DAYS_CORPUS_DIRS", str(corpus_dir))
466 monkeypatch.setenv("LAST30DAYS_STORE", "yes")
467 monkeypatch.setattr(
468 sys, "argv",
469 [
470 "last30days.py", "--preflight", "--emit=json", "--save-dir", "",
471 "--no-browser-cookies", "--preflight-report-on-save-dir", saved_reports,
472 "--preflight-engine-cache-dir", str(engine_dir),
473 ],
474 )
475
476 assert cli.main() == 0
477
478 payload = json.loads(capsys.readouterr().out)
479 assert payload["local_writes"] == []
480 expected = {
481 ("engine_cache_on_first_use", str(engine_dir)),
482 ("research_cache_on_save", str(config_dir / "last-run.json")),
483 ("research_cache_on_save", str(config_dir / "last-report.json")),
484 ("corpus_cache_on_save", str(config_dir / corpus.CACHE_FILENAME)),
485 }
486 if export_enabled:
487 expected.update({
488 ("report_on_save", str(report_dir)),
489 ("library_index_on_save", str(report_dir / ".last30days-library.db")),
490 ("research_store_on_save", str(report_dir / "research.db")),
491 })
492 else:
493 expected.add(("research_store_on_save", str(default_db)))
494 from lib import rust_accel
495 if rust_accel.would_auto_install_on_run():
496 expected.add(("native_core_on_first_run", str(rust_accel.install_bin_path())))
497 assert {(row["kind"], row["path"]) for row in payload["conditional_writes"]} == expected
498 assert list(tmp_path.iterdir()) == [corpus_dir]
499
500
501 @pytest.mark.parametrize("no_persistence", [False, True], ids=["normal", "no-persistence"])
502 def test_cli_preflight_matches_actual_corpus_and_library_writes(
503 monkeypatch, capsys, tmp_path, no_persistence,
504 ):
505 import store
506 from lib import library_index
507
508 notes = tmp_path / "notes"
509 notes.mkdir()
510 (notes / "MCP servers.txt").write_text("MCP servers use a local transport.", encoding="utf-8")
511 config_dir = tmp_path / "app config"
512 reports = tmp_path / "reports"
513 monkeypatch.setattr(env, "CONFIG_DIR", config_dir)
514 monkeypatch.setattr(store, "DB_PATH", tmp_path / "state" / "research.db")
515 monkeypatch.setattr(library_index, "DEFAULT_LIBRARY_DB", tmp_path / "state" / "library.db")
516 monkeypatch.setenv("LAST30DAYS_STORE", "1")
517 monkeypatch.setenv("LAST30DAYS_LIBRARY_CONTEXT", "on")
518 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
519 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
520 monkeypatch.setenv("LAST30DAYS_NO_PATENT_DIGEST", "1")
521 monkeypatch.setenv("EXCLUDE_SOURCES", "jobs,yahoo_finance")
522 flags = [
523 "--search=corpus", "--quick", "--web-backend=none", "--no-browser-cookies",
524 "--corpus", str(notes), "--save-dir", str(reports),
525 ]
526 topic = "MCP servers"
527 preflight_topic = []
528 if no_persistence:
529 flags.extend(["--research-only", "--no-research-persistence", "--store"])
530 preflight_topic.append(topic)
531 monkeypatch.setattr(
532 sys, "argv", ["last30days.py", "--preflight", "--emit=json", *flags, *preflight_topic],
533 )
534
535 assert cli.main() == 0
536 plan = json.loads(capsys.readouterr().out)
537 assert not config_dir.exists()
538 assert not reports.exists()
539
540 monkeypatch.setattr(sys, "argv", ["last30days.py", topic, *flags])
541 assert cli.main() == 0
542
543 if no_persistence:
544 assert "MCP servers" in capsys.readouterr().out
545 assert list(tmp_path.iterdir()) == [notes]
546 assert plan["local_writes"] == []
547 assert plan["conditional_writes"] == []
548 return
549
550 expected = {
551 config_dir / "last-run.json", config_dir / "last-report.json",
552 config_dir / corpus.CACHE_FILENAME, reports / "research.db",
553 reports / ".last30days-library.db", reports,
554 }
555 assert all(path.exists() for path in expected)
556 assert expected <= {Path(write["path"]) for write in plan["local_writes"] + plan["conditional_writes"]}
557 [report] = reports.glob("*-raw.md")
558 assert "MCP servers" in report.read_text(encoding="utf-8")
559
560
561 def test_cli_preflight_omits_disabled_corpus_and_library_writes(monkeypatch, capsys, tmp_path):
562 monkeypatch.setenv("LAST30DAYS_CORPUS_DIRS", str(tmp_path))
563 monkeypatch.setenv("EXCLUDE_SOURCES", "corpus")
564 monkeypatch.setenv("LAST30DAYS_LIBRARY_CONTEXT", "off")
565 monkeypatch.setattr(
566 sys, "argv", ["last30days.py", "--preflight", "--emit=json", "--save-dir", ""],
567 )
568
569 assert cli.main() == 0
570 plan = json.loads(capsys.readouterr().out)
571 from lib import rust_accel
572 expected_kinds = {"research_cache"}
573 if rust_accel.would_auto_install_on_run():
574 expected_kinds.add("native_core_on_first_run")
575 assert {write["kind"] for write in plan["local_writes"] + plan["conditional_writes"]} == expected_kinds
576
577
578 def test_cli_preflight_json_returns_structured_contract(monkeypatch):
579 with mock.patch.object(cli.env, "get_config", return_value={}), \
580 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag_with_preflight()), \
581 mock.patch.object(sys, "argv", ["last30days.py", "--preflight", "--emit=json"]):
582 stdout = io.StringIO()
583 stderr = io.StringIO()
584 with redirect_stdout(stdout), redirect_stderr(stderr):
585 assert cli.main() == 0
586
587 payload = json.loads(stdout.getvalue())
588 from lib import rust_accel
589 expected_conditional = (
590 [{"kind": "native_core_on_first_run", "path": str(rust_accel.install_bin_path())}]
591 if rust_accel.would_auto_install_on_run()
592 else []
593 )
594 assert payload["local_reads"]["browser_cookies"]["status"] == "off"
595 assert payload["conditional_writes"] == expected_conditional
596 assert payload["safe"] is True
597
598
599 DUMMY_X_BEARER = "dummy-x-bearer-token-not-real-000"
600
601
602 def test_preflight_reports_x_bearer_presence_as_boolean_without_value():
603 """U6: the X API bearer row is computed from config inside preflight (not
604 through diagnose.providers) and never carries the value."""
605 diag = _diag() # providers dict has no x_bearer entry on purpose
606 present = permission_preflight.build({"X_BEARER_TOKEN": DUMMY_X_BEARER}, diag)
607 absent = permission_preflight.build({}, diag)
608
609 assert present["credentials"]["x_bearer"] == {
610 "present": True,
611 "label": permission_preflight.PROVIDER_CREDENTIALS["x_bearer"],
612 }
613 assert absent["credentials"]["x_bearer"]["present"] is False
614 assert DUMMY_X_BEARER not in json.dumps(present)
615
616 text = permission_preflight.render_text(present)
617 assert permission_preflight.PROVIDER_CREDENTIALS["x_bearer"] in text
618 assert DUMMY_X_BEARER not in text
619 assert "Values are not printed or written by preflight" in text
620
621
622 def test_preflight_x_bearer_ignores_whitespace_only_value():
623 diag = _diag()
624 assert permission_preflight.build({"X_BEARER_TOKEN": " "}, diag)["credentials"]["x_bearer"]["present"] is False
625
626
627 def test_preflight_names_unsubstituted_templates_and_reports_action_needed():
628 # get_config() already emptied these values, so the provider flags read as
629 # absent; the record is what turns "nothing is configured" into an
630 # explanation the user can act on.
631 config = {env.TEMPLATE_CONFIG_KEYS: ["GEMINI_API_KEY", "SCRAPECREATORS_API_KEY"]}
632 preflight = permission_preflight.build(config, _diag())
633
634 assert preflight["status"] == "action_needed"
635 item = next(
636 i for i in preflight["action_items"] if "Unsubstituted config template" in i
637 )
638 assert "GEMINI_API_KEY" in item
639 assert "SCRAPECREATORS_API_KEY" in item
640 assert [n for n, info in preflight["credentials"].items() if info["present"]] == []
641 assert "Unsubstituted config template" in permission_preflight.render_text(preflight)
642
643
644 def test_preflight_without_templates_keeps_the_ready_shape():
645 preflight = permission_preflight.build({}, _diag())
646
647 assert preflight["status"] == "ready"
648 assert preflight["action_items"] == []
649 assert "Unsubstituted config template" not in permission_preflight.render_text(preflight)
650
650 lines PYTHON