返回 last30days-skill
test_pr05_cli_privacy_readonly_fanout_security.py
根目录 / tests / test_pr05_cli_privacy_readonly_fanout_security.py
1 """Security and concurrency regression tests for PR05 (HIGH-001, 003, 004, 006, 007)."""
2
3 from __future__ import annotations
4
5 import io
6 import json
7 import os
8 import sys
9 import threading
10 from contextlib import redirect_stderr, redirect_stdout
11 from pathlib import Path
12 from unittest import mock
13
14 import pytest
15
16 import last30days as cli
17 from lib import cookie_extract, env, html_publish, pipeline, schema
18
19
20 def _sample_report(topic: str = "OpenClaw") -> schema.Report:
21 item = schema.SourceItem(
22 item_id="reddit-1",
23 source="reddit",
24 title="Widget API is open",
25 body="Community thread discussing Widget API status.",
26 url="https://reddit.com/r/example/comments/abc/widget",
27 published_at="2026-07-09T12:00:00Z",
28 snippet="Widget API is open",
29 )
30 candidate = schema.Candidate(
31 candidate_id="candidate-1",
32 item_id=item.item_id,
33 source=item.source,
34 title=item.title,
35 url=item.url,
36 snippet=item.snippet,
37 subquery_labels=["primary"],
38 native_ranks={"primary:reddit": 1},
39 local_relevance=0.9,
40 freshness=90,
41 engagement=25,
42 source_quality=0.8,
43 rrf_score=0.02,
44 final_score=90,
45 source_items=[item],
46 )
47 return schema.Report(
48 topic=topic,
49 range_from="2026-06-10",
50 range_to="2026-07-10",
51 generated_at="2026-07-10T12:00:00Z",
52 provider_runtime=schema.ProviderRuntime(
53 reasoning_provider="local",
54 planner_model="fixture",
55 rerank_model="fixture",
56 ),
57 query_plan=schema.QueryPlan(
58 intent="research",
59 freshness_mode="balanced_recent",
60 cluster_mode="story",
61 raw_topic=topic,
62 subqueries=[
63 schema.SubQuery(
64 label="primary",
65 search_query=topic,
66 ranking_query=topic,
67 sources=["reddit"],
68 )
69 ],
70 source_weights={"reddit": 1.0},
71 ),
72 clusters=[
73 schema.Cluster(
74 cluster_id="cluster-1",
75 title="Widget API status",
76 candidate_ids=[candidate.candidate_id],
77 representative_ids=[candidate.candidate_id],
78 sources=["reddit"],
79 score=90,
80 )
81 ],
82 ranked_candidates=[candidate],
83 items_by_source={"reddit": [item]},
84 errors_by_source={},
85 source_status={"reddit": schema.SourceOutcome(source="reddit", state="ok", items_returned=1)},
86 )
87
88
89 def _run_cli(argv: list[str], *, environ: dict[str, str] | None = None) -> tuple[int, str, str]:
90 stdout, stderr = io.StringIO(), io.StringIO()
91 env_patch = {"LAST30DAYS_SKIP_PREFLIGHT": "1", **(environ or {})}
92 with mock.patch.dict(os.environ, env_patch, clear=False), \
93 mock.patch.object(sys, "argv", ["last30days.py", *argv]), \
94 redirect_stdout(stdout), redirect_stderr(stderr):
95 try:
96 rc = cli.main()
97 except SystemExit as exc:
98 rc = int(exc.code) if isinstance(exc.code, int) else 1
99 return rc, stdout.getvalue(), stderr.getvalue()
100
101
102 # ---------------------------------------------------------------------------
103 # HIGH-001: --record-fixtures logged-in Reddit session guard for --drill / --discover
104 # ---------------------------------------------------------------------------
105
106
107 SESSION_ON_CONFIG = {
108 "_BROWSER_COOKIE_MODE": "read",
109 env.REDDIT_CONSENT_VAR: "true",
110 env.REDDIT_FROM_BROWSER_VAR: "chrome",
111 }
112
113
114 class TestRecordFixturesRedditSessionGuard:
115 @pytest.mark.parametrize(
116 "argv",
117 [
118 ["--drill", "cluster 1"],
119 ["--discover"],
120 ["--discover", "AI agents"],
121 ["--discover", "--nominate-only"],
122 ["--discover", "--judgments", "judgments.json"],
123 ["--research-only", "setup"],
124 ],
125 ids=[
126 "drill",
127 "discover-global",
128 "discover-domain",
129 "discover-nominate-only",
130 "discover-judgments",
131 "research-only-setup",
132 ],
133 )
134 def test_refuses_logged_in_reddit_session_on_drill_discover_and_research_only(
135 self, tmp_path: Path, argv: list[str],
136 ):
137 rec_dir = tmp_path / "rec"
138 with mock.patch.object(cli.env, "get_config", return_value=dict(SESSION_ON_CONFIG)), \
139 mock.patch.object(cli, "_run_drill", side_effect=AssertionError("drill must not run")), \
140 mock.patch.object(cli, "_run_discover", side_effect=AssertionError("discover must not run")), \
141 mock.patch.object(cli, "_run_discover_protocol_leg", side_effect=AssertionError("protocol leg must not run")), \
142 mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline must not run")):
143 rc, _out, err = _run_cli([*argv, "--record-fixtures", str(rec_dir)])
144
145 assert rc == 2
146 assert "--record-fixtures refuses" in err
147 assert "--no-browser-cookies" in err
148
149 @pytest.mark.parametrize(
150 ("argv", "target"),
151 [
152 (["--drill", "cluster 1", "--no-browser-cookies"], "_run_drill"),
153 (["--discover", "AI agents", "--no-browser-cookies"], "_run_discover"),
154 ],
155 )
156 def test_allows_drill_and_discover_when_browser_cookies_disabled(
157 self, tmp_path: Path, argv: list[str], target: str,
158 ):
159 def fake_get_config(*, policy):
160 return {
161 "_BROWSER_COOKIE_MODE": policy.browser_cookies,
162 env.REDDIT_CONSENT_VAR: "true",
163 env.REDDIT_FROM_BROWSER_VAR: "chrome",
164 }
165
166 with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \
167 mock.patch.object(cli, target, return_value=0) as handler:
168 rc, _out, err = _run_cli([*argv, "--record-fixtures", str(tmp_path / "rec")])
169
170 assert rc == 0, err
171 handler.assert_called_once()
172
173 def test_discover_finalize_is_offline_and_not_blocked_by_session_guard(self, tmp_path: Path):
174 def fake_get_config(*, policy):
175 return {
176 "_BROWSER_COOKIE_MODE": policy.browser_cookies,
177 env.REDDIT_CONSENT_VAR: "true",
178 env.REDDIT_FROM_BROWSER_VAR: "chrome",
179 }
180
181 with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \
182 mock.patch.object(cli, "_run_discover_protocol_leg", return_value=0) as handler:
183 rc, _out, err = _run_cli(
184 ["--discover", "--finalize", "--record-fixtures", str(tmp_path / "rec")]
185 )
186
187 assert rc == 0, err
188 handler.assert_called_once()
189
190 @pytest.mark.parametrize("flag", ["--diagnose", "--preflight"])
191 @pytest.mark.parametrize("target_kind", ["existing_file", "existing_dir", "missing_file"])
192 def test_diagnose_and_preflight_reject_record_fixtures_without_touching_files(
193 self, tmp_path: Path, flag: str, target_kind: str,
194 ):
195 sentinel = '{"format": "sentinel", "exchanges": [{"id": 1}]}\n'
196 if target_kind == "existing_file":
197 fixture_arg = tmp_path / "existing.json"
198 fixture_arg.write_text(sentinel, encoding="utf-8")
199 check_path = fixture_arg
200 elif target_kind == "existing_dir":
201 fixture_arg = tmp_path / "existing_dir"
202 fixture_arg.mkdir()
203 check_path = fixture_arg / "http.json"
204 check_path.write_text(sentinel, encoding="utf-8")
205 else:
206 fixture_arg = tmp_path / "never-created.json"
207 check_path = fixture_arg
208
209 with mock.patch.object(
210 cli.http, "recording_requests",
211 side_effect=AssertionError("recording_requests must not start"),
212 ), mock.patch.object(
213 cli.env, "get_config",
214 side_effect=AssertionError("must reject before loading config"),
215 ):
216 rc, out, err = _run_cli([flag, "--record-fixtures", str(fixture_arg)])
217
218 assert rc == 2
219 assert out == ""
220 assert f"--record-fixtures cannot be combined with {flag}" in err
221 if target_kind == "missing_file":
222 assert not check_path.exists()
223 else:
224 assert check_path.read_text(encoding="utf-8") == sentinel
225
226
227 # ---------------------------------------------------------------------------
228 # HIGH-003: Offline, --mock, hosted-API, empty/invalid, non-auto setup cookie guard
229 # ---------------------------------------------------------------------------
230
231
232 class TestConfigPolicyNoUnexpectedCookieReads:
233 @pytest.mark.parametrize(
234 ("argv", "expected"),
235 [
236 (["some topic", "--mock"], "off"),
237 (["--drill", "cluster 1", "--mock"], "off"),
238 (["--discover", "AI agents", "--mock"], "off"),
239 (["--discover", "--mock"], "off"),
240 (["--discover", "--finalize"], "off"),
241 (["--discover", "--finalize", "--angles", "angles.json"], "off"),
242 ([], "off"),
243 (["--discover-shallow"], "off"),
244 (["--deep-research"], "off"),
245 (["--nominate-only"], "off"),
246 (["--finalize"], "off"),
247 (["--angles", "angles.json"], "off"),
248 (["--discover", "AI agents", "--emit=html"], "off"),
249 (["--drill", "cluster 1", "--publish-html"], "off"),
250 (["some topic", "--publish-html"], "off"),
251 (["setup", "--openclaw", "--allow-browser-cookies"], "off"),
252 (["setup", "--github-start", "--allow-browser-cookies"], "off"),
253 (["setup", "--github-poll", "--allow-browser-cookies"], "off"),
254 (["setup", "--github", "--allow-browser-cookies"], "off"),
255 (["setup", "--device-auth", "--allow-browser-cookies"], "off"),
256 (["setup", "--reddit-session", "--allow-browser-cookies"], "off"),
257 (["setup", "--no-reddit-session", "--allow-browser-cookies"], "off"),
258 (["setup", "--store-key", "XAI_API_KEY", "--allow-browser-cookies"], "off"),
259 (["setup", "--install-hooks", "--allow-browser-cookies"], "off"),
260 # Positive controls: legitimate live flows still allow reads.
261 (["some topic"], "read"),
262 (["--discover", "AI agents"], "read"),
263 (["--discover", "--verify-freshness"], "read"),
264 (["--discover", "AI agents", "--verify-freshness"], "read"),
265 (["--drill", "cluster 1"], "read"),
266 (["--drill", "cluster 1", "--verify-freshness"], "read"),
267 (["setup", "--allow-browser-cookies"], "read"),
268 (["setup", "--use-recorded-browser-consent"], "read"),
269 # Cache-only freshness verification and --diagnose/--preflight stay plan_only.
270 (["--verify-freshness"], "plan_only"),
271 (["--diagnose", "--mock"], "plan_only"),
272 (["--preflight", "--mock"], "plan_only"),
273 ],
274 )
275 def test_config_policy_matrix(self, monkeypatch, argv: list[str], expected: str):
276 for var in (
277 *env.AGENT_HOST_ENV_VARS,
278 env.HOST_AGENT_VAR,
279 env.X_HOST_VAR,
280 "LAST30DAYS_API_KEY",
281 "LAST30DAYS_API_BASE",
282 "LAST30DAYS_API_MODE",
283 "LAST30DAYS_CORPUS_DIRS",
284 "PERPLEXITY_API_KEY",
285 ):
286 monkeypatch.delenv(var, raising=False)
287 parser = cli.build_parser()
288 args, extra = parser.parse_known_args(argv)
289 topic = " ".join(args.topic).strip()
290 assert cli._config_policy_for_args(args, topic, extra).browser_cookies == expected
291
292 def test_hosted_api_run_sets_browser_cookies_off_and_skips_cookie_extraction(
293 self, tmp_path: Path, monkeypatch,
294 ):
295 env_file = tmp_path / ".env"
296 env_file.write_text("FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n", encoding="utf-8")
297 env_file.chmod(0o600)
298 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
299 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
300 monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_DUMMY_TEST_KEY_00000")
301 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1")
302 monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False)
303 monkeypatch.setenv("LAST30DAYS_SKIP_KEYCHAIN", "1")
304
305 parser = cli.build_parser()
306 args, extra = parser.parse_known_args(["Ghostty terminal"])
307 hosted_policy = cli._config_policy_for_args(args, "Ghostty terminal", extra)
308 assert hosted_policy.browser_cookies == "off"
309 assert hosted_policy.load_secret_stores is False
310
311 # --corpus under hosted env stays deferred ("off", no secret stores)
312 # until .env EXCLUDE_SOURCES is checked; unconditional local modes keep "read".
313 corpus_args, corpus_extra = parser.parse_known_args(
314 ["Ghostty terminal", "--corpus", str(tmp_path)]
315 )
316 corpus_policy = cli._config_policy_for_args(corpus_args, "Ghostty terminal", corpus_extra)
317 assert corpus_policy.browser_cookies == "off"
318 assert corpus_policy.load_secret_stores is False
319
320 for bypass_argv in (
321 ["Ghostty terminal", "--deep-research"],
322 ["Ghostty terminal", "--record-fixtures", str(tmp_path / "rec")],
323 ):
324 b_args, b_extra = parser.parse_known_args(bypass_argv)
325 b_policy = cli._config_policy_for_args(b_args, "Ghostty terminal", b_extra)
326 assert b_policy.browser_cookies == "read"
327 assert b_policy.load_secret_stores is True
328
329 with mock.patch.object(
330 env, "_load_keychain",
331 side_effect=AssertionError("hosted run must not query Keychain"),
332 ), mock.patch.object(
333 env, "_load_pass",
334 side_effect=AssertionError("hosted run must not query pass"),
335 ), mock.patch.object(
336 env, "_discover_and_apply_x_credentials",
337 side_effect=AssertionError("hosted run must not extract browser cookies"),
338 ), mock.patch.object(
339 cookie_extract, "extract_cookies",
340 side_effect=AssertionError("hosted run must not extract browser cookies"),
341 ), mock.patch("lib.hosted.run_hosted", return_value=0) as run_hosted:
342 rc, _out, err = _run_cli(["Ghostty terminal"])
343
344 assert rc == 0, err
345 run_hosted.assert_called_once()
346
347 def test_hosted_excluded_corpus_stays_hosted_without_cookie_or_secret_store_reads(
348 self, tmp_path: Path, monkeypatch,
349 ):
350 notes = tmp_path / "notes"
351 notes.mkdir()
352 env_file = tmp_path / ".env"
353 env_file.write_text(
354 f"FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n"
355 f"LAST30DAYS_CORPUS_DIRS={notes}\nEXCLUDE_SOURCES=corpus\n",
356 encoding="utf-8",
357 )
358 env_file.chmod(0o600)
359 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
360 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
361 monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_DUMMY_TEST_KEY_00000")
362 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1")
363 monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False)
364 monkeypatch.setenv("LAST30DAYS_CORPUS_DIRS", str(notes))
365 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
366
367 with mock.patch.object(
368 env, "_load_keychain",
369 side_effect=AssertionError("hosted excluded-corpus run must not query Keychain"),
370 ), mock.patch.object(
371 env, "_load_pass",
372 side_effect=AssertionError("hosted excluded-corpus run must not query pass"),
373 ), mock.patch.object(
374 env, "_discover_and_apply_x_credentials",
375 side_effect=AssertionError("hosted excluded-corpus run must not read browser cookies"),
376 ), mock.patch.object(
377 cookie_extract, "extract_cookies",
378 side_effect=AssertionError("hosted excluded-corpus run must not read browser cookies"),
379 ), mock.patch("lib.hosted.run_hosted", return_value=0) as run_hosted:
380 rc, _out, err = _run_cli(["Ghostty terminal", "--corpus", str(notes)])
381
382 assert rc == 0, err
383 run_hosted.assert_called_once()
384
385 @pytest.mark.parametrize("no_cookies", [False, True])
386 def test_hosted_dotenv_corpus_bypass_reloads_browser_cookies_for_local_run(
387 self, tmp_path: Path, monkeypatch, no_cookies: bool,
388 ):
389 notes = tmp_path / "notes"
390 notes.mkdir()
391 env_file = tmp_path / ".env"
392 env_file.write_text(
393 f"FROM_BROWSER=chrome\nBROWSER_CONSENT=true\nLAST30DAYS_CORPUS_DIRS={notes}\n",
394 encoding="utf-8",
395 )
396 env_file.chmod(0o600)
397 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
398 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
399 monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_DUMMY_TEST_KEY_00000")
400 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1")
401 monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False)
402 monkeypatch.delenv("LAST30DAYS_CORPUS_DIRS", raising=False)
403 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
404 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
405 monkeypatch.setenv("LAST30DAYS_NO_PATENT_DIGEST", "1")
406
407 discovered: list[str] = []
408 keychain_calls = 0
409
410 def fake_discover(cfg):
411 discovered.append(str(cfg.get("_BROWSER_COOKIE_MODE")))
412 cfg["AUTH_TOKEN"] = "dummy-reloaded-auth-token"
413 cfg["CT0"] = "dummy-reloaded-ct0"
414
415 def fake_keychain(keys, aliases=None):
416 nonlocal keychain_calls
417 keychain_calls += 1
418 return {"XQUIK_API_KEY": "dummy-keychain-xquik"}
419
420 argv = [
421 "Ghostty",
422 "--search=corpus",
423 "--quick",
424 "--web-backend=none",
425 "--x-handle=ghostty",
426 ]
427 if no_cookies:
428 argv.append("--no-browser-cookies")
429
430 with mock.patch.object(env, "_load_keychain", side_effect=fake_keychain), \
431 mock.patch.object(env, "_load_pass", return_value={}), \
432 mock.patch.object(env, "_discover_and_apply_x_credentials", side_effect=fake_discover), \
433 mock.patch.object(cli, "_resolved_company", return_value={}), \
434 mock.patch.object(cli.pipeline, "diagnose", return_value={"available_sources": ["corpus"]}), \
435 mock.patch.object(cli.pipeline, "run", return_value=_sample_report("Ghostty")) as run_mock, \
436 mock.patch.object(cli, "_render_save_and_print", return_value=0):
437 rc, _out, err = _run_cli(argv)
438
439 assert rc == 0, err
440 # Keychain is skipped on the tentative hosted load and queried once on local reload.
441 assert keychain_calls == 1
442 reloaded_cfg = run_mock.call_args.kwargs["config"]
443 assert reloaded_cfg["XQUIK_API_KEY"] == "dummy-keychain-xquik"
444 if no_cookies:
445 assert discovered == []
446 assert reloaded_cfg["_BROWSER_COOKIE_MODE"] == "off"
447 assert not reloaded_cfg.get("AUTH_TOKEN")
448 else:
449 assert discovered == ["read"]
450 assert reloaded_cfg["_BROWSER_COOKIE_MODE"] == "read"
451 assert reloaded_cfg["AUTH_TOKEN"] == "dummy-reloaded-auth-token"
452 # Verify cached research_options refreshed config_sha256 after local reload.
453 cached_payload = json.loads((tmp_path / "last-report.json").read_text(encoding="utf-8"))
454 cached_sha = cached_payload["research_options"]["config_sha256"]
455 parser = cli.build_parser()
456 check_args = parser.parse_args(argv)
457 without_reloaded = dict(reloaded_cfg)
458 without_reloaded.pop("AUTH_TOKEN", None)
459 without_reloaded.pop("CT0", None)
460 without_reloaded.pop("XQUIK_API_KEY", None)
461 expected_with = cli._cache_research_options(
462 check_args, reloaded_cfg, resolved_corpus_dirs=[notes],
463 )["config_sha256"]
464 expected_without = cli._cache_research_options(
465 check_args, without_reloaded, resolved_corpus_dirs=[notes],
466 )["config_sha256"]
467 assert expected_with != expected_without
468 assert cached_sha == expected_with
469
470 @pytest.mark.parametrize(
471 "clarify_args",
472 [["--clarify-angle", "pricing"], ["--clarify-broadly"]],
473 )
474 def test_clarify_flags_with_dotenv_corpus_reject_before_cookie_or_secret_store_reload(
475 self, tmp_path: Path, monkeypatch, clarify_args: list[str],
476 ):
477 notes = tmp_path / "notes"
478 notes.mkdir()
479 env_file = tmp_path / ".env"
480 env_file.write_text(
481 f"FROM_BROWSER=chrome\nBROWSER_CONSENT=true\nLAST30DAYS_CORPUS_DIRS={notes}\n",
482 encoding="utf-8",
483 )
484 env_file.chmod(0o600)
485 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
486 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
487 monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_DUMMY_TEST_KEY_00000")
488 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1")
489 monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False)
490 monkeypatch.delenv("LAST30DAYS_CORPUS_DIRS", raising=False)
491 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
492
493 with mock.patch.object(
494 env, "_load_keychain",
495 side_effect=AssertionError("invalid clarify run must not query Keychain"),
496 ), mock.patch.object(
497 env, "_load_pass",
498 side_effect=AssertionError("invalid clarify run must not query pass"),
499 ), mock.patch.object(
500 env, "_discover_and_apply_x_credentials",
501 side_effect=AssertionError("invalid clarify run must not extract browser cookies"),
502 ):
503 rc, out, err = _run_cli(["Ghostty", *clarify_args])
504
505 assert rc == 2
506 assert out == ""
507 assert "--clarify-angle and --clarify-broadly" in err
508
509 @pytest.mark.parametrize(
510 "clarify_args",
511 [["--clarify-angle", "pricing"], ["--clarify-broadly"]],
512 )
513 def test_clarify_flags_without_hosted_env_skip_cookies_and_secret_stores(
514 self, tmp_path: Path, monkeypatch, clarify_args: list[str],
515 ):
516 env_file = tmp_path / ".env"
517 env_file.write_text("FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n", encoding="utf-8")
518 env_file.chmod(0o600)
519 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
520 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
521 monkeypatch.delenv("LAST30DAYS_API_KEY", raising=False)
522 monkeypatch.delenv("LAST30DAYS_API_BASE", raising=False)
523 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
524
525 with mock.patch.object(
526 env, "_load_keychain",
527 side_effect=AssertionError("invalid clarify run must not query Keychain"),
528 ), mock.patch.object(
529 env, "_load_pass",
530 side_effect=AssertionError("invalid clarify run must not query pass"),
531 ), mock.patch.object(
532 env, "_discover_and_apply_x_credentials",
533 side_effect=AssertionError("invalid clarify run must not extract browser cookies"),
534 ):
535 rc, out, err = _run_cli(["Ghostty", *clarify_args])
536
537 assert rc == 2
538 assert out == ""
539 assert "--clarify-angle and --clarify-broadly" in err
540
541 @pytest.mark.parametrize(
542 "argv",
543 [
544 ["OpenAI vs Anthropic", "--deep-research"],
545 ["OpenAI", "--competitors", "--deep-research"],
546 ["OpenAI", "--competitors-list", "Anthropic", "--deep-research"],
547 ],
548 )
549 def test_deep_research_with_comparison_rejects_before_cookies_or_secret_stores(
550 self, tmp_path: Path, monkeypatch, argv: list[str],
551 ):
552 env_file = tmp_path / ".env"
553 env_file.write_text("FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n", encoding="utf-8")
554 env_file.chmod(0o600)
555 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
556 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
557 monkeypatch.delenv("PERPLEXITY_API_KEY", raising=False)
558 monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
559 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
560
561 with mock.patch.object(
562 env, "_load_keychain",
563 side_effect=AssertionError("invalid deep-research comparison must not query Keychain"),
564 ), mock.patch.object(
565 env, "_load_pass",
566 side_effect=AssertionError("invalid deep-research comparison must not query pass"),
567 ), mock.patch.object(
568 env, "_discover_and_apply_x_credentials",
569 side_effect=AssertionError("invalid deep-research comparison must not extract browser cookies"),
570 ):
571 rc, out, err = _run_cli(argv)
572
573 assert rc == 2
574 assert out == ""
575 assert "--deep-research cannot be combined with competitor or vs-mode" in err
576
577 def test_env_get_config_skips_keychain_and_pass_when_policy_disables_secret_stores(
578 self, tmp_path: Path, monkeypatch,
579 ):
580 monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "missing.env")
581 monkeypatch.chdir(tmp_path)
582 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
583
584 with mock.patch.object(
585 env, "_load_keychain", side_effect=AssertionError("Keychain must not be queried"),
586 ), mock.patch.object(
587 env, "_load_pass", side_effect=AssertionError("pass must not be queried"),
588 ):
589 cfg = env.get_config(policy=env.ConfigLoadPolicy(load_secret_stores=False))
590
591 assert cfg["_CONFIG_SOURCE"] == "env_only"
592
593 @pytest.mark.parametrize(
594 ("argv", "expected_rc"),
595 [
596 (["Ghostty", "--mock", "--quick"], 0),
597 (["--diagnose", "--mock"], 0),
598 (["--discover", "--finalize"], 0),
599 ([], 2),
600 (["--discover-shallow"], 2),
601 (["--deep-research"], 2),
602 (["OpenAI vs Anthropic", "--deep-research"], 2),
603 (["--verify-freshness", "--mock"], 0),
604 (["queue", "list"], 0),
605 (["setup", "--github-start"], 0),
606 ],
607 )
608 def test_offline_mock_finalize_and_invalid_modes_never_query_keychain_or_pass(
609 self, tmp_path: Path, monkeypatch, argv: list[str], expected_rc: int,
610 ):
611 env_file = tmp_path / ".env"
612 env_file.write_text("FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n", encoding="utf-8")
613 env_file.chmod(0o600)
614 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
615 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
616 monkeypatch.delenv("LAST30DAYS_API_KEY", raising=False)
617 monkeypatch.delenv("LAST30DAYS_API_BASE", raising=False)
618 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
619 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
620 if "--verify-freshness" in argv:
621 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
622
623 with mock.patch.object(
624 env, "_load_keychain", side_effect=AssertionError("Keychain must not be queried"),
625 ), mock.patch.object(
626 env, "_load_pass", side_effect=AssertionError("pass must not be queried"),
627 ), mock.patch.object(
628 env, "_discover_and_apply_x_credentials",
629 side_effect=AssertionError("browser cookies must not be extracted"),
630 ), mock.patch.object(cli.pipeline, "diagnose", return_value={"available_sources": ["reddit"]}), \
631 mock.patch.object(cli.pipeline, "run", return_value=_sample_report("Ghostty")), \
632 mock.patch.object(cli, "_render_save_and_print", return_value=0), \
633 mock.patch.object(cli, "_run_discover_protocol_leg", return_value=0), \
634 mock.patch.object(cli, "_run_queue_list", return_value=0), \
635 mock.patch("lib.setup_wizard.run_github_start", return_value={"status": "started"}):
636 rc, _out, err = _run_cli(argv)
637
638 assert rc == expected_rc, err
639
640 def test_cached_report_export_skips_keychain_pass_and_browser_cookies(
641 self, tmp_path: Path, monkeypatch,
642 ):
643 env_file = tmp_path / ".env"
644 env_file.write_text("FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n", encoding="utf-8")
645 env_file.chmod(0o600)
646 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
647 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
648 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
649 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
650 syn = tmp_path / "syn.md"
651 syn.write_text("# Cached export synthesis\n", encoding="utf-8")
652
653 with mock.patch.object(
654 env, "_load_keychain", side_effect=AssertionError("Keychain must not be queried"),
655 ), mock.patch.object(
656 env, "_load_pass", side_effect=AssertionError("pass must not be queried"),
657 ), mock.patch.object(
658 env, "_discover_and_apply_x_credentials",
659 side_effect=AssertionError("browser cookies must not be extracted"),
660 ):
661 rc, out, err = _run_cli([
662 "OpenClaw", "--cached-report", "--emit=html", "--synthesis-file", str(syn),
663 ])
664
665 assert rc == 0, err
666 assert "Cached export synthesis" in out
667
668 @pytest.mark.parametrize("secret_store", ["keychain", "pass"])
669 def test_hosted_corpus_agent_host_html_cache_reuse_reloads_secret_stores_without_cookies(
670 self, tmp_path: Path, monkeypatch, secret_store: str,
671 ):
672 notes = tmp_path / "notes"
673 notes.mkdir()
674 env_file = tmp_path / ".env"
675 env_file.write_text(
676 f"FROM_BROWSER=chrome\nBROWSER_CONSENT=true\nLAST30DAYS_CORPUS_DIRS={notes}\n",
677 encoding="utf-8",
678 )
679 env_file.chmod(0o600)
680 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
681 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
682 monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_DUMMY_TEST_KEY_00000")
683 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1")
684 monkeypatch.setenv("CLAUDECODE", "1")
685 monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False)
686 monkeypatch.delenv("LAST30DAYS_CORPUS_DIRS", raising=False)
687 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
688 monkeypatch.delenv("LAST30DAYS_ALLOW_ENGINE_PLAN", raising=False)
689 monkeypatch.delenv("XAI_API_KEY", raising=False)
690
691 syn = tmp_path / "syn.md"
692 syn.write_text("# Agent host cached synthesis\n", encoding="utf-8")
693 stored_secret = {"XAI_API_KEY": f"dummy-{secret_store}-xai-key"}
694 kc_return = stored_secret if secret_store == "keychain" else {}
695 pass_return = stored_secret if secret_store == "pass" else {}
696
697 # Build and save a cached report as produced by an earlier local run
698 # that had the Keychain/pass key loaded (without browser cookies).
699 with mock.patch.object(env, "_load_keychain", return_value=kc_return), \
700 mock.patch.object(env, "_load_pass", return_value=pass_return):
701 prior_config = env.get_config(
702 policy=env.ConfigLoadPolicy(browser_cookies="off", load_secret_stores=True)
703 )
704 prior_args = cli.build_parser().parse_args([
705 "OpenClaw", "--emit=html", "--synthesis-file", str(syn),
706 ])
707 prior_opts = cli._cache_research_options(
708 prior_args, prior_config, resolved_corpus_dirs=[notes],
709 )
710 prior_report = _sample_report("OpenClaw")
711 prior_report.range_from, prior_report.range_to = cli.dates.get_date_range(30)
712 assert cli._write_last_run("OpenClaw", prior_report, research_options=prior_opts)
713
714 kc_mock = mock.Mock(return_value=kc_return)
715 pass_mock = mock.Mock(return_value=pass_return)
716 with mock.patch.object(env, "_load_keychain", kc_mock), \
717 mock.patch.object(env, "_load_pass", pass_mock), \
718 mock.patch.object(
719 env, "_discover_and_apply_x_credentials",
720 side_effect=AssertionError("HTML cache reuse must not read browser cookies"),
721 ), \
722 mock.patch.object(
723 cookie_extract, "extract_cookies",
724 side_effect=AssertionError("HTML cache reuse must not read browser cookies"),
725 ), \
726 mock.patch.object(
727 cli.pipeline, "run",
728 side_effect=AssertionError("HTML cache reuse must not start research"),
729 ):
730 rc, out, err = _run_cli([
731 "OpenClaw", "--emit=html", "--synthesis-file", str(syn),
732 ])
733
734 assert rc == 0, err
735 assert "Reusing cached report data" in err
736 assert "Agent host cached synthesis" in out
737 # Initial tentative hosted load skipped secret stores; local HTML cache
738 # check reloaded them once without touching browser cookies.
739 assert kc_mock.call_count == 1
740 assert pass_mock.call_count == 1
741
742 @pytest.mark.parametrize(
743 ("argv", "expected_load_stores"),
744 [
745 (["setup", "--openclaw", "--github-start"], True),
746 (["setup", "--openclaw", "--device-auth"], True),
747 (["setup", "--openclaw", "--reddit-session"], True),
748 (["setup", "--github-start"], False),
749 (["setup", "--store-key", "XAI_API_KEY", "--openclaw"], False),
750 (["setup", "--install-hooks", "--openclaw"], False),
751 ],
752 )
753 def test_setup_openclaw_precedence_preserves_secret_stores_in_policy(
754 self, argv: list[str], expected_load_stores: bool,
755 ):
756 parser = cli.build_parser()
757 args, extra = parser.parse_known_args(argv)
758 policy = cli._config_policy_for_args(args, "setup", extra)
759 assert policy.browser_cookies == "off"
760 assert policy.load_secret_stores is expected_load_stores
761
762 def test_setup_openclaw_with_github_start_reports_keychain_keys(
763 self, tmp_path: Path, monkeypatch,
764 ):
765 monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "missing.env")
766 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
767 monkeypatch.chdir(tmp_path)
768 monkeypatch.delenv("XAI_API_KEY", raising=False)
769 monkeypatch.delenv("LAST30DAYS_SKIP_KEYCHAIN", raising=False)
770
771 with mock.patch.object(env, "_load_keychain", return_value={"XAI_API_KEY": "dummy-kc-xai"}) as kc, \
772 mock.patch.object(env, "_load_pass", return_value={}), \
773 mock.patch.object(
774 env, "_discover_and_apply_x_credentials",
775 side_effect=AssertionError("openclaw setup must not read browser cookies"),
776 ), \
777 mock.patch("lib.setup_wizard._install_digg_cli", return_value=(False, "no_npx", "", "")):
778 rc, out, err = _run_cli(["setup", "--openclaw", "--github-start"])
779
780 assert rc == 0, err
781 kc.assert_called_once()
782 payload = json.loads(out)
783 assert payload["keys"]["xai"] is True
784 assert payload["x_method"] == "xai"
785
786 @pytest.mark.parametrize(
787 "argv",
788 [
789 [],
790 ["--discover-shallow"],
791 ["--deep-research"],
792 ["--nominate-only"],
793 ["setup", "--openclaw", "--allow-browser-cookies"],
794 ["setup", "--github-start", "--allow-browser-cookies"],
795 ],
796 )
797 def test_empty_invalid_and_non_auto_setup_never_trigger_cookie_extraction(
798 self, tmp_path: Path, monkeypatch, argv: list[str],
799 ):
800 env_file = tmp_path / ".env"
801 env_file.write_text("FROM_BROWSER=chrome\nBROWSER_CONSENT=true\n", encoding="utf-8")
802 env_file.chmod(0o600)
803 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
804 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
805 monkeypatch.setenv("LAST30DAYS_SKIP_KEYCHAIN", "1")
806
807 with mock.patch.object(env, "_load_keychain", return_value={}), \
808 mock.patch.object(env, "_load_pass", return_value={}), \
809 mock.patch.object(
810 env, "_discover_and_apply_x_credentials",
811 side_effect=AssertionError("must not extract browser cookies"),
812 ), \
813 mock.patch("lib.setup_wizard.run_openclaw_setup", return_value={"ok": True}), \
814 mock.patch("lib.setup_wizard.run_github_start", return_value={"status": "started"}):
815 rc, _out, _err = _run_cli(argv)
816
817 expected_rc = 0 if argv and argv[0] == "setup" else 2
818 assert rc == expected_rc
819
820
821 # ---------------------------------------------------------------------------
822 # HIGH-004: Shared config dict mutation race & cross-entity contamination
823 # ---------------------------------------------------------------------------
824
825
826 class TestComparisonFanoutConfigIsolation:
827 def test_pipeline_run_does_not_mutate_caller_config_on_default_path(self):
828 caller_config: dict[str, object] = {"INCLUDE_SOURCES": ""}
829 snapshot = dict(caller_config)
830
831 report = pipeline.run(
832 topic="$NVDA stock",
833 config=caller_config,
834 depth="quick",
835 requested_sources=["reddit"],
836 mock=True,
837 web_backend="none",
838 as_of_date="2026-07-10",
839 )
840
841 assert report.topic == "$NVDA stock"
842 assert caller_config == snapshot
843 assert "_financial_topic" not in caller_config
844 assert "_jobs_lane" not in caller_config
845 assert "stocktwits" not in pipeline.available_sources(caller_config)
846
847 def test_concurrent_comparison_fanout_isolates_configs_under_heavy_mutation(
848 self, tmp_path: Path, monkeypatch,
849 ):
850 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
851 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
852 monkeypatch.setenv("LAST30DAYS_NO_PATENT_DIGEST", "1")
853
854 outer_config: dict[str, object] = {
855 "INCLUDE_SOURCES": "",
856 "EXCLUDE_SOURCES": "yahoo_finance",
857 "_BROWSER_COOKIE_MODE": "off",
858 }
859 peers = ["PeerOne", "PeerTwo", "PeerThree", "PeerFour", "PeerFive"]
860 barrier = threading.Barrier(1 + len(peers), timeout=10.0)
861 seen_configs: dict[str, dict[str, object]] = {}
862 seen_ids: dict[str, int] = {}
863 lock = threading.Lock()
864
865 def racing_pipeline_run(**kwargs):
866 entity = kwargs["topic"]
867 cfg = kwargs["config"]
868 with lock:
869 seen_configs[entity] = dict(cfg)
870 seen_ids[entity] = id(cfg)
871 # Synchronize all 6 worker threads so mutation and dict(cfg) overlap.
872 barrier.wait()
873 if entity == "$NVDA stock":
874 for i in range(250):
875 cfg[f"_race_key_{i}"] = i
876 cfg["_financial_topic"] = True
877 cfg["_jobs_story_terms"] = ["nvda-only-term"]
878 else:
879 for _ in range(250):
880 _ = dict(cfg)
881 _ = list(cfg.items())
882 return _sample_report(entity)
883
884 with mock.patch.object(cli.env, "get_config", return_value=outer_config), \
885 mock.patch.object(cli.pipeline, "diagnose", return_value={"available_sources": ["reddit"]}), \
886 mock.patch.object(cli.pipeline, "run", side_effect=racing_pipeline_run), \
887 mock.patch.object(cli, "_show_runtime_ui"), \
888 mock.patch.object(cli, "_render_save_and_print", return_value=0) as render_mock:
889 rc, _out, err = _run_cli([
890 "$NVDA stock",
891 "--competitors-list", ",".join(peers),
892 "--mock",
893 "--quick",
894 "--amazon-query", "Nvidia GPU",
895 "--devto-tags", "cuda,gpu",
896 "--polymarket-keywords", "nvidia",
897 "--dedicated-subreddits", "r/nvidia",
898 "--jobs-board", "https://jobs.example.test/nvidia",
899 "--company", "Nvidia",
900 ])
901
902 assert rc == 0, err
903 # Every entity thread must have received a distinct config object.
904 assert len(seen_ids) == 1 + len(peers)
905 assert len(set(seen_ids.values())) == 1 + len(peers)
906 assert id(outer_config) not in seen_ids.values()
907
908 # All 6 entity reports survived without RuntimeError during iteration.
909 entity_reports = render_mock.call_args.args[2]
910 assert [label for label, _ in entity_reports] == ["$NVDA stock", *peers]
911
912 # Main entity-specific transient keys must not contaminate any peer.
913 for peer in peers:
914 peer_cfg = seen_configs[peer]
915 assert "_financial_topic" not in peer_cfg
916 assert "_jobs_story_terms" not in peer_cfg
917 assert "_company_signal" not in peer_cfg
918 assert "_jobs_board" not in peer_cfg
919 assert "_amazon_query" not in peer_cfg
920 assert "_devto_tags" not in peer_cfg
921 assert "_meta_ads_page" not in peer_cfg
922 assert "_dedicated_subreddits" not in peer_cfg
923 assert "_polymarket_keywords" not in peer_cfg
924 assert "_polymarket_hints" not in peer_cfg
925 assert "_auto_resolve_context" not in peer_cfg
926 assert not any(k.startswith("_race_key_") for k in peer_cfg)
927 assert peer_cfg["_company"]["entity"] == peer
928
929 # Outer config must remain untouched by worker mutations.
930 assert "_financial_topic" not in outer_config
931 assert "_jobs_story_terms" not in outer_config
932 assert not any(k.startswith("_race_key_") for k in outer_config)
933
934
935 # ---------------------------------------------------------------------------
936 # HIGH-006: Read-only --preflight and --diagnose never bypassed by subcommands
937 # ---------------------------------------------------------------------------
938
939
940 class TestReadOnlyPreflightAndDiagnoseGuard:
941 @pytest.mark.parametrize("flag", ["--preflight", "--diagnose"])
942 def test_store_key_rejected_before_reading_stdin_or_writing_env(
943 self, tmp_path: Path, flag: str,
944 ):
945 env_path = tmp_path / ".env"
946 stdin_read = mock.Mock(side_effect=AssertionError("stdin must not be read"))
947
948 class _GuardStdin:
949 readline = stdin_read
950
951 with mock.patch.object(cli.env, "CONFIG_FILE", env_path), \
952 mock.patch.object(cli.env, "get_config", side_effect=AssertionError("must not load config")), \
953 mock.patch("lib.setup_wizard.write_api_key", side_effect=AssertionError("must not write key")), \
954 mock.patch.object(sys, "stdin", _GuardStdin()):
955 rc, out, err = _run_cli(["setup", "--store-key", "XAI_API_KEY", flag])
956
957 assert rc == 2
958 assert out == ""
959 assert f"{flag} cannot be combined with the 'setup' command" in err
960 assert not env_path.exists()
961 stdin_read.assert_not_called()
962
963 @pytest.mark.parametrize("flag", ["--preflight", "--diagnose"])
964 @pytest.mark.parametrize(
965 "cmd_argv",
966 [
967 ["setup"],
968 ["setup", "--allow-browser-cookies"],
969 ["setup", "--openclaw"],
970 ["setup", "--github-start"],
971 ["setup", "--reddit-session"],
972 ["setup", "--install-hooks"],
973 ["library", "feed"],
974 ["library", "feed", "--publish"],
975 ["library", "harvest"],
976 ["library", "search", "MCP"],
977 ["queue", "cover", "Agent memory"],
978 ["queue", "list"],
979 ["doctor"],
980 ],
981 )
982 def test_admin_subcommands_rejected_with_preflight_or_diagnose(
983 self, flag: str, cmd_argv: list[str],
984 ):
985 with mock.patch.object(cli.env, "get_config", side_effect=AssertionError("must not load config")), \
986 mock.patch("lib.setup_wizard.run_auto_setup", side_effect=AssertionError("setup must not run")), \
987 mock.patch("lib.setup_wizard.write_setup_config", side_effect=AssertionError("setup must not write")), \
988 mock.patch("lib.setup_wizard.run_openclaw_setup", side_effect=AssertionError("openclaw must not run")), \
989 mock.patch("lib.hook_installer.install_hooks", side_effect=AssertionError("hooks must not install")), \
990 mock.patch.object(cli, "_run_library_feed", side_effect=AssertionError("library feed must not run")), \
991 mock.patch.object(cli, "_run_library_harvest", side_effect=AssertionError("library harvest must not run")), \
992 mock.patch.object(cli, "_run_library_search", side_effect=AssertionError("library search must not run")), \
993 mock.patch.object(cli, "_run_queue_cover", side_effect=AssertionError("queue cover must not run")), \
994 mock.patch.object(cli, "_run_queue_list", side_effect=AssertionError("queue list must not run")), \
995 mock.patch("lib.doctor.run", side_effect=AssertionError("doctor must not run")):
996 rc, out, err = _run_cli([*cmd_argv, flag])
997
998 assert rc == 2
999 assert out == ""
1000 assert f"{flag} cannot be combined" in err
1001
1002 @pytest.mark.parametrize("mode_args", [["--diagnose"], ["--preflight", "--emit=json"]])
1003 @pytest.mark.parametrize(
1004 "base_argv",
1005 [
1006 ["--discover"],
1007 ["--discover", "AI agents"],
1008 ["--discover", "--nominate-only"],
1009 ["--drill", "cluster 1"],
1010 ["--verify-freshness"],
1011 ],
1012 )
1013 def test_diagnose_and_preflight_not_bypassed_by_discover_drill_or_cached_freshness(
1014 self, base_argv: list[str], mode_args: list[str],
1015 ):
1016 diag_payload = {
1017 "available_sources": ["reddit"],
1018 "providers": {"google": False, "openai": False, "xai": False, "openrouter": False, "perplexity": False},
1019 "has_scrapecreators": False,
1020 "has_github": False,
1021 "safe": True,
1022 "config_source": "env_only",
1023 "ignored_project_config": None,
1024 "ignored_project_config_keys": [],
1025 "ignored_endpoint_overrides": [],
1026 "browser_cookies": {"mode": "plan_only", "browsers": [], "reads_values": False},
1027 "external_commands": {"yt-dlp": False, "digg-pp-cli": False, "gh": False},
1028 "credential_destinations": {"global_env": None},
1029 "local_writes": [],
1030 "native_search": False,
1031 }
1032 with mock.patch.object(cli.env, "get_config", return_value={}), \
1033 mock.patch.object(cli.pipeline, "diagnose", return_value=diag_payload) as diag_mock, \
1034 mock.patch.object(cli, "_run_discover", side_effect=AssertionError("discover must not run")), \
1035 mock.patch.object(cli, "_run_discover_protocol_leg", side_effect=AssertionError("protocol must not run")), \
1036 mock.patch.object(cli, "_run_drill", side_effect=AssertionError("drill must not run")), \
1037 mock.patch.object(cli, "_run_cached_freshness", side_effect=AssertionError("freshness must not run")):
1038 rc, out, err = _run_cli([*base_argv, *mode_args])
1039
1040 assert rc == 0, err
1041 diag_mock.assert_called_once()
1042 parsed = json.loads(out)
1043 if mode_args[0] == "--diagnose":
1044 assert parsed["available_sources"] == ["reddit"]
1045 else:
1046 assert "local_reads" in parsed
1047 assert parsed["safe"] is True
1048
1049 @pytest.mark.parametrize(
1050 ("argv", "expected_key"),
1051 [
1052 (["--research-only", "setup", "--diagnose"], "available_sources"),
1053 (["--research-only", "library", "feed", "--preflight", "--emit=json"], "local_reads"),
1054 ],
1055 )
1056 def test_research_only_allows_inspecting_admin_named_topics(
1057 self, argv: list[str], expected_key: str,
1058 ):
1059 diag_payload = {
1060 "available_sources": ["reddit"],
1061 "providers": {"google": False, "openai": False, "xai": False, "openrouter": False, "perplexity": False},
1062 "has_scrapecreators": False,
1063 "has_github": False,
1064 "safe": True,
1065 "config_source": "env_only",
1066 "ignored_project_config": None,
1067 "ignored_project_config_keys": [],
1068 "ignored_endpoint_overrides": [],
1069 "browser_cookies": {"mode": "plan_only", "browsers": [], "reads_values": False},
1070 "external_commands": {"yt-dlp": False, "digg-pp-cli": False, "gh": False},
1071 "credential_destinations": {"global_env": None},
1072 "local_writes": [],
1073 "native_search": False,
1074 }
1075 with mock.patch.object(cli.env, "get_config", return_value={}), \
1076 mock.patch.object(cli.pipeline, "diagnose", return_value=diag_payload):
1077 rc, out, err = _run_cli(argv)
1078
1079 assert rc == 0, err
1080 assert expected_key in json.loads(out)
1081
1082
1083 # ---------------------------------------------------------------------------
1084 # HIGH-007: Cache-only --verify-freshness --publish-html guard & --synthesis-file
1085 # ---------------------------------------------------------------------------
1086
1087
1088 class TestCachedFreshnessPublishAndSynthesisContract:
1089 @pytest.mark.parametrize("emit_args", [[], ["--emit=compact"], ["--emit=md"], ["--emit=json"]])
1090 def test_cached_freshness_publish_html_requires_html_emit_before_dispatch(
1091 self, tmp_path: Path, monkeypatch, emit_args: list[str],
1092 ):
1093 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
1094 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
1095 cache_path = tmp_path / "last-report.json"
1096 before = cache_path.read_bytes()
1097
1098 with mock.patch.object(cli.env, "get_config", return_value={}), \
1099 mock.patch.object(cli, "_run_cached_freshness", side_effect=AssertionError("must not dispatch")), \
1100 mock.patch.object(html_publish, "publish_html", side_effect=AssertionError("must not publish")):
1101 rc, out, err = _run_cli(["--verify-freshness", "--publish-html", *emit_args])
1102
1103 assert rc == 2
1104 assert out == ""
1105 assert "--publish-html requires --emit=html" in err
1106 assert cache_path.read_bytes() == before
1107
1108 def test_run_cached_freshness_direct_rejects_publish_html_without_html_emit(
1109 self, tmp_path: Path, monkeypatch,
1110 ):
1111 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
1112 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
1113 cache_path = tmp_path / "last-report.json"
1114 before = cache_path.read_bytes()
1115 args = cli.build_parser().parse_args(["--verify-freshness", "--publish-html"])
1116
1117 stderr = io.StringIO()
1118 with mock.patch.object(html_publish, "publish_html", side_effect=AssertionError("must not publish")), \
1119 redirect_stderr(stderr):
1120 rc = cli._run_cached_freshness(args, {})
1121
1122 assert rc == 2
1123 assert "--publish-html requires --emit=html" in stderr.getvalue()
1124 assert cache_path.read_bytes() == before
1125
1126 def test_cached_freshness_honors_synthesis_file_for_html_and_publish(
1127 self, tmp_path: Path, monkeypatch,
1128 ):
1129 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
1130 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
1131 synthesis_path = tmp_path / "synthesis.md"
1132 synthesis_path.write_text(
1133 "# Verified Briefing\n\nCustom synthesis paragraph for freshness HTML export.\n",
1134 encoding="utf-8",
1135 )
1136 published_docs: list[str] = []
1137
1138 def fake_publish(doc: str, *, password=None):
1139 published_docs.append(doc)
1140 return {"url": "https://verified.ht-ml.app", "site_id": "s1", "status": "active"}
1141
1142 with mock.patch.object(cli.env, "get_config", return_value={}), \
1143 mock.patch.object(html_publish, "publish_html", side_effect=fake_publish):
1144 rc, out, err = _run_cli([
1145 "--verify-freshness",
1146 "--mock",
1147 "--emit=html",
1148 "--synthesis-file", str(synthesis_path),
1149 "--publish-html",
1150 ])
1151
1152 assert rc == 0, err
1153 assert "Custom synthesis paragraph for freshness HTML export." in out
1154 assert "<html" in out.lower()
1155 assert len(published_docs) == 1
1156 assert "<html" in published_docs[0].lower()
1157 assert "Custom synthesis paragraph for freshness HTML export." in published_docs[0]
1158 assert "Published HTML to https://verified.ht-ml.app" in err
1159 payload = json.loads((tmp_path / "last-report.json").read_text(encoding="utf-8"))
1160 assert payload["reports"][0]["report"]["freshness_verdicts"][0]["verdict"] == "unsupported"
1161
1162 def test_cached_freshness_warns_and_ignores_synthesis_file_when_emit_not_html(
1163 self, tmp_path: Path, monkeypatch,
1164 ):
1165 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
1166 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
1167 synthesis_path = tmp_path / "synthesis.md"
1168 synthesis_path.write_text("# Ignored synthesis", encoding="utf-8")
1169
1170 with mock.patch.object(cli.env, "get_config", return_value={}):
1171 rc, out, err = _run_cli([
1172 "--verify-freshness",
1173 "--mock",
1174 "--emit=compact",
1175 "--synthesis-file", str(synthesis_path),
1176 ])
1177
1178 assert rc == 0, err
1179 assert "--synthesis-file is only used with --emit=html; ignoring." in err
1180 assert "Ignored synthesis" not in out
1181
1182 def test_cached_freshness_missing_synthesis_file_exits_2_without_mutating_cache(
1183 self, tmp_path: Path, monkeypatch,
1184 ):
1185 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
1186 assert cli._write_last_run("OpenClaw", _sample_report("OpenClaw"))
1187 cache_path = tmp_path / "last-report.json"
1188 before = cache_path.read_bytes()
1189
1190 with mock.patch.object(cli.env, "get_config", return_value={}):
1191 rc, _out, err = _run_cli([
1192 "--verify-freshness",
1193 "--mock",
1194 "--emit=html",
1195 "--synthesis-file", str(tmp_path / "does-not-exist.md"),
1196 ])
1197
1198 assert rc == 2
1199 assert "Cannot read --synthesis-file" in err
1200 assert cache_path.read_bytes() == before
1201
1201 lines PYTHON