AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(planner): enforce host plan gate before live diagnostics (#1244)
Ilia Alshanetsky43aeb04e9e99
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 2b54c26c..14dba1e4 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -444,6 +444,25 @@ An explicit `--register` wins over `LAST30DAYS_REGISTER`; the environment/configWhen you invoke `/last30days` from Claude Code, Codex, or Gemini, the host model **is** the reasoning provider for plan + synthesis - you don't need any of the keys above unless you also run the script headlessly (cron, CI, watchlist).+### Agent-hosted runs must pass `--plan`++When the engine detects an agent host, a research run without `--plan` exits 2 before live diagnostics or retrieval and does not call the internal planner. It prints a `[Planner] LAW 7` message telling the host model to write the plan and pass it with `--plan` (Step 0.75 and Research Execution in `references/research-runbook.md`). The engine treats a run as agent-hosted when any of these variables is set in the process environment (a `.env` line never counts):++| Variable | Set by |+|---|---|+| `CLAUDECODE`, `CLAUDE_CODE_ENTRYPOINT` | Claude Code / Claude Agent SDK |+| `CODEX_THREAD_ID`, `CODEX_SESSION_ID`, `CODEX_SANDBOX` | Codex |+| `LAST30DAYS_HOST` | Hosts that self-identify (e.g. `grok-bot`) |+| `LAST30DAYS_HOST_AGENT=1` | Any other agent runtime, explicitly |++Runs that may skip the plan stay unaffected: `--mock`, `--hiring-signals`, `--auto-resolve` (the no-WebSearch path), comparison runs (`A vs B`, `--competitors*`), the hosted API path, and non-research commands (`doctor`, `setup`, `--diagnose`, `--preflight`, discovery legs, `--drill`, `--verify-freshness` without a topic, `library`/`queue` commands). The watchlist runner and the MCP `research` tool opt their engine calls back in automatically.++| Variable | Effect |+|---|---|+| `LAST30DAYS_ALLOW_ENGINE_PLAN=1` | Lift the gate for a headless or cron run launched from an agent shell: the engine plans internally with the reasoning provider above (or the deterministic fallback). Process environment only. |++Outside a detected agent host nothing changes. The engine still plans internally and prints the LAW 7 reminder whenever it ends on the deterministic fallback, including when the internal planner fails (for example an HTTP 402 from a provider with no credits).+### Provider endpoint overridesPoint a provider at a gateway (LiteLLM, an enterprise proxy, a self-hosted OpenAI-compatible server) without a code change:diff --git a/changelog.d/1178.changed.md b/changelog.d/1178.changed.mdnew file mode 100644index 00000000..55d9cf6c--- /dev/null+++ b/changelog.d/1178.changed.md@@ -0,0 +1 @@+Under a detected agent host (Claude Code, Codex, `LAST30DAYS_HOST`, or `LAST30DAYS_HOST_AGENT=1`), a research run without `--plan` now stops with exit 2 and a LAW 7 message before any retrieval or internal-planner spend, instead of silently planning with an engine-side provider. `--mock`, `--hiring-signals`, `--auto-resolve`, comparison runs and non-research commands are exempt, and `LAST30DAYS_ALLOW_ENGINE_PLAN=1` restores engine planning for headless runs under an agent. Outside an agent host, a failed internal planner (for example HTTP 402) now also prints the LAW 7 reminder.diff --git a/mcp/internal/tools/research.go b/mcp/internal/tools/research.goindex 53deda8f..2d47349d 100644--- a/mcp/internal/tools/research.go+++ b/mcp/internal/tools/research.go@@ -25,6 +25,12 @@ type Config struct {// browser-cookie consent and configuration.const BrowserCookiesEnvOverride = "LAST30DAYS_MCP_ALLOW_BROWSER_COOKIES"+// allowEnginePlanEnv lets the engine use its internal planner. The research+// tool has no query-plan argument, so the engine must plan for itself; without+// this, an MCP server launched from an agent shell (which inherits markers such+// as CLAUDECODE) would hit the engine's LAW 7 host-plan gate and exit 2.+const allowEnginePlanEnv = "LAST30DAYS_ALLOW_ENGINE_PLAN=1"+// Register adds every tool this server exposes to s. The caller supplies a// Config so test harnesses can pin a version without touching globals.func Register(s *server.MCPServer, cfg Config) {@@ -83,6 +89,7 @@ func makeResearchHandler(cfg Config) server.ToolHandlerFunc {res, runErr := engine.Run(ctx, engine.RunOptions{CacheDir: cacheDir,Args: runArgs,+ ExtraEnv: researchExtraEnv(),})if runErr != nil {return mcplib.NewToolResultError(formatRunError(runErr, res)), nil@@ -109,6 +116,10 @@ func researchRunArgs(topic, emit string, save bool) []string {return append(runArgs, "--", topic)}+func researchExtraEnv() []string {+ return []string{allowEnginePlanEnv}+}+func browserCookiesAllowed() bool {raw := os.Getenv(BrowserCookiesEnvOverride)return raw == "1" ||diff --git a/mcp/internal/tools/research_test.go b/mcp/internal/tools/research_test.goindex b4371c04..7b33f4d1 100644--- a/mcp/internal/tools/research_test.go+++ b/mcp/internal/tools/research_test.go@@ -252,3 +252,10 @@ func TestFormatRunErrorHandlesNilResult(t *testing.T) {t.Fatalf("nil result: got %q, want %q", msg, "boom")}}++func TestResearchExtraEnvAllowsEnginePlanning(t *testing.T) {+ got := researchExtraEnv()+ if len(got) != 1 || got[0] != "LAST30DAYS_ALLOW_ENGINE_PLAN=1" {+ t.Fatalf("researchExtraEnv() = %#v, want [LAST30DAYS_ALLOW_ENGINE_PLAN=1]", got)+ }+}diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 3c0aa537..ff6ed26c 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -182,6 +182,8 @@ GENERAL / NEWS / PROMPTING / RECOMMENDATIONS use `What I learned:` on line 3 and**LAW 7 - YOU ARE THE PLANNER. `--plan` IS MANDATORY ON NAMED-ENTITY TOPICS.** The hosting reasoning model generates the JSON query plan without an external provider key. Internal planning/fallback is a headless/cron path. Named entities include proper nouns, products, people, projects, and topics benefiting from handle resolution. Before the research command, verify it contains `--plan "$QUERY_PLAN_FILE"` (or another readable plan-file path); otherwise stop and generate the plan through Step 0.75. Do not interpret “provider” in an engine message as a requirement for credentials to write your own plan. The explicit no-host-WebSearch and jobs-only exceptions remain scoped to their runbook/mode procedures.+Agent research without `--plan` exits 2 before live probes unless exempt.+Write plans to a temporary file using `mktemp` with trailing `XXXXXX`, a cleanup trap, `cat >|`, and a quoted heredoc delimiter. Pass the file path, never inline single-quoted JSON. Run the heredoc directly in the shell tool. Never wrap the invocation in `bash -lc '...'` or `zsh -lc '...'`; apostrophes in search/ranking strings must remain data.**LAW 8 - CITE READABLY FOR THE CURRENT HOST.** Governing host/tool requirements and user instructions determine required links before renderer preferences. Detection is deterministic: `CLAUDECODE` or `CURSOR_AGENT` set means hidden-link default; both unset means visible-URL default. This renderer split is separate from onboarding; Cursor remains non-modal.diff --git a/skills/last30days/references/research-runbook.md b/skills/last30days/references/research-runbook.mdindex bf4f4bb6..42f4dd08 100644--- a/skills/last30days/references/research-runbook.md+++ b/skills/last30days/references/research-runbook.md@@ -651,7 +651,7 @@ Then add to the engine command:**If you skipped Steps 0.55 and 0.75 (no WebSearch -- OpenClaw, Codex, etc.), add:**- `--auto-resolve` (the engine will use Brave/Exa/Serper to discover subreddits and context before planning)-**If you skipped Steps 0.55 and 0.75 (no WebSearch), run with `--auto-resolve`; the engine plans internally.**+**If you skipped Steps 0.55 and 0.75 (no WebSearch), keep `--auto-resolve` on the command; the engine plans internally.** Under a detected agent host, a research run with neither `--plan` nor `--auto-resolve` exits 2 (LAW 7).Use a **timeout of 300000** (5 minutes) on the Bash call. The script typically takes 1-3 minutes.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 9616520f..9cbcb0ca 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -2748,6 +2748,50 @@ def _comparison_requested(args: argparse.Namespace, topic: str) -> bool:) or len(_planner._comparison_entities(topic, uncapped=True)) >= 2+LAW7_HOST_PLAN_EXIT = 2+++def _law7_host_plan_message(signal: str) -> str:+ return (+ "[Planner] LAW 7: no --plan passed, and this run is agent-hosted "+ f"({signal} is set). The engine stopped before retrieval and did not "+ "call its internal planner. If you are the reasoning model hosting "+ "this skill, YOU ARE the planner; no API key or provider is needed. "+ "Write the JSON query plan (references/research-runbook.md Step 0.75) "+ "to a tmpfile with a "+ "quoted heredoc - QUERY_PLAN_FILE=$(mktemp "+ "\"${TMPDIR:-/tmp}/last30days-plan.XXXXXX\"); "+ "cat >| \"$QUERY_PLAN_FILE\" <<'PLAN_EOF' ... PLAN_EOF - and re-run "+ "with --plan \"$QUERY_PLAN_FILE\" (see Research Execution in that "+ "runbook). With no "+ "web-search tool, pass --auto-resolve instead. For headless or cron "+ f"runs under an agent, set {env.ALLOW_ENGINE_PLAN_VAR}=1 to let the "+ "engine plan internally.\n"+ )+++def _law7_host_plan_signal(args: argparse.Namespace, topic: str) -> str:+ """Identify a blocked agent run before configuration probes run."""+ if not topic:+ return ""+ if args.plan or args.mock or args.hiring_signals or args.auto_resolve:+ return ""+ if _comparison_requested(args, topic):+ return ""+ if env.engine_plan_allowed():+ return ""+ return env.agent_host_signal()+++def _law7_host_plan_gate(args: argparse.Namespace, topic: str) -> int | None:+ """Stop a plan-less agent research run after dispatch and cache exemptions."""+ signal = _law7_host_plan_signal(args, topic)+ if not signal:+ return None+ sys.stderr.write(_law7_host_plan_message(signal))+ return LAW7_HOST_PLAN_EXIT++def _read_x_envelope(path: str,topic: str,@@ -2891,6 +2935,9 @@ def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: librowser_mode = "plan_only"elif normalized_topic == "setup":browser_mode = "read" if _setup_allows_browser_cookies(args, extra_argv) else "off"+ elif _law7_host_plan_signal(args, topic):+ # Hosted and cached paths need config before dispatch, but no browser read.+ browser_mode = "plan_only"else:browser_mode = "read"return env.ConfigLoadPolicy(@@ -3697,20 +3744,14 @@ def _main(except x_envelope.EnvelopeContractError as exc:sys.stderr.write(f"[last30days] {exc.message}\n")return 2- diag = pipeline.diagnose(- config, requested_sources, safe=args.diagnose,- x_envelope=x_posts_envelope is not None,- )-if args.diagnose:+ diag = pipeline.diagnose(+ config, requested_sources, safe=True,+ x_envelope=x_posts_envelope is not None,+ )print(json.dumps(diag, indent=2, sort_keys=True))return 0- # Competitor sub-runs shallow-copy this config. The shared object makes the- # paid Perplexity cap command-wide and thread-safe across that fanout. Keep- # this runtime-only object out of the safe diagnose configuration contract.- config["_perplexity_paid_budget"] = pipeline.PaidSourceBudget()-# Per-entity host-fetched X envelopes are validated here, on the main# thread and BEFORE the report-cache lookup, so a bad or stale one fails# closed (exit 2) instead of silently dropping that entity inside the@@ -3779,6 +3820,22 @@ def _main()sys.stderr.flush()+ # LAW 7: an agent host that skipped --plan stops before live diagnostics,+ # auto-resolve, the internal planner, or any source retrieval can spend.+ law7_exit = _law7_host_plan_gate(args, topic)+ if law7_exit is not None:+ return law7_exit++ diag = pipeline.diagnose(+ config, requested_sources, safe=False,+ x_envelope=x_posts_envelope is not None,+ )++ # Competitor sub-runs shallow-copy this config. The shared object makes the+ # paid Perplexity cap command-wide and thread-safe across that fanout. Keep+ # this runtime-only object out of the safe diagnose configuration contract.+ config["_perplexity_paid_budget"] = pipeline.PaidSourceBudget()+progress = ui.ProgressDisplay(topic, show_banner=True)progress.start_processing()diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex 23cc2db4..8030d694 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -1265,6 +1265,52 @@ GROK_BOT_HOST = 'grok-bot'# Per-session X connector lane signal: process env only.X_HOST_LANE_VAR = 'LAST30DAYS_X_HOST_LANE'+# Agent-hosted run detection, used only to enforce SKILL.md LAW 7 (the host+# model writes the query plan and passes --plan). This is separate from the+# X policy above, which trusts LAST30DAYS_HOST alone. Here the engine reads+# the markers agent runtimes export into the shells they spawn, because the+# failure it guards against is a host that forgot to plan. Process+# environment only: a .env line never makes a cron run look agent-hosted.+AGENT_HOST_ENV_VARS = (+ 'CLAUDECODE', # Claude Code+ 'CLAUDE_CODE_ENTRYPOINT', # Claude Code / Claude Agent SDK+ 'CODEX_THREAD_ID', # Codex+ 'CODEX_SESSION_ID',+ 'CODEX_SANDBOX',+)+# Explicit self-identification for any other agent runtime.+HOST_AGENT_VAR = 'LAST30DAYS_HOST_AGENT'+# Headless/cron escape hatch under an agent: let the engine plan internally.+ALLOW_ENGINE_PLAN_VAR = 'LAST30DAYS_ALLOW_ENGINE_PLAN'+++def agent_host_signal(environ: Any = None) -> str:+ """Name of the env var that marks this process as agent-hosted, or "".++ ``LAST30DAYS_HOST_AGENT`` counts when truthy; the runtime markers in+ ``AGENT_HOST_ENV_VARS`` and a host self-identification in+ ``LAST30DAYS_HOST`` (e.g. ``grok-bot``) count when non-empty. Returns the+ variable name (never its value) so messages can cite what was detected.+ """+ source = os.environ if environ is None else environ+ if _truthy(source.get(HOST_AGENT_VAR)):+ return HOST_AGENT_VAR+ for name in (*AGENT_HOST_ENV_VARS, X_HOST_VAR):+ if str(source.get(name) or '').strip():+ return name+ return ''+++def agent_hosted_run(environ: Any = None) -> bool:+ """True when an agent runtime appears to be hosting this engine process."""+ return bool(agent_host_signal(environ))+++def engine_plan_allowed(environ: Any = None) -> bool:+ """True when ``LAST30DAYS_ALLOW_ENGINE_PLAN`` opts back into engine planning."""+ source = os.environ if environ is None else environ+ return _truthy(source.get(ALLOW_ENGINE_PLAN_VAR))+# Public routing definitions for the doctor/backend-descriptor layer# (lib/backends.py). These are aliases for knowledge this module already# owns — the declared X chain order and the pin/floor env var names — sodiff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.pyindex f3441734..e108c800 100644--- a/skills/last30days/scripts/lib/planner.py+++ b/skills/last30days/scripts/lib/planner.py@@ -359,7 +359,11 @@ def plan_query(internal_subrun: when True, suppress the LAW 7 "No --plan passed" stderrwarning. LAW 7 targets the hosting-reasoning-model path; competitorfan-out sub-runs are engine-internal and the warning is a false positive- there. Default False preserves the warning on every user-facing invocation.+ there. Default False preserves the warning on every user-facing invocation+ that ends on the deterministic fallback, including a failed internal+ planner. On a detected agent host the CLI stops a plan-less research run+ before this is reached, apart from its documented exemptions and the+ ``LAST30DAYS_ALLOW_ENGINE_PLAN`` override (``last30days._law7_host_plan_gate``)."""if _should_force_deterministic_plan(topic):return _fallback_plan(@@ -383,6 +387,11 @@ def plan_query(except (ValueError, KeyError, json.JSONDecodeError, OSError, http.HTTPError) as exc:import sysprint(f"[Planner] LLM planning failed, using deterministic fallback: {type(exc).__name__}: {exc}", file=sys.stderr)+ # A failed internal planner (e.g. HTTP 402, no credits) degrades+ # the run exactly like having none, and the host may not be+ # detectable, so the LAW 7 reminder applies here too.+ if not internal_subrun:+ _print_law7_reminder()return _fallback_plan(topic, available_sources, requested_sources, depth,note=f"fallback-plan (LLM error: {type(exc).__name__})",@@ -397,20 +406,24 @@ def plan_query(# the hosting reasoning model, YOU are the provider. LAW 7 / 2026-04-19# Hermes Agent Use Cases failure mode.if not internal_subrun:- import sys- print(- "[Planner] No --plan passed. If you are the reasoning model hosting "- "this skill (Claude Code, Codex, Hermes, Gemini, or any agent runtime), "- "YOU ARE the planner: generate a JSON query plan yourself and pass it "- "via --plan. You do not need an API key or credentials; you ARE the "- "LLM. The deterministic fallback below is the headless/cron path only. "- "See LAW 7 in SKILL.md and Step 0.75 in references/research-runbook.md "- "for the plan schema.",- file=sys.stderr,- )+ _print_law7_reminder()return _fallback_plan(topic, available_sources, requested_sources, depth)+def _print_law7_reminder() -> None:+ import sys+ print(+ "[Planner] No --plan passed. If you are the reasoning model hosting "+ "this skill (Claude Code, Codex, Hermes, Gemini, or any agent runtime), "+ "YOU ARE the planner: generate a JSON query plan yourself and pass it "+ "via --plan. You do not need an API key or credentials; you ARE the "+ "LLM. The deterministic fallback below is the headless/cron path only. "+ "See LAW 7 in SKILL.md and Step 0.75 in references/research-runbook.md "+ "for the plan schema.",+ file=sys.stderr,+ )++def _build_prompt(topic: str,available_sources: list[str],diff --git a/skills/last30days/scripts/verify_v3.py b/skills/last30days/scripts/verify_v3.pyindex dc7eb665..8782f6b2 100644--- a/skills/last30days/scripts/verify_v3.py+++ b/skills/last30days/scripts/verify_v3.py@@ -90,6 +90,8 @@ def verify_smoke() -> list[dict[str, object]]:for provider, extra in SMOKE_CASES:env = os.environ.copy()env["LAST30DAYS_REASONING_PROVIDER"] = provider+ # This smoke exercises the engine's own planner providers on purpose.+ env["LAST30DAYS_ALLOW_ENGINE_PLAN"] = "1"start = time.time()result = run_command([PYTHON, str(ENGINE), SMOKE_TOPIC, "--emit=json", "--json-profile=raw", *extra],@@ -113,12 +115,15 @@ def verify_smoke() -> list[dict[str, object]]:def verify_latency() -> dict[str, dict[str, object]]:results: dict[str, dict[str, object]] = {}+ env = os.environ.copy()+ env["LAST30DAYS_ALLOW_ENGINE_PLAN"] = "1"for profile, extra in LATENCY_PROFILES:timings = []for topic in LATENCY_TOPICS:start = time.time()run_command([PYTHON, str(ENGINE), topic, "--emit=json", "--json-profile=raw", *extra],+ env=env,timeout=300,)timings.append(time.time() - start)diff --git a/skills/last30days/scripts/watchlist.py b/skills/last30days/scripts/watchlist.pyindex e65bc7bb..0a2c993f 100644--- a/skills/last30days/scripts/watchlist.py+++ b/skills/last30days/scripts/watchlist.py@@ -17,7 +17,7 @@ SCRIPT_DIR = Path(__file__).parent.resolve()sys.path.insert(0, str(SCRIPT_DIR))import store-from lib import http, schema, usage+from lib import env as envlib, http, schema, usage# --- Webhook Delivery Functions ---@@ -219,7 +219,7 @@ def _research_topic(topic: dict, run_id: int, child_env: dict) -> dict:capture_output=True,text=True,timeout=300,- env=child_env,+ env={**child_env, envlib.ALLOW_ENGINE_PLAN_VAR: "1"},)duration = time.time() - start_timeif result.returncode != 0:diff --git a/tests/conftest.py b/tests/conftest.pyindex 2f93396a..98f5909c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -93,6 +93,26 @@ def _reset_reddit_keyless_memo():_reddit.reset_scrapecreators_memo()[email protected](autouse=True)+def _no_ambient_agent_host(monkeypatch):+ """Strip agent-host markers so the LAW 7 host-plan gate stays off.++ Contributors mostly run this suite from inside Claude Code or Codex, whose+ shells export CLAUDECODE / CODEX_* markers that CI never has. Tests that+ exercise the gate set these themselves.+ """+ from lib import env as _env++ for name in (+ *_env.AGENT_HOST_ENV_VARS,+ _env.HOST_AGENT_VAR,+ _env.X_HOST_VAR,+ _env.ALLOW_ENGINE_PLAN_VAR,+ ):+ monkeypatch.delenv(name, raising=False)+ yield++@pytest.fixture(autouse=True)def _no_ambient_credentials(monkeypatch):"""Strip credential-shaped variables from the process environment.diff --git a/tests/test_browser_cookie_consent.py b/tests/test_browser_cookie_consent.pyindex 6fc1dc9d..6a02075b 100644--- a/tests/test_browser_cookie_consent.py+++ b/tests/test_browser_cookie_consent.py@@ -59,6 +59,49 @@ def test_repeated_research_reads_explicitly_consented_browser(browser_session, sassert auth_token not in env_path.read_text()+def test_law7_rejection_skips_consented_browser_probe(browser_session, monkeypatch):+ env_path, cdp, native, _ = browser_session+ env_path.write_text(+ "BROWSER_CONSENT=true\n"+ "AGENTCOOKIE=off\n"+ "BROWSER_CDP_URL=ws://127.0.0.1:18800/devtools/page/test\n"+ )+ cdp.return_value = []+ monkeypatch.setenv("CLAUDECODE", "1")+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "best", "espresso", "grinders", "--search=reddit",+ ])++ assert cli.main() == cli.LAW7_HOST_PLAN_EXIT+ cdp.assert_not_called()+ native.assert_not_called()+++def test_law7_auto_resolve_keeps_consented_browser_probe(browser_session, monkeypatch):+ env_path, cdp, _, _ = browser_session+ env_path.write_text(+ "BROWSER_CONSENT=true\n"+ "AGENTCOOKIE=off\n"+ "BROWSER_CDP_URL=ws://127.0.0.1:18800/devtools/page/test\n"+ )+ cdp.return_value = []+ monkeypatch.setenv("CLAUDECODE", "1")+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "best", "espresso", "grinders",+ "--search=reddit", "--auto-resolve",+ ])++ class DiagnoseReached(Exception):+ pass++ with mock.patch.object(cli.pipeline, "diagnose", side_effect=DiagnoseReached):+ with pytest.raises(DiagnoseReached):+ cli.main()+ cdp.assert_called_once_with("ws://127.0.0.1:18800/devtools/page/test")++def test_from_browser_off_overrides_recorded_consent(browser_session):env_path, cdp, native, _ = browser_sessionenv_path.write_text("BROWSER_CONSENT=true\nFROM_BROWSER=off\n")diff --git a/tests/test_env_doc_contract.py b/tests/test_env_doc_contract.pyindex 902f0d0b..d76081bf 100644--- a/tests/test_env_doc_contract.py+++ b/tests/test_env_doc_contract.py@@ -39,6 +39,10 @@ DOC_ONLY_KEYS = {"LAST30DAYS_CONFIG_DIR","LAST30DAYS_PASS_PREFIX","LAST30DAYS_SKIP_KEYCHAIN",+ # LAW 7 host-plan gate: process environment only, so a .env line can+ # neither make a cron run look agent-hosted nor silently lift the gate.+ "LAST30DAYS_ALLOW_ENGINE_PLAN",+ "LAST30DAYS_HOST_AGENT",}diff --git a/tests/test_last_run_state.py b/tests/test_last_run_state.pyindex c78eb740..8b9db8ec 100644--- a/tests/test_last_run_state.py+++ b/tests/test_last_run_state.py@@ -162,7 +162,7 @@ class LastRunStateTests(unittest.TestCase):cli._write_last_run("OpenClaw", _report("OpenClaw"))with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \- mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.env, "get_config", return_value={}) as get_config, \mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline should not run")), \mock.patch.object(sys, "argv", [@@ -172,13 +172,20 @@ class LastRunStateTests(unittest.TestCase):"--synthesis-file",str(synthesis_path),]), \- mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):+ mock.patch.dict(+ os.environ,+ {"LAST30DAYS_SKIP_PREFLIGHT": "1", "CLAUDECODE": "1"},+ clear=False,+ ):stdout = io.StringIO()stderr = io.StringIO()with redirect_stdout(stdout), redirect_stderr(stderr):rc = cli.main()self.assertEqual(0, rc)+ self.assertEqual(+ "plan_only", get_config.call_args.kwargs["policy"].browser_cookies+ )self.assertIn("Cached synthesis body.", stdout.getvalue())self.assertIn("Reusing cached report data", stderr.getvalue())diff --git a/tests/test_law7_host_plan_gate.py b/tests/test_law7_host_plan_gate.pynew file mode 100644index 00000000..798ed395--- /dev/null+++ b/tests/test_law7_host_plan_gate.py@@ -0,0 +1,389 @@+"""LAW 7 enforcement: an agent-hosted research run without --plan stops.++SKILL.md LAW 7 says the hosting reasoning model writes the query plan and+passes --plan. When the engine detects an agent host (Claude Code, Codex, or+an explicit LAST30DAYS_HOST_AGENT=1) and no plan was passed, it must stop+before retrieval with a clear message instead of silently spending on its+internal planner, unless the mode is exempt or LAST30DAYS_ALLOW_ENGINE_PLAN=1.+"""++from __future__ import annotations++import io+import json+import sys+from contextlib import redirect_stderr, redirect_stdout+from unittest import mock++import pytest++import last30days as cli+from lib import env, http, planner++DUMMY_CONFIG = {"OPENROUTER_API_KEY": "dummy-openrouter-key-000"}+DIAG = {+ "available_sources": ["reddit", "hackernews"],+ "providers": {"google": False, "openai": False, "xai": False},+ "x_backend": None,+ "bird_installed": False,+ "bird_authenticated": False,+ "bird_username": None,+ "native_web_backend": None,+ "permission_preflight": {},+}+TOPIC = ["best", "espresso", "grinders"]+VALID_PLAN = {+ "intent": "product",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "market",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "espresso grinder",+ "ranking_query": "Which espresso grinders do people recommend?",+ "sources": ["reddit", "hackernews"],+ "weight": 1.0,+ }+ ],+}+++class _RetrievalReached(Exception):+ """pipeline.run was entered: the gate let the run through."""+++def _parse(*argv: str):+ args, _extra = cli.build_parser().parse_known_args(list(argv))+ return args+++def _run_main(monkeypatch, argv, *, host_env=None, config=None):+ """Drive cli.main() up to retrieval with every side effect stubbed.++ Returns (rc, stderr, mocks). rc is None when pipeline.run was reached.+ """+ for name in ("LAST30DAYS_API_KEY", "LAST30DAYS_API_BASE", "LAST30DAYS_MEMORY_DIR"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ for name, value in (host_env or {}).items():+ monkeypatch.setenv(name, value)+ monkeypatch.setattr(sys, "argv", ["last30days.py", *argv])++ run_mock = mock.Mock(side_effect=_RetrievalReached)+ diagnose_mock = mock.Mock(return_value=dict(DIAG))+ runtime_mock = mock.Mock(side_effect=AssertionError("provider resolved"))+ resolve_mock = mock.Mock(return_value={})+ err = io.StringIO()+ with mock.patch.object(cli.env, "get_config", return_value=dict(config or DUMMY_CONFIG)), \+ mock.patch.object(cli.pipeline, "diagnose", diagnose_mock), \+ mock.patch.object(cli.pipeline, "run", run_mock), \+ mock.patch("lib.providers.resolve_runtime", runtime_mock), \+ mock.patch("lib.resolve.auto_resolve", resolve_mock), \+ mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock()), \+ redirect_stdout(io.StringIO()), redirect_stderr(err):+ try:+ rc = cli.main()+ except _RetrievalReached:+ rc = None+ return rc, err.getvalue(), {+ "diagnose": diagnose_mock, "run": run_mock,+ "runtime": runtime_mock, "resolve": resolve_mock,+ }+++# ---------------------------------------------------------------------------+# Host detection helpers (lib/env.py)+# ---------------------------------------------------------------------------++[email protected]("name", env.AGENT_HOST_ENV_VARS)+def test_each_runtime_marker_signals_an_agent_host(name):+ assert env.agent_host_signal({name: "1"}) == name+ assert env.agent_hosted_run({name: "anything"})+++def test_explicit_host_agent_opt_in_signals_an_agent_host():+ assert env.agent_host_signal({"LAST30DAYS_HOST_AGENT": "1"}) == "LAST30DAYS_HOST_AGENT"+ assert not env.agent_hosted_run({"LAST30DAYS_HOST_AGENT": "0"})+++def test_host_self_identification_signals_an_agent_host():+ assert env.agent_host_signal({"LAST30DAYS_HOST": "grok-bot"}) == "LAST30DAYS_HOST"+++def test_no_markers_or_blank_markers_are_not_agent_hosted():+ assert env.agent_host_signal({}) == ""+ assert not env.agent_hosted_run({"CLAUDECODE": "", "CODEX_THREAD_ID": " "})+++def test_signal_names_the_variable_never_its_value():+ assert env.agent_host_signal({"CODEX_THREAD_ID": "thread-secret-000"}) == "CODEX_THREAD_ID"++[email protected]("value,expected", [("1", True), ("true", True), ("on", True), ("0", False), ("", False)])+def test_engine_plan_override_is_truthy_only(value, expected):+ assert env.engine_plan_allowed({"LAST30DAYS_ALLOW_ENGINE_PLAN": value}) is expected+++def test_helpers_read_the_process_environment(monkeypatch):+ monkeypatch.setenv("CODEX_SANDBOX", "seatbelt")+ monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")+ assert env.agent_host_signal() == "CODEX_SANDBOX"+ assert env.engine_plan_allowed()+++# ---------------------------------------------------------------------------+# The gate on the research path+# ---------------------------------------------------------------------------++[email protected]("name", [*env.AGENT_HOST_ENV_VARS, "LAST30DAYS_HOST_AGENT"])+def test_agent_hosted_run_without_plan_stops_before_retrieval(monkeypatch, name):+ rc, stderr, mocks = _run_main(monkeypatch, TOPIC, host_env={name: "1"})++ assert rc == cli.LAW7_HOST_PLAN_EXIT != 0+ mocks["run"].assert_not_called()+ mocks["runtime"].assert_not_called() # internal LLM planner never resolved+ mocks["resolve"].assert_not_called()+ assert "LAW 7" in stderr+ assert f"({name} is set)" in stderr+ assert "Step 0.75" in stderr+ assert "references/research-runbook.md" in stderr+ assert '--plan "$QUERY_PLAN_FILE"' in stderr+ assert "<<'PLAN_EOF'" in stderr+ assert "LAST30DAYS_ALLOW_ENGINE_PLAN=1" in stderr+ assert "dummy-openrouter-key-000" not in stderr+++def test_entity_topic_stops_before_engine_auto_resolve(monkeypatch):+ # Entity-shaped topics switch on auto-resolve (a paid web search) when no+ # handle is given; the gate must come first.+ rc, _stderr, mocks = _run_main(+ monkeypatch, ["Peter", "Steinberger"], host_env={"CLAUDECODE": "1"}+ )+ assert rc == cli.LAW7_HOST_PLAN_EXIT+ mocks["resolve"].assert_not_called()+ mocks["run"].assert_not_called()+++def test_agent_hosted_run_without_plan_stops_before_live_diagnostics(monkeypatch):+ rc, _stderr, mocks = _run_main(+ monkeypatch, TOPIC, host_env={"CLAUDECODE": "1"}+ )+ assert rc == cli.LAW7_HOST_PLAN_EXIT+ mocks["diagnose"].assert_not_called()+++def test_agent_hosted_run_with_plan_reaches_retrieval(monkeypatch, tmp_path):+ plan_file = tmp_path / "plan.json"+ plan_file.write_text(json.dumps(VALID_PLAN), encoding="utf-8")+ rc, stderr, mocks = _run_main(+ monkeypatch, [*TOPIC, "--plan", str(plan_file)], host_env={"CLAUDECODE": "1"}+ )+ assert rc is None+ assert mocks["run"].call_args.kwargs["external_plan"] == VALID_PLAN+ assert "LAW 7" not in stderr+++def test_override_restores_engine_planning_under_an_agent(monkeypatch):+ rc, stderr, mocks = _run_main(+ monkeypatch,+ TOPIC,+ host_env={"CLAUDECODE": "1", "LAST30DAYS_ALLOW_ENGINE_PLAN": "1"},+ )+ assert rc is None+ assert mocks["run"].call_args.kwargs["external_plan"] is None+ assert "LAW 7" not in stderr+++def test_non_agent_run_is_unchanged(monkeypatch):+ rc, stderr, mocks = _run_main(monkeypatch, TOPIC)+ assert rc is None+ assert mocks["run"].call_args.kwargs["external_plan"] is None+ assert "LAW 7" not in stderr+++ "extra",+ [+ ["--mock"],+ ["--hiring-signals"],+ ["--auto-resolve"],+ ],+ ids=["mock", "hiring-signals", "auto-resolve"],+)+def test_exempt_research_modes_reach_retrieval_under_an_agent(monkeypatch, extra):+ rc, stderr, mocks = _run_main(monkeypatch, [*TOPIC, *extra], host_env={"CLAUDECODE": "1"})+ assert rc is None+ mocks["run"].assert_called_once()+ assert "LAW 7" not in stderr+++ "argv",+ [+ ["OpenAI", "vs", "Anthropic"],+ ["OpenAI", "--competitors"],+ ["OpenAI", "--competitors-list", "Anthropic,Google"],+ ["OpenAI", "--competitors-plan", '{"Anthropic": {"x_handle": "AnthropicAI"}}'],+ ],+ ids=["vs-topic", "competitors", "competitors-list", "competitors-plan"],+)+def test_comparison_runs_are_exempt(monkeypatch, argv):+ # Peers never take a query plan (SKILL.md vs-mode invokes without --plan).+ monkeypatch.setenv("CLAUDECODE", "1")+ args = _parse(*argv)+ topic = " ".join(args.topic).strip()+ assert cli._law7_host_plan_gate(args, topic) is None+++def test_gate_function_blocks_a_plain_topic(monkeypatch):+ monkeypatch.setenv("CODEX_THREAD_ID", "t")+ args = _parse(*TOPIC)+ err = io.StringIO()+ with redirect_stderr(err):+ assert cli._law7_host_plan_gate(args, " ".join(TOPIC)) == cli.LAW7_HOST_PLAN_EXIT+ assert "CODEX_THREAD_ID" in err.getvalue()+++# ---------------------------------------------------------------------------+# Modes that dispatch before the research path never see the gate+# ---------------------------------------------------------------------------+++ "argv,target",+ [+ (["doctor"], "lib.doctor.run"),+ (["setup", "--openclaw"], "lib.setup_wizard.run_openclaw_setup"),+ (["library", "search", "espresso"], "last30days._run_library_search"),+ (["library", "feed"], "last30days._run_library_feed"),+ (["queue", "list"], "last30days._run_queue_list"),+ (["--discover"], "last30days._run_discover"),+ (["--discover", "ai", "--discover-shallow"], "last30days._run_discover"),+ (["--discover", "--nominate-only"], "last30days._run_discover_protocol_leg"),+ (["--discover", "--finalize"], "last30days._run_discover_protocol_leg"),+ (["--drill", "3"], "last30days._run_drill"),+ (["--verify-freshness"], "last30days._run_cached_freshness"),+ ],+ ids=[+ "doctor", "setup", "library-search", "library-feed", "queue-list",+ "discover", "discover-shallow", "nominate-only", "finalize", "drill",+ "verify-freshness-cached",+ ],+)+def test_non_research_commands_are_not_gated(monkeypatch, argv, target):+ with mock.patch(target, return_value={} if "setup_wizard" in target else 0) as dispatched:+ rc, stderr, mocks = _run_main(monkeypatch, argv, host_env={"CLAUDECODE": "1"})+ assert rc == 0+ dispatched.assert_called_once()+ mocks["run"].assert_not_called()+ assert "LAW 7" not in stderr+++def test_diagnose_is_not_gated(monkeypatch):+ rc, stderr, mocks = _run_main(monkeypatch, [*TOPIC, "--diagnose"], host_env={"CLAUDECODE": "1"})+ assert rc == 0+ mocks["diagnose"].assert_called_once()+ assert mocks["diagnose"].call_args.kwargs["safe"] is True+ mocks["run"].assert_not_called()+ assert "LAW 7" not in stderr+++def test_preflight_is_not_gated(monkeypatch):+ with mock.patch.object(cli.permission_preflight, "render_text", return_value="ok\n"):+ rc, stderr, _mocks = _run_main(monkeypatch, ["--preflight"], host_env={"CLAUDECODE": "1"})+ assert rc == 0+ assert "LAW 7" not in stderr+++def test_hosted_api_path_is_not_gated(monkeypatch):+ # The remote API plans server-side and takes no --plan.+ monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example.test")+ monkeypatch.setattr(sys, "argv", ["last30days.py", *TOPIC])+ monkeypatch.setenv("CLAUDECODE", "1")+ err = io.StringIO()+ with mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.env, "read_secret_env", return_value="dummy-hosted-key-000"), \+ mock.patch("lib.hosted.run_hosted", return_value=0) as hosted, \+ redirect_stdout(io.StringIO()), redirect_stderr(err):+ rc = cli.main()+ assert rc == 0+ hosted.assert_called_once()+ assert "LAW 7" not in err.getvalue()+++# ---------------------------------------------------------------------------+# Unattended callers opt back into engine planning+# ---------------------------------------------------------------------------+++def test_watchlist_subprocess_allows_engine_planning(monkeypatch):+ import watchlist++ monkeypatch.setenv("CLAUDECODE", "1")+ fake = mock.Mock(returncode=1, stdout="", stderr="boom")+ with mock.patch.object(watchlist, "store") as store, \+ mock.patch.object(watchlist.subprocess, "run", return_value=fake) as run:+ store.record_run.return_value = 1+ watchlist._run_topic({"id": 1, "name": "test topic", "search_queries": None})+ child_env = run.call_args.kwargs["env"]+ assert child_env["LAST30DAYS_ALLOW_ENGINE_PLAN"] == "1"+ assert child_env["CLAUDECODE"] == "1" # rest of the environment passes through+++# ---------------------------------------------------------------------------+# Non-agent path: a failed internal planner still prints the LAW 7 reminder+# ---------------------------------------------------------------------------+++def _plan_with_failing_provider(*, internal_subrun: bool) -> tuple:+ provider = mock.Mock()+ provider.generate_json.side_effect = http.HTTPError(+ "HTTP 402: insufficient credits", status_code=402+ )+ err = io.StringIO()+ with redirect_stderr(err):+ plan = planner.plan_query(+ topic="best espresso grinders",+ available_sources=["reddit", "hackernews"],+ requested_sources=None,+ depth="default",+ provider=provider,+ model="dummy-model",+ internal_subrun=internal_subrun,+ )+ return plan, err.getvalue()+++def test_provider_failure_prints_law7_reminder():+ plan, stderr = _plan_with_failing_provider(internal_subrun=False)+ assert "LLM planning failed" in stderr+ assert "No --plan passed" in stderr+ assert "YOU ARE the planner" in stderr+ assert plan.subqueries+ assert any("fallback-plan" in note for note in plan.notes)+++def test_provider_failure_in_internal_subrun_stays_quiet():+ plan, stderr = _plan_with_failing_provider(internal_subrun=True)+ assert "LLM planning failed" in stderr+ assert "No --plan passed" not in stderr+ assert plan.subqueries+++def test_successful_provider_plan_prints_no_reminder():+ provider = mock.Mock()+ provider.generate_json.return_value = VALID_PLAN+ err = io.StringIO()+ with redirect_stderr(err):+ plan = planner.plan_query(+ topic="best espresso grinders",+ available_sources=["reddit", "hackernews"],+ requested_sources=None,+ depth="default",+ provider=provider,+ model="dummy-model",+ )+ assert plan.subqueries+ assert "No --plan passed" not in err.getvalue()diff --git a/tests/test_planner_v3.py b/tests/test_planner_v3.pyindex fd3902d7..838bda22 100644--- a/tests/test_planner_v3.py+++ b/tests/test_planner_v3.py@@ -615,11 +615,12 @@ class FallbackDefaultsTests(unittest.TestCase):# The old misleading phrasing must NOT appear.self.assertNotIn("No --plan and no LLM provider configured", output)- def test_fallback_does_not_log_new_warning_when_provider_present(self):+ def test_provider_failure_logs_error_and_law7_reminder(self):# When a provider is configured, the provider path runs; if it- # errors, we get the "LLM planning failed" message, NOT the- # "No --plan passed" guidance (which is specifically for the- # no-provider-no-plan caller path).+ # errors, we get the "LLM planning failed" message AND the+ # "No --plan passed" guidance: a failed internal planner degrades+ # the run exactly like having none, and the host may not be+ # detectable (see test_law7_host_plan_gate.py).import ioimport contextlibbuf = io.StringIO()@@ -639,7 +640,7 @@ class FallbackDefaultsTests(unittest.TestCase):)output = buf.getvalue()self.assertIn("LLM planning failed", output)- self.assertNotIn("No --plan passed", output)+ self.assertIn("No --plan passed", output)if __name__ == "__main__":unittest.main()diff --git a/tests/test_verify_v3.py b/tests/test_verify_v3.pyindex 4a992f75..f25b483d 100644--- a/tests/test_verify_v3.py+++ b/tests/test_verify_v3.py@@ -38,6 +38,7 @@ class VerifyV3Tests(unittest.TestCase):self.assertEqual(commands[0], [module.PYTHON, str(module.ENGINE), module.SMOKE_TOPIC, "--emit=json", "--json-profile=raw", "--quick"])self.assertEqual(commands[1], [module.PYTHON, str(module.ENGINE), "topic", "--emit=json", "--json-profile=raw", "--quick"])self.assertEqual(run.call_args_list[0].kwargs["env"]["LAST30DAYS_REASONING_PROVIDER"], "auto")+ self.assertEqual(run.call_args_list[1].kwargs["env"]["LAST30DAYS_ALLOW_ENGINE_PLAN"], "1")self.assertEqual(len(smoke), 1)self.assertEqual({key: value for key, value in smoke[0].items() if key != "duration_seconds"}, {"provider": "auto", "reasoning_provider": "fixture", "cluster_count": 1,