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: resolve 20 repository review findings (#1326)
Ilia Alshanetskyf3cd06a620e3
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex bc8a6c11..bef3f731 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -46,6 +46,8 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--save-dir <path>` - one-off output location. **Flag wins over env var.** If neither flag nor env var is set, the engine does not write a file (DB persistence is independent — see `LAST30DAYS_STORE` below).- `--resolve-save-dir` - print the absolute save directory selected for the skill and exit without research, browser-cookie reads, credential-store lookups, or file writes. It honors `--save-dir`, process environment, and trusted config files, preserving empty values. For memory directories, whole unresolved host placeholders such as `${user_config.memory_dir}` are absent at each configuration layer: a process placeholder falls back to trusted project then global configuration, and a project placeholder preserves the global value, including an empty value that disables saving. The bare engine uses the same placeholder precedence. Explicit `--save-dir` values remain literal paths. Only this query supplies the skill's `~/Documents/Last30Days` fallback; it does not change the bare research engine's no-save default. Shell wrappers capture this output without sourcing `.env` files.- `--output <file>` - write the rendered output to an exact file path, using the format selected by `--emit`.+- `--research-only` - treat the positional topic as research text, including reserved names such as `setup`, `doctor`, `library`, and `queue`. Programmatic wrappers such as MCP use this flag to prevent topics from invoking administrative commands. Omit it when you intend to run an administrative command.+- `--cached-report` - render a saved research result with `--emit=html --synthesis-file <file>` without repeating retrieval or reopening temporary research plans. The topic and any explicit research flags must match the cached report. Omitted research flags use the saved provenance. If no compatible cache exists, the command fails so you can run research again explicitly.- `--json-profile {agent,raw}` - select the research JSON shape used with `--emit=json`. `agent` is the default, versioned workflow contract; `raw` preserves the full internal `Report` dump for debugging and power users. See the [JSON export reference](docs/reference/json-export.md).- `--corpus <dir>` - add a local `.md`/`.txt` directory as a private ranked source; repeat the flag for multiple directories. PDFs are extracted only when `pdftotext` is on PATH and otherwise skip with a note. File modification time supplies recency, so the normal research window applies.- `--corpus-all-time` - include relevant registered files whose modification time is older than the current research window. Without this flag, a 30-day run includes only files modified in those 30 days.@@ -470,9 +472,11 @@ An explicit `--register` wins over `LAST30DAYS_REGISTER`; the environment/config1. **Gemini** - `GOOGLE_API_KEY` / `GEMINI_API_KEY` / `GOOGLE_GENAI_API_KEY`2. **OpenAI** - `OPENAI_API_KEY` only. Codex ChatGPT auth at `~/.codex/auth.json` is intentionally not used as an OpenAI provider credential.3. **xAI** - `XAI_API_KEY`-4. **OpenRouter** - `OPENROUTER_API_KEY` (reasoning provider, auto-resolve, and synchronous Sonar fallback for the Perplexity source)+4. **OpenRouter** - `OPENROUTER_API_KEY` (reasoning provider and synchronous Sonar fallback for the Perplexity source)5. **Local / deterministic** - always available, lowest quality+Entity and competitor auto-resolution requires a configured Brave, Exa, Serper, or Parallel search backend. OpenRouter and Perplexity credentials alone do not enable auto-resolution. Their Perplexity-source search routes retain their explicit opt-in behavior.+When 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). If one of them is configured anyway, for example `XAI_API_KEY` kept for X search or `OPENROUTER_API_KEY` kept for Perplexity, the engine still sends the topic and the shortlisted titles, snippets, and comments to that provider for reranking and fun scoring, even when you pass `--plan`. To keep that step local, leave all four key families out of every config layer (environment, `.env`, Keychain, `pass`). Local corpus evidence is always scored locally.### Agent-hosted runs must pass `--plan`diff --git a/changelog.d/+review-boundaries.security.md b/changelog.d/+review-boundaries.security.mdnew file mode 100644index 00000000..13c72040--- /dev/null+++ b/changelog.d/+review-boundaries.security.md@@ -0,0 +1 @@+Fixed MCP research dispatch so reserved topic names cannot invoke administrative commands. Protected existing password-store credentials when decryption fails, and sanitized Digg-attached X quotes so external content cannot forge the engine's evidence boundaries.diff --git a/changelog.d/+review-research.fixed.md b/changelog.d/+review-research.fixed.mdnew file mode 100644index 00000000..adcd2e3e--- /dev/null+++ b/changelog.d/+review-research.fixed.md@@ -0,0 +1,5 @@+Fixed cached HTML exports to respect research scope and support comparison exports after temporary plans are removed. Aligned MCP save destinations with preflight and trusted configuration, isolated comparison peers' dedicated subreddits, and honored jobs exclusions throughout source selection.++Kept rejected Polymarket markets out of ranking, restored enrichment-based entity grounding, selected the newest relevant freshness assertion, included the final requested day in Grok and Xquik searches, and restored Reddit fallback when ScrapeCreators results are all outside the requested window. Corrected non-Latin web-backend guidance and autoresolve backend availability.++Fixed signup credential persistence over empty configuration assignments, browser cookie snapshots with committed SQLite WAL changes, multipart Trustpilot hostnames, and Startpage snippet association. Preserved maximum observed engagement during concurrent updates.diff --git a/mcp/README.md b/mcp/README.mdindex 603a059c..8b4da3a8 100644--- a/mcp/README.md+++ b/mcp/README.md@@ -33,6 +33,8 @@ End users need Python 3.12+. The bundle ships the engine source but relies on thMCP research denies browser-cookie access by default by passing `--no-browser-cookies`. Set `LAST30DAYS_MCP_ALLOW_BROWSER_COOKIES` to `1`, `true`, `yes`, or `on` (case-insensitive) to remove that MCP-layer denial. Empty, false, unset, and unrecognized values keep the denial in place. Enabling this variable does not create consent: browser-cookie use still requires the engine's separately recorded consent and configuration.+The research tool passes `--research-only`, so topics such as `setup` remain research queries and cannot invoke administrative commands. Preflight and research resolve save destinations through the engine's `--resolve-save-dir` query, including trusted `.env` configuration. Set `save=false` to suppress research file saves.+## VersioningThe MCPB `manifest.json` version is hand-bumped in the same PR that ships engine changes worth releasing. Release CI stamps the Go binary's `main.Version` from the tag.diff --git a/mcp/internal/tools/preflight.go b/mcp/internal/tools/preflight.goindex 123dc941..fd9603c1 100644--- a/mcp/internal/tools/preflight.go+++ b/mcp/internal/tools/preflight.go@@ -46,9 +46,13 @@ func makePreflightHandler(cfg Config) server.ToolHandlerFunc {)), nil}+ saveDir, err := resolveSaveDir(ctx, cacheDir)+ if err != nil {+ return mcplib.NewToolResultError(err.Error()), nil+ }res, runErr := engine.Run(ctx, engine.RunOptions{CacheDir: cacheDir,- Args: preflightRunArgs(format),+ Args: preflightRunArgs(format, saveDir),})if runErr != nil {return mcplib.NewToolResultError(formatRunError(runErr, res)), nil@@ -57,8 +61,8 @@ func makePreflightHandler(cfg Config) server.ToolHandlerFunc {}}-func preflightRunArgs(format string) []string {- runArgs := []string{"--preflight", "--preflight-report-on-save-dir", mcpSaveDir()}+func preflightRunArgs(format, saveDir string) []string {+ runArgs := []string{"--preflight", "--save-dir", "", "--preflight-report-on-save-dir", saveDir}if format == "json" {runArgs = append(runArgs, "--emit=json")}diff --git a/mcp/internal/tools/preflight_test.go b/mcp/internal/tools/preflight_test.goindex 31e0f333..4495c376 100644--- a/mcp/internal/tools/preflight_test.go+++ b/mcp/internal/tools/preflight_test.go@@ -7,9 +7,10 @@ import (func TestPreflightRunArgsDefaultTextIsSafe(t *testing.T) {t.Setenv("LAST30DAYS_MEMORY_DIR", "")- args := preflightRunArgs("text")+ args := preflightRunArgs("text", "~/Documents/Last30Days")want := []string{"--preflight",+ "--save-dir", "","--preflight-report-on-save-dir","~/Documents/Last30Days",}@@ -20,9 +21,10 @@ func TestPreflightRunArgsDefaultTextIsSafe(t *testing.T) {func TestPreflightRunArgsJSONIsSafeAndStructured(t *testing.T) {t.Setenv("LAST30DAYS_MEMORY_DIR", "/tmp/last30days-reports")- args := preflightRunArgs("json")+ args := preflightRunArgs("json", "/tmp/last30days-reports")want := []string{"--preflight",+ "--save-dir", "","--preflight-report-on-save-dir","/tmp/last30days-reports","--emit=json",diff --git a/mcp/internal/tools/research.go b/mcp/internal/tools/research.goindex 2d47349d..73fdcf62 100644--- a/mcp/internal/tools/research.go+++ b/mcp/internal/tools/research.go@@ -84,7 +84,14 @@ func makeResearchHandler(cfg Config) server.ToolHandlerFunc {)), nil}- runArgs := researchRunArgs(topic, emit, save)+ saveDir := ""+ if save {+ saveDir, err = resolveSaveDir(ctx, cacheDir)+ if err != nil {+ return mcplib.NewToolResultError(err.Error()), nil+ }+ }+ runArgs := researchRunArgs(topic, emit, saveDir)res, runErr := engine.Run(ctx, engine.RunOptions{CacheDir: cacheDir,@@ -98,21 +105,17 @@ func makeResearchHandler(cfg Config) server.ToolHandlerFunc {}}-func researchRunArgs(topic, emit string, save bool) []string {+func researchRunArgs(topic, emit, saveDir string) []string {// Options first, positional topic last behind a `--` separator: a// dash-prefixed topic must never be parsed as engine flags.- runArgs := []string{"--emit=" + emit}+ runArgs := []string{"--research-only", "--emit=" + emit}if !browserCookiesAllowed() {runArgs = append(runArgs, "--no-browser-cookies")}// Always pass --save-dir explicitly. An empty value skips the engine's// `is None` LAST30DAYS_MEMORY_DIR fallback and is falsy at the save// gate, so declining to save writes nothing even when the env var set.- if save {- runArgs = append(runArgs, "--save-dir", mcpSaveDir())- } else {- runArgs = append(runArgs, "--save-dir", "")- }+ runArgs = append(runArgs, "--save-dir", saveDir)return append(runArgs, "--", topic)}@@ -128,12 +131,15 @@ func browserCookiesAllowed() bool {strings.EqualFold(raw, "on")}-func mcpSaveDir() string {- saveDir := os.Getenv("LAST30DAYS_MEMORY_DIR")- if saveDir == "" {- return "~/Documents/Last30Days"+func resolveSaveDir(ctx context.Context, cacheDir string) (string, error) {+ res, err := engine.Run(ctx, engine.RunOptions{+ CacheDir: cacheDir,+ Args: []string{"--resolve-save-dir"},+ })+ if err != nil {+ return "", fmt.Errorf("save directory resolution failed: %s", formatRunError(err, res))}- return saveDir+ return strings.TrimSuffix(strings.TrimSuffix(string(res.Stdout), "\n"), "\r"), nil}func requireString(args map[string]any, name string) (string, error) {diff --git a/mcp/internal/tools/research_test.go b/mcp/internal/tools/research_test.goindex 7b33f4d1..79944940 100644--- a/mcp/internal/tools/research_test.go+++ b/mcp/internal/tools/research_test.go@@ -4,6 +4,7 @@ import ("context""errors""os"+ "path/filepath""strings""testing"@@ -103,8 +104,8 @@ func TestResearchRunArgsIncludesNoBrowserCookies(t *testing.T) {if err := os.Unsetenv(BrowserCookiesEnvOverride); err != nil {t.Fatalf("unset %s: %v", BrowserCookiesEnvOverride, err)}- args := researchRunArgs("OpenAI", "compact", false)- want := []string{"--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "OpenAI"}+ args := researchRunArgs("OpenAI", "compact", "")+ want := []string{"--research-only", "--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "OpenAI"}if strings.Join(args, "\x00") != strings.Join(want, "\x00") {t.Fatalf("args = %#v, want %#v", args, want)}@@ -114,8 +115,8 @@ func TestResearchRunArgsAllowsBrowserCookiesForTruthyOptIn(t *testing.T) {for _, value := range []string{"1", "true", "TRUE", "yes", "YeS", "on", "ON"} {t.Run(value, func(t *testing.T) {t.Setenv(BrowserCookiesEnvOverride, value)- args := researchRunArgs("OpenAI", "compact", false)- want := []string{"--emit=compact", "--save-dir", "", "--", "OpenAI"}+ args := researchRunArgs("OpenAI", "compact", "")+ want := []string{"--research-only", "--emit=compact", "--save-dir", "", "--", "OpenAI"}if strings.Join(args, "\x00") != strings.Join(want, "\x00") {t.Fatalf("%s=%q: args = %#v, want %#v", BrowserCookiesEnvOverride, value, args, want)}@@ -131,8 +132,8 @@ func TestResearchRunArgsDeniesBrowserCookiesForFalseAndUnrecognizedValues(t *tes}t.Run(name, func(t *testing.T) {t.Setenv(BrowserCookiesEnvOverride, value)- args := researchRunArgs("OpenAI", "compact", false)- want := []string{"--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "OpenAI"}+ args := researchRunArgs("OpenAI", "compact", "")+ want := []string{"--research-only", "--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "OpenAI"}if strings.Join(args, "\x00") != strings.Join(want, "\x00") {t.Fatalf("%s=%q: args = %#v, want %#v", BrowserCookiesEnvOverride, value, args, want)}@@ -143,22 +144,22 @@ func TestResearchRunArgsDeniesBrowserCookiesForFalseAndUnrecognizedValues(t *tesfunc TestResearchRunArgsSaveUsesSupportedSaveDir(t *testing.T) {t.Setenv(BrowserCookiesEnvOverride, "")t.Setenv("LAST30DAYS_MEMORY_DIR", "")- args := researchRunArgs("OpenAI", "html", true)+ args := researchRunArgs("OpenAI", "html", "~/Documents/Last30Days")got := strings.Join(args, "\x00")if strings.Contains(got, "--save\x00") || strings.HasSuffix(got, "--save") {t.Fatalf("args still include unsupported --save: %#v", args)}- want := []string{"--emit=html", "--no-browser-cookies", "--save-dir", "~/Documents/Last30Days", "--", "OpenAI"}+ want := []string{"--research-only", "--emit=html", "--no-browser-cookies", "--save-dir", "~/Documents/Last30Days", "--", "OpenAI"}if got != strings.Join(want, "\x00") {t.Fatalf("args = %#v, want %#v", args, want)}}-func TestResearchRunArgsSaveUsesMemoryDirEnvOverride(t *testing.T) {+func TestResearchRunArgsSaveUsesResolvedDirectory(t *testing.T) {t.Setenv(BrowserCookiesEnvOverride, "")t.Setenv("LAST30DAYS_MEMORY_DIR", "/tmp/last30days-reports")- args := researchRunArgs("OpenAI", "html", true)- want := []string{"--emit=html", "--no-browser-cookies", "--save-dir", "/tmp/last30days-reports", "--", "OpenAI"}+ args := researchRunArgs("OpenAI", "html", "/tmp/last30days-reports")+ want := []string{"--research-only", "--emit=html", "--no-browser-cookies", "--save-dir", "/tmp/last30days-reports", "--", "OpenAI"}if strings.Join(args, "\x00") != strings.Join(want, "\x00") {t.Fatalf("args = %#v, want %#v", args, want)}@@ -170,8 +171,8 @@ func TestResearchRunArgsSaveUsesMemoryDirEnvOverride(t *testing.T) {func TestResearchRunArgsSeparatesTopicWithDoubleDash(t *testing.T) {t.Setenv(BrowserCookiesEnvOverride, "")t.Setenv("LAST30DAYS_MEMORY_DIR", "")- args := researchRunArgs("--mock", "compact", false)- want := []string{"--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "--mock"}+ args := researchRunArgs("--mock", "compact", "")+ want := []string{"--research-only", "--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "--mock"}if strings.Join(args, "\x00") != strings.Join(want, "\x00") {t.Fatalf("args = %#v, want %#v", args, want)}@@ -199,8 +200,8 @@ func TestResearchRunArgsSeparatesTopicWithDoubleDash(t *testing.T) {func TestResearchRunArgsSaveFalsePassesExplicitEmptySaveDir(t *testing.T) {t.Setenv(BrowserCookiesEnvOverride, "")t.Setenv("LAST30DAYS_MEMORY_DIR", "/tmp/last30days-reports")- args := researchRunArgs("OpenAI", "compact", false)- want := []string{"--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "OpenAI"}+ args := researchRunArgs("OpenAI", "compact", "")+ want := []string{"--research-only", "--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "OpenAI"}if strings.Join(args, "\x00") != strings.Join(want, "\x00") {t.Fatalf("args = %#v, want %#v", args, want)}@@ -259,3 +260,54 @@ func TestResearchExtraEnvAllowsEnginePlanning(t *testing.T) {t.Fatalf("researchExtraEnv() = %#v, want [LAST30DAYS_ALLOW_ENGINE_PLAN=1]", got)}}++func TestResolveSaveDirUsesEngineConfiguration(t *testing.T) {+ cacheDir, err := filepath.Abs("../../../skills/last30days/scripts")+ if err != nil {+ t.Fatal(err)+ }+ home := t.TempDir()+ configDir := filepath.Join(home, "config")+ if err := os.Mkdir(configDir, 0700); err != nil {+ t.Fatal(err)+ }+ configured := filepath.Join(home, "client-reports")+ if err := os.WriteFile(filepath.Join(configDir, ".env"), []byte("LAST30DAYS_MEMORY_DIR="+configured+"\n"), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("LAST30DAYS_CONFIG_DIR", configDir)+ t.Setenv("LAST30DAYS_SKIP_KEYCHAIN", "1")+ t.Setenv(BrowserCookiesEnvOverride, "")+ t.Setenv("LAST30DAYS_MEMORY_DIR", "")+ if err := os.Unsetenv("LAST30DAYS_MEMORY_DIR"); err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ name string+ env *string+ want string+ }{+ {name: "dotenv", want: configured},+ {name: "shell override", env: stringPointer(filepath.Join(home, "override")), want: filepath.Join(home, "override")},+ {name: "explicit empty disables save", env: stringPointer(""), want: ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if tc.env != nil {+ t.Setenv("LAST30DAYS_MEMORY_DIR", *tc.env)+ }+ got, err := resolveSaveDir(context.Background(), cacheDir)+ if err != nil || got != tc.want {+ t.Fatalf("resolveSaveDir() = %q, %v; want %q", got, err, tc.want)+ }+ preflight := preflightRunArgs("json", got)+ research := researchRunArgs("setup", "compact", got)+ if preflight[4] != research[4] {+ t.Fatalf("preflight/research destinations differ: %q, %q", preflight, research)+ }+ })+ }+}++func stringPointer(value string) *string { return &value }diff --git a/skills/last30days/references/comparison.md b/skills/last30days/references/comparison.mdindex 262f0237..dad4b282 100644--- a/skills/last30days/references/comparison.md+++ b/skills/last30days/references/comparison.md@@ -82,6 +82,8 @@ PLAN_EOFFor any additional outer targeting flag, capture its value through a quoted heredoc and add it to `MAIN_TARGETING` with a quoted variable expansion. Omit unresolved flags. Never paste a topic, handle, subreddit, or fetched context directly into shell command words. The quoted heredocs keep shell-active text literal; `json.tool` rejects malformed peer JSON before the research run.+The cleanup trap removes both plan files after research. For a later HTML export, follow `save-html-brief.md` with `--cached-report` and the original topic. Do not replay the removed plan paths. The cache preserves every entity's report and targeting; if the cache expires, recreate the plans before running research again.+### Without host web searchOn a Grok Bot with the official X connector, follow `grok-bot-x.md` to fetch and write one envelope per entity before this command. Replace `COMPETITORS_PLAN_JSON` with JSON keyed by every entity name, including the main one, containing each envelope's absolute path as `x_posts`. When an envelope has `from` or `mention` calls, its plan entry must also contain the matching `x_handle`; when it has `related` calls, include their handles as an `x_related` array. For example, `{"Main Brand":{"x_posts":"/tmp/main.json","x_handle":"mainbrand"},"Peer Brand":{"x_posts":"/tmp/peer.json","x_handle":"peerbrand"}}`. Set `TOPIC_A_HANDLE` below to the main entity's matching handle and `TOPIC_A_RELATED` to its comma-separated related handles, or leave them empty when no handles are known. The main plan entry validates its envelope, while the outer flags target its pipeline run. With no known handle, fetch only a topic call and omit handle fields. Run the command in the same shell as the envelope setup so its parent cleanup trap remains active. Other hosts use this command without a competitors plan.diff --git a/skills/last30days/references/competitors.md b/skills/last30days/references/competitors.mdindex cd8529a8..d8b05ecc 100644--- a/skills/last30days/references/competitors.md+++ b/skills/last30days/references/competitors.md@@ -24,6 +24,8 @@ Read when competitor mode is selected. The root also requires `comparison.md`; r**Why --competitors-plan over --competitors-list on web-search hosts:** without per-entity handles/subs, peer sub-runs can produce visibly thinner evidence than the main topic. The Resolved Entities block in stdout makes the gap visible. Dashes on a host with web search mean Step 0.55 needs another pass; dashes on a host without it may mean no resolver was configured.-**Engine-internal auto-resolve:** if the engine detects BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / PARALLEL_API_KEY / PERPLEXITY_API_KEY / OPENROUTER_API_KEY, it runs its own per-entity `resolve.auto_resolve()` before each sub-run. A hosting model with web search does not need those keys for its own Step 0.55; hosts without web search and headless cron/CI runs use this engine fallback.+**Engine-internal auto-resolve:** if the engine detects BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / PARALLEL_API_KEY, it runs its own per-entity `resolve.auto_resolve()` before each sub-run. A hosting model with web search does not need those keys for its own Step 0.55; hosts without web search and headless cron/CI runs use this engine fallback.++OpenRouter and Perplexity credentials do not enable engine auto-resolve or peer discovery. Their paid Perplexity source remains a separate opt-in. Without a supported search API key, use host web search or supply named peers; the engine's keyless general-web floor does not enable automatic peer discovery.**Output:** for Markdown/compact runs, one `{slug}-raw.md` per entity in `--save-dir` plus the merged comparison on stdout. For HTML runs, the main saved artifact is merged comparison HTML and peer artifacts remain per-entity. Always use the `[last30days] Comparison artifact set: main=...; peers=...` log line as the source of truth. Synthesis contract identical to the vs-mode protocol in `comparison.md`.diff --git a/skills/last30days/references/research-runbook.md b/skills/last30days/references/research-runbook.mdindex 85b88328..b7584f0c 100644--- a/skills/last30days/references/research-runbook.md+++ b/skills/last30days/references/research-runbook.md@@ -114,14 +114,13 @@ Known keyword-trap classes and how to handle each:> "{TOPIC} is a huge category - are you asking about {specific-facet-A}, {specific-facet-B}, or {specific-facet-C}? Each is a different community. Pick one or tell me the angle."**Class 5: Non-English / non-Latin-script topic (Hebrew, Arabic, Chinese, Japanese, etc.)**-- Pattern: topic contains non-Latin characters (Hebrew [\u0590-\u05FF], Arabic [\u0600-\u06FF], CJK [\u4E00-\u9FFF], etc.).-- Why it fails without intervention: Reddit, HackerNews, GitHub, and Polymarket are English-dominant platforms. A Hebrew brand like "קפה עלית" scores zero entity-matches across all four sources and returns only English-language noise as fallback padding.-- Action: **Mandatory pre-flight steps for non-English topics:**- 1. **Force `--web-backend brave`** in the engine command. Brave indexes non-English web (Ynet/Walla/Mako for Hebrew; Haber7/Hurriyet for Turkish; etc.) and is the only available source with real-language coverage.- 2. **Skip `--subreddits` targeting unless the topic has a known English-speaking community.** Generic subreddits (r/food, r/Israel) return English noise; omit them or scope tightly to known bilingual communities.- 3. **Note in the Resolved block:** "Non-English topic detected ([language]). Routing to `--web-backend brave`; Reddit/HN/GitHub will likely return zero on-topic results."- 4. **X/Twitter and YouTube are the highest-value missing sources for non-English topics.** Surface this clearly in the output so the user knows what would unlock deeper coverage.-- Do NOT skip this class check for mixed-script queries (e.g. "קפה עלית Elite Coffee") - if any non-Latin characters are present, Class 5 applies.+- Pattern: Any non-Latin character, including mixed-script queries.+- Risk: English-dominant Reddit, Hacker News, GitHub, and Polymarket may miss entity matches.+- Required steps:+ 1. **Leave `--web-backend` unset unless the user requested a backend.** Configured API priority: Brave, Exa, Serper, Parallel. Without a search API key, use the host's native web search when available; otherwise retain the engine's keyless floor. Never force `--web-backend brave` for non-Latin text; explicit Brave requires a resolved `BRAVE_API_KEY`.+ 2. Skip `--subreddits` unless a known English-speaking or bilingual community covers the topic. Avoid generic communities.+ 3. In Resolved, state the language, web search in that language, and possible English-source coverage gaps. Name a backend only if the engine or host reports it available.+ 4. Flag missing X/Twitter and YouTube as the highest-value sources for deeper coverage.**Pre-Flight decision flow (do this BEFORE any WebSearch):**1. Read the topic. Match against Classes 1-5 above.@@ -171,7 +170,7 @@ Before running the engine, determine every applicable targeting flag and resolve| `--devto-tags={t1,t2}` | Step 0.55 | Tech topics: 1-3 lowercase tags (`claudecode,ai`); enables dev.to || `--tiktok-creators={c1,c2,...}` | Step 0.55 | Creator / influencer / brand topics || `--ig-creators={c1,c2,...}` | Step 0.55 | Creator / brand topics |-| `--web-backend brave` | Step 0.45 Class 5 | **MANDATORY** for non-Latin-script topics (Hebrew, Arabic, CJK, etc.) — Brave is the only source that indexes non-English web |+| `--web-backend {backend}` | Explicit user request | Otherwise use automatic selection, including non-Latin topics. API backends require their resolved credential. || `--web-backend parallel-mcp` | Explicit user request only | Use only when the user asks to use Parallel Search MCP. This opts the run into sending its search objective and queries to `https://search.parallel.ai/mcp`; never select it automatically. Anonymous use sends no authorization header; an existing `PARALLEL_API_KEY` is sent as Bearer auth. || `--auto-resolve` | Fallback | WebSearch is available but Step 0.55 could not resolve everything cleanly — use as belt-and-suspenders |@@ -572,6 +571,8 @@ Store your plan as `QUERY_PLAN_JSON` - you'll pass it to the script in the nextFill `{TOPIC}` below with the parsed topic as literal data, excluding skill-mode controls and engine CLI flags. Choose a quoted heredoc delimiter that does not occur as a line in the topic. Map recognized CLI flags separately to the engine command. Never evaluate raw slash-command text or depend on a shell `$ARGUMENTS` variable.+For research topics matching administrative commands (for example `setup`), add `--research-only` to treat the topic as text. Omit it for explicitly requested administrative actions and follow their runtime flow.+```bash# SKILL_DIR is already bound to the directory containing the loaded root SKILL.md.# Never rebind it to this reference directory or search other installations.diff --git a/skills/last30days/references/save-html-brief.md b/skills/last30days/references/save-html-brief.mdindex 53dfa3ee..0badfe6d 100644--- a/skills/last30days/references/save-html-brief.md+++ b/skills/last30days/references/save-html-brief.md@@ -47,16 +47,17 @@ KEY PATTERNS from the research:SYNTHESIS_EOF# 2. Convert the synthesis to a self-contained HTML file via the engine.-# REPLAY THE SAME SCOPE FLAGS as your original run (--plan, --hiring-signals,-# resolved --x-handle/--subreddits/etc). On a same-topic follow-up, the-# engine reuses the structured last-report cache at+# Use --cached-report with the same topic as your original run. The engine+# reuses the original scope and per-entity reports in the structured cache at# ~/.config/last30days/last-report.json to build badge metadata and footer# without re-running source fetchers. That cache is intentionally short-lived# (default: one hour; tune with LAST30DAYS_REPORT_CACHE_TTL_SECONDS, or set-# it to 0 to disable reuse). If the cache is stale, missing, or for a-# different topic, stderr says "No matching cached report data" and the-# engine falls back to a fresh run; the same scope flags keep that fallback-# aligned with the synthesis body.+# it to 0 to disable reuse). Do not replay --plan, --competitors-plan, or+# --x-posts: their temporary files can already be removed. If the cache is+# stale, missing, or for a different topic, stderr says+# "No matching cached report data" and the command exits without research. Recreate the original+# research plans, rerun research with the original scope, and update the+# synthesis before retrying this export.SLUG=$(printf '%s\n' "${TOPIC}" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//')# Render beside the destination, then create a new name atomically. The hard# link refuses existing paths even when another exporter wins the same name.@@ -65,8 +66,8 @@ HTML_PATH=$(trap 'rm -f -- "${HTML_TMP}"' EXIT"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" "${TOPIC}" \--emit=html \+ --cached-report \--synthesis-file "${SYNTHESIS_FILE}" \- "${SCOPE_FLAGS[@]}" \>| "${HTML_TMP}" || exit "$?""${LAST30DAYS_PYTHON}" - "${HTML_TMP}" "${LAST30DAYS_MEMORY_DIR}" "${SLUG}" << 'HTML_PATH_PY'from datetime import date@@ -90,10 +91,7 @@ while True:breakHTML_PATH_PY) || exit "$?"-# where SCOPE_FLAGS is the same array you passed the first time, e.g.-# SCOPE_FLAGS=(--hiring-signals --plan "$QUERY_PLAN_FILE" --x-handle=acme).-# For a scoped --hiring-signals brief, --hiring-signals MUST be here too so-# the footer reflects the jobs-scoped board, not a generic crawl.+# The cached report preserves hiring scope and comparison targeting.# 3. Finish with the artifact handoff described below. Do not print the saved# path from the shell block; the chat handoff is the single user-visible@@ -131,10 +129,10 @@ When the user chooses the built-in `ht-ml.app` path, add `--publish-html` to theLAST30DAYS_PUBLISH_PASSWORD="${PUBLISH_PASSWORD:-}" \"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" "${TOPIC}" \--emit=html \+ --cached-report \--synthesis-file "$SYNTHESIS_FILE" \--output "$HTML_PATH" \--publish-html \- "${SCOPE_FLAGS[@]}" \>/dev/null```@@ -193,15 +191,15 @@ The renderer strips engine-internal noise that doesn't belong in a shareable art## Comparison mode-Same flow when the topic is `X vs Y` (or `X vs Y vs Z`). The engine routes through `render_for_html_comparison` internally; you don't need to do anything special. The synthesis temp file should still contain the comparison-shaped synthesis you wrote in chat (`## Quick Verdict`, `## {Entity}` per entity, `## Head-to-Head` table, `## The Bottom Line`, `## The emerging stack` per LAW 4 comparison exception).+Same flow when the topic is `X vs Y` (or `X vs Y vs Z`). Use `--cached-report` without the deleted `--competitors-plan` and `--plan` files. The engine routes the stored entity reports through `render_for_html_comparison`. The synthesis temp file should still contain the comparison-shaped synthesis you wrote in chat (`## Quick Verdict`, `## {Entity}` per entity, `## Head-to-Head` table, `## The Bottom Line`, `## The emerging stack` per LAW 4 comparison exception).## Follow-up turn-If the user runs `/last30days OpenClaw` normally, sees the synthesis in chat, and THEN explicitly refers back to that visible synthesis ("save that as HTML", "make this shareable", "turn the above into HTML"), do the same save flow on the synthesis you wrote in the previous turn. Do not re-research; the synthesis is already in the conversation history. Just write it to the temp file and call the engine with `--emit=html --synthesis-file`, then use the normal-report-plus-HTML artifact block.+If the user runs `/last30days OpenClaw` normally, sees the synthesis in chat, and THEN explicitly refers back to that visible synthesis ("save that as HTML", "make this shareable", "turn the above into HTML"), do the same save flow on the synthesis you wrote in the previous turn. Write the synthesis to the temp file. Call the engine with `--cached-report --emit=html --synthesis-file`. Use the normal-report-plus-HTML artifact block.If the follow-up instead asks for a new HTML deliverable ("give it to me in HTML", `--emit=html`, `--html`) rather than referring back to an already-visible report, treat it as HTML-as-deliverable mode.-The engine will try to reuse `~/.config/last30days/last-report.json` for that second invocation when it is still within `LAST30DAYS_REPORT_CACHE_TTL_SECONDS` (default: one hour). If stderr says it is reusing cached report data, continue normally. If stderr says no matching cache exists, the cache may be stale; let the command finish only if you supplied the same scope flags as the original run. Otherwise stop and re-run with the original flags so the HTML footer does not describe a different dataset.+The engine reuses `~/.config/last30days/last-report.json` when it is still within `LAST30DAYS_REPORT_CACHE_TTL_SECONDS` (default: one hour). If stderr says it is reusing cached report data, continue normally. If no matching cache exists, the command stops before research. Recreate the original plans, rerun the original research scope, and update the synthesis before exporting again.## What NOT to dodiff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex e8e9535c..72c473fd 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -667,6 +667,8 @@ def build_parser() -> argparse.ArgumentParser:allow_abbrev=False,)parser.add_argument("topic", nargs="*", help="Research topic")+ parser.add_argument("--research-only", action="store_true",+ help="Treat the topic as research text, never as an administrative command")parser.add_argument("--emit", default="compact", choices=["compact", "json", "context", "md", "html", "brief"])parser.add_argument("--register",@@ -790,6 +792,8 @@ def build_parser() -> argparse.ArgumentParser:)parser.add_argument("--output", help="Optional exact file path for saving the rendered output")parser.add_argument("--synthesis-file", help="Markdown synthesis to embed in --emit=html output")+ parser.add_argument("--cached-report", action="store_true",+ help="Render --emit=html --synthesis-file from cached research only, without replaying temporary plans")parser.add_argument("--publish-html", action="store_true",help="Publish --emit=html output to ht-ml.app (explicit opt-in; public by default)")parser.add_argument("--publish", action="store_true",@@ -1307,7 +1311,7 @@ def _show_runtime_ui(progress.show_promo(promo, diag=diag)-REPORT_CACHE_VERSION = "last30days-report-cache/v1"+REPORT_CACHE_VERSION = "last30days-report-cache/v2"DEFAULT_REPORT_CACHE_TTL_SECONDS = 3600@@ -1339,6 +1343,7 @@ def _write_last_run(entity_reports: list[tuple[str, schema.Report]] | None = None,*,x_envelope_sha256: str | None = None,+ research_options: dict[str, object] | None = None,) -> bool:# ``x_envelope_sha256`` binds the cached report to the --x-posts file it# was built from; _load_last_report_cache misses on any mismatch.@@ -1368,6 +1373,10 @@ def _write_last_run("timestamp": payload["timestamp"],"comparison": bool(entity_reports),"x_envelope_sha256": x_envelope_sha256 or None,+ "research_options": (+ research_options if research_options is not None+ else _cache_research_options(build_parser().parse_args([]))+ ),"reports": [{"entity": label, "report": schema.to_dict(cached_report)}for label, cached_report in cached_reports@@ -1390,6 +1399,9 @@ def _load_last_report_cache(ttl_seconds: int = DEFAULT_REPORT_CACHE_TTL_SECONDS,*,x_envelope_sha256: str | None = None,+ research_options: dict[str, object] | None = None,+ requested_window: tuple[str, str] | None = None,+ use_cached_envelopes: bool = False,) -> tuple[schema.Report, list[tuple[str, schema.Report]] | None, Path] | None:cache_path = _last_report_cache_path()if cache_path is None or not cache_path.exists():@@ -1406,7 +1418,12 @@ def _load_last_report_cache(# same envelope content; a digest on either side that does not match# the other is a miss.cached_digest = payload.get("x_envelope_sha256") or None- if (cached_digest or x_envelope_sha256) and cached_digest != x_envelope_sha256:+ if not use_cached_envelopes and (cached_digest or x_envelope_sha256) and cached_digest != x_envelope_sha256:+ return None+ cached_options = payload.get("research_options") or {}+ if not isinstance(cached_options, dict):+ return None+ if any(cached_options.get(key) != value for key, value in (research_options or {}).items()):return Nonecached_topic = str(payload.get("topic") or "").strip().lower()if topic is not None and cached_topic != topic.strip().lower():@@ -1421,6 +1438,11 @@ def _load_last_report_cache(]if not entity_reports:return None+ if requested_window is not None and any(+ (report.range_from, report.range_to) != requested_window+ for _, report in entity_reports+ ):+ return Noneif payload.get("comparison"):if len(entity_reports) < 2:return None@@ -1436,6 +1458,74 @@ def _load_last_report_cache(return None+def _cache_research_options(+ args: argparse.Namespace, config: dict[str, object] | None = None, *, supplied_only: bool = False,+ resolved_corpus_dirs: list[Path] | None = None,+) -> dict[str, object]:+ names = (+ "search", "quick", "deep", "mock", "web_backend", "perplexity_search_type",+ "hiring_signals", "x_handle", "x_related", "official_site", "no_x_handle",+ "subreddits", "dedicated_subreddits", "devto_tags", "tiktok_hashtags",+ "tiktok_creators", "ig_creators", "max_results", "max_per_source",+ "max_source_fetches", "auto_resolve", "github_user", "github_repo",+ "trustpilot_domain", "amazon_query", "meta_ads_page", "telegram_sources",+ "competitors", "competitors_list", "polymarket_keywords", "corpus_all_time", "drill",+ )+ options = {+ name: getattr(args, name, None) for name in names+ if not supplied_only or name in getattr(args, "_explicit_options", ())+ }+ if not supplied_only or "corpus" in getattr(args, "_explicit_options", ()):+ if resolved_corpus_dirs is None:+ resolved_corpus_dirs = corpus.resolve_directories(+ args.corpus, (config or {}).get("LAST30DAYS_CORPUS_DIRS")+ )+ if "corpus" in {+ value.strip().lower()+ for value in str((config or {}).get("EXCLUDE_SOURCES") or "").split(",")+ }:+ resolved_corpus_dirs = []+ options["corpus_sha256"] = hashlib.sha256(json.dumps([+ os.path.normcase(str(path)) for path in resolved_corpus_dirs+ ]).encode("utf-8")).hexdigest()+ for name in ("plan", "competitors_plan"):+ raw = getattr(args, name, None)+ if not supplied_only:+ options[name] = None+ if raw:+ try:+ content = Path(raw).read_text(encoding="utf-8") if os.path.isfile(raw) else raw+ content = json.dumps(json.loads(content), sort_keys=True)+ except (OSError, ValueError):+ content = raw+ options[name] = hashlib.sha256(content.encode("utf-8")).hexdigest()+ if not supplied_only:+ rendering_keys = {+ "FUN_LEVEL", "ELI5_MODE", "LAST30DAYS_REGISTER", "LAST30DAYS_MEMORY_DIR",+ "LAST30DAYS_REPORT_CACHE_TTL_SECONDS", "LAST30DAYS_STORE", "LAST30DAYS_DEBUG",+ "LAST30DAYS_STRICT_EXIT", "LAST30DAYS_VERIFY_FRESHNESS", "LAST30DAYS_PUBLISH_PASSWORD",+ "LAST30DAYS_CORPUS_DIRS",+ }+ research_keys = {+ "INCLUDE_SOURCES", "EXCLUDE_SOURCES", "TELEGRAM_SOURCES", "BSKY_HANDLE",+ "BSKY_SEARCH_HOST", "FROM_BROWSER", "BROWSER_CONSENT", "BROWSER_CDP_URL",+ "DEGRADED_TRANSCRIPT_THRESHOLD",+ }+ relevant_config = {}+ for key, value in (config or {}).items():+ if key.startswith("_") or key in rendering_keys:+ continue+ if key.endswith(("_KEY", "_TOKEN", "_PASSWORD", "_SECRET", "_COOKIE")) or key == "CT0":+ if value:+ relevant_config[key] = True+ elif key in research_keys or key.startswith("LAST30DAYS_") or key.endswith(("_BASE_URL", "_MODEL_PIN")):+ relevant_config[key] = value+ options["config_sha256"] = hashlib.sha256(+ json.dumps(relevant_config, sort_keys=True, default=str).encode("utf-8")+ ).hexdigest()+ return options++def _config_truthy(value: object) -> bool:return str(value or "").strip().lower() in {"1", "true", "yes", "on"}@@ -1658,7 +1748,7 @@ def _run_drill(_verify_report_set(merged, None, allow_network=not args.mock)else:merged.freshness_verdicts = []- if _write_last_run(report.topic, merged):+ if _write_last_run(report.topic, merged, research_options=_cache_research_options(args, config)):sys.stderr.write(f"[last30days] Updated drill cache in {cache_path}\n")else:sys.stderr.write(@@ -2980,7 +3070,7 @@ def _validate_extra_argv(parser: argparse.ArgumentParser, topic: str, extra_argvdef _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: list[str]) -> env.ConfigLoadPolicy:- normalized_topic = topic.lower()+ normalized_topic = "" if args.research_only or args.cached_report else topic.lower()is_library_command = (normalized_topic == "library feed"or normalized_topic == "library search"@@ -2997,7 +3087,7 @@ def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: liif args.no_browser_cookies:browser_mode = "off"elif (- args.diagnose or args.preflight or normalized_topic == "doctor"+ args.diagnose or args.preflight or args.cached_report or normalized_topic == "doctor"or is_library_command or is_queue_command or is_cached_verification):# doctor is plan-only like --diagnose: it must never read cookies.@@ -3280,6 +3370,12 @@ def main() -> int:# Use parse_known_args so setup sub-flags (--device-auth, --github,# --openclaw) pass through without argparse hard-exiting.args, extra_argv = parser.parse_known_args()+ option_argv = sys.argv[1:sys.argv.index("--")] if "--" in sys.argv else sys.argv[1:]+ option_tokens = {token.split("=", 1)[0] for token in option_argv}+ args._explicit_options = {+ action.dest for action in parser._actions+ if any(option in option_tokens for option in action.option_strings)+ }if args.record_fixtures:with http.recording_requests(Path(args.record_fixtures)):return _main(parser, args, extra_argv)@@ -3327,6 +3423,13 @@ def _main(if args.debug:os.environ["LAST30DAYS_DEBUG"] = "1"+ if args.cached_report and (+ args.emit != "html" or not args.synthesis_file or not args.topic or args.deep_research+ or args.plan or args.competitors_plan or args.x_posts+ or args.discover is not None or args.drill or args.diagnose or args.preflight+ or args.welcome or args.resolve_save_dir or args.verify_freshness is True+ ):+ parser.error("--cached-report requires a topic, --emit=html, and --synthesis-file without research input files, --verify-freshness, or other command modes")if args.welcome:from lib import setup_wizardprint(setup_wizard.render_welcome())@@ -3334,7 +3437,15 @@ def _main(topic = " ".join(args.topic).strip()original_topic = topic- _validate_extra_argv(parser, topic, extra_argv)+ requested_window = (+ dates.get_date_range(+ 30 if args.lookback_days is None else args.lookback_days,+ as_of_date=args.as_of_date,+ )+ if not args.cached_report or args.lookback_days is not None or args.as_of_date is not None else None+ )+ command_topic = "" if args.research_only or args.cached_report else topic.lower()+ _validate_extra_argv(parser, command_topic, extra_argv)if args.resolve_save_dir:print(env.resolve_memory_dir(args.save_dir))return 0@@ -3344,12 +3455,12 @@ def _main("accepted); write the envelope to a .json file and pass its path.\n")return 2- if args.publish and topic.lower() != "library feed":+ if args.publish and command_topic != "library feed":sys.stderr.write("[last30days] --publish is only supported by the 'library feed' command.\n")return 2- if topic.lower() == "setup":+ if command_topic == "setup":# Persisting a credential needs no config load (no Keychain / pass# probes, no cookie policy), so it dispatches before get_config.store_key_present, store_key_name, _ = _split_store_key(extra_argv)@@ -3381,6 +3492,10 @@ def _main(config["_CORPUS_DIRS"] = [str(path) for path in resolved_corpus_dirs]if _config_truthy(config.get("LAST30DAYS_CORPUS_IN_EXPORT")):config["_CORPUS_IN_EXPORT"] = True+ research_options = _cache_research_options(+ args, config, supplied_only=args.cached_report,+ resolved_corpus_dirs=resolved_corpus_dirs,+ )_propagate_config_to_environ(config)# Env-var fallback for --save-dir, mirroring the LAST30DAYS_STORE pattern below.@@ -3427,7 +3542,7 @@ def _main(# match only, so multi-word research topics containing "doctor" still# research normally). Aggregates probes/descriptors/prescriptions into# one grouped health surface; always exits 0.- if topic.lower() == "doctor":+ if command_topic == "doctor":from lib import doctorreturn doctor.run(config,@@ -3437,18 +3552,18 @@ def _main(probe="--probe" in extra_argv,)- if topic.lower() == "library feed":+ if command_topic == "library feed":return _run_library_feed(args, config)- if topic.lower() == "library search" or topic.lower().startswith("library search "):+ if command_topic == "library search" or command_topic.startswith("library search "):return _run_library_search(args, config, topic[len("library search") :].strip())- if topic.lower() == "queue list":+ if command_topic == "queue list":return _run_queue_list(args, config)- if topic.lower() == "queue cover" or topic.lower().startswith("queue cover "):+ if command_topic == "queue cover" or command_topic.startswith("queue cover "):return _run_queue_cover(args, config, topic[len("queue cover") :].strip())# Handle setup subcommand- if topic.lower() == "setup":+ if command_topic == "setup":from lib import setup_wizardif "--openclaw" in extra_argv:results = setup_wizard.run_openclaw_setup(config)@@ -3726,6 +3841,7 @@ def _main(if (topicand not args.diagnose+ and not args.cached_reportand not args.mockand not args.record_fixturesand env.read_secret_env("LAST30DAYS_API_KEY")@@ -3893,6 +4009,9 @@ def _main(topic,ttl_seconds=_report_cache_ttl_seconds(config),x_envelope_sha256=_x_envelope_digest(x_posts_envelope, comp_plan),+ research_options=research_options,+ requested_window=requested_window,+ use_cached_envelopes=args.cached_report,)if cached is not None:cached_report, cached_entity_reports, cache_path = cached@@ -3900,7 +4019,7 @@ def _main(f"[last30days] Reusing cached report data from {cache_path}\n")sys.stderr.flush()- if _freshness_enabled(args, config):+ if not args.cached_report and _freshness_enabled(args, config):_verify_report_set(cached_report,cached_entity_reports,@@ -3914,6 +4033,9 @@ def _main(return _render_save_and_print(args, cached_report, cached_entity_reports, synthesis_md, config)+ if args.cached_report:+ sys.stderr.write("[last30days] No matching cached report data; rerun research with recreated plans before exporting HTML.\n")+ return 2sys.stderr.write("[last30days] No matching cached report data for ""--emit=html --synthesis-file; running fresh research.\n"@@ -4271,8 +4393,8 @@ def _main("See the skill's references/competitors.md for the full protocol.\n""\n""HEADLESS / CRON PATH (no hosting model available): set "- "BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / PARALLEL_API_KEY / "- "PERPLEXITY_API_KEY / OPENROUTER_API_KEY and re-run.\n"+ "BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / PARALLEL_API_KEY "+ "and re-run.\n""\n""MINIMUM ESCAPE HATCH: pass --competitors-list 'A,B,C' to skip ""discovery. Without --competitors-plan, peer sub-runs fall back to "@@ -4338,6 +4460,7 @@ def _main(# An advertiser page is per-entity state by definition: left in# place it would render one brand's ads as every peer's.entity_config.pop("_meta_ads_page", None)+ entity_config.pop("_dedicated_subreddits", None)plan_entry = comp_plan.get(entity.strip().lower(), {})resolved = {"entity": entity,@@ -4479,6 +4602,7 @@ def _main(_write_last_run(original_topic, report, entity_reports=entity_reports,x_envelope_sha256=_x_envelope_digest(x_posts_envelope, comp_plan),+ research_options=research_options,)# LAST30DAYS_STORE env var = persistence default-on. Read both os.environ# (for shell-exported users) and config (for users who set it indiff --git a/skills/last30days/scripts/lib/chrome_cookies.py b/skills/last30days/scripts/lib/chrome_cookies.pyindex 9289d804..8e11d7b9 100644--- a/skills/last30days/scripts/lib/chrome_cookies.py+++ b/skills/last30days/scripts/lib/chrome_cookies.py@@ -14,7 +14,6 @@ This is NOT affected by Windows App-Bound Encryption (v20).import hashlibimport loggingimport os-import shutilimport sqlite3import subprocessimport tempfile@@ -22,6 +21,7 @@ from pathlib import Pathfrom typing import Optionalfrom .cookie_paths import path_exists, path_is_dir+from .sqlite_snapshot import copy_snapshotlogger = logging.getLogger(__name__)@@ -210,7 +210,7 @@ def _extract_chromium_cookies_macos() -> Optional[dict[str, str]]:"""Extract cookies from any Chromium-based browser on macOS.- Copies the locked Cookies database to a temp file, reads specified cookies,+ Snapshots committed Cookies database state to a temp file, reads specified cookies,and decrypts v10-encrypted values using the Keychain-stored key.Args:@@ -231,15 +231,13 @@ def _extract_chromium_cookies_macos(logger.info("%s cookies database not found at %s", keychain_service, db_path)return None- # Copy DB to temp file (browser locks the original while running)+ # The backup includes committed WAL updates while the browser is running.tmp_fd = Nonetmp_path = Nonetry:tmp_fd, tmp_path = tempfile.mkstemp(suffix=".sqlite")- # mkstemp creates the file 0600. copy2 would copy the source DB's- # permission bits onto the temp file before the chmod below runs,- # briefly exposing live cookies when the source DB is looser.- shutil.copyfile(str(db_path), tmp_path)+ # Snapshot content only; preserve mkstemp's 0600 permissions.+ copy_snapshot(db_path, tmp_path)_lock_temp_cookie_copy(tmp_path)except Exception as e:browser_read_denied = isinstance(e, PermissionError) and e.filename == str(db_path)@@ -260,6 +258,7 @@ def _extract_chromium_cookies_macos(import osos.close(tmp_fd)+ conn = Nonetry:conn = sqlite3.connect(tmp_path)cursor = conn.cursor()@@ -309,8 +308,6 @@ def _extract_chromium_cookies_macos(elif encrypted_value:logger.debug("Unknown encryption for cookie %s (prefix: %r)", name, encrypted_value[:3])- conn.close()-if not results:logger.info("No matching cookies found in %s for domain %s", keychain_service, domain)return None@@ -324,6 +321,8 @@ def _extract_chromium_cookies_macos(logger.info("Unexpected error reading %s cookies: %s", keychain_service, e)return Nonefinally:+ if conn is not None:+ conn.close()try:Path(tmp_path).unlink(missing_ok=True)except Exception:diff --git a/skills/last30days/scripts/lib/cookie_extract.py b/skills/last30days/scripts/lib/cookie_extract.pyindex d12b1e1b..25fef2d6 100644--- a/skills/last30days/scripts/lib/cookie_extract.py+++ b/skills/last30days/scripts/lib/cookie_extract.py@@ -13,13 +13,13 @@ import functoolsimport loggingimport osimport platform-import shutilimport sqlite3import tempfilefrom pathlib import Pathfrom typing import Dict, List, Optionalfrom .cookie_paths import path_is_dir, path_is_file+from .sqlite_snapshot import copy_snapshotlogger = logging.getLogger(__name__)@@ -252,9 +252,9 @@ def _fallback_find_profile(def _query_cookies_db(db_path: Path, domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]:- """Copy the cookies database to a temp file and query it.+ """Snapshot the cookies database to a temp file and query it.- Firefox locks cookies.sqlite while running, so we copy first.+ The snapshot includes committed WAL updates while Firefox is running.Returns {name: value} dict or None if no matching cookies found."""if not path_is_file(db_path):@@ -264,12 +264,8 @@ def _query_cookies_db(tmp_path = Nonetry:tmp_fd, tmp_path = tempfile.mkstemp(suffix=".sqlite")- # mkstemp creates the file 0600. copy2 would copy the source's mode- # (Firefox cookies.sqlite is commonly 0644, looser on WSL /mnt/c) onto- # the temp file, leaving live session secrets world-readable in shared- # /tmp until the chmod below runs. copyfile writes content only and- # leaves the 0600 perms intact, closing that window.- shutil.copyfile(str(db_path), tmp_path)+ # Snapshot content only; preserve mkstemp's 0600 permissions.+ copy_snapshot(db_path, tmp_path)_lock_temp_cookie_copy(tmp_path)conn = sqlite3.connect(tmp_path)diff --git a/skills/last30days/scripts/lib/dates.py b/skills/last30days/scripts/lib/dates.pyindex 33980e4e..6705c988 100644--- a/skills/last30days/scripts/lib/dates.py+++ b/skills/last30days/scripts/lib/dates.py@@ -1,9 +1,18 @@"""Date utilities for last30days skill."""-from datetime import datetime, timedelta, timezone+from datetime import date, datetime, timedelta, timezonefrom typing import Optional, Tuple+def x_date_filters(from_date: str, to_date: str) -> str:+ """Translate an inclusive research window to X search operators."""+ filters = f"since:{from_date}"+ end = date.fromisoformat(to_date)+ if end != date.max:+ filters += f" until:{(end + timedelta(days=1)).isoformat()}"+ return filters++def parse_as_of_date(as_of_date: Optional[str]) -> Optional[str]:"""Validate and normalize an --as-of date.diff --git a/skills/last30days/scripts/lib/freshness.py b/skills/last30days/scripts/lib/freshness.pyindex 06d66170..20ab3bb0 100644--- a/skills/last30days/scripts/lib/freshness.py+++ b/skills/last30days/scripts/lib/freshness.py@@ -40,10 +40,11 @@ Refetcher = Callable[[schema.SourceItem | None, str], RefetchedDatum | dict[str,_STATUS_PATTERN = re.compile(r"\b(?P<subject>[A-Z][A-Za-z0-9&.'’/+_-]*(?:\s+[A-Z0-9][A-Za-z0-9&.'’/+_-]*){0,5})"- r"\s+(?:is|was|remains|became|has been)\s+"+ r"\s+(?P<copula>is|was|remains|became|has been)\s+"r"(?P<status>open|closed|active|inactive|available|unavailable|"r"approved|rejected|launched|discontinued|online|offline)\b")+_STATUS_COPULA_PRIORITY = {"was": 0, "became": 0, "has been": 1, "is": 2, "remains": 2}_OPPOSITE_STATUS = {"open": "closed","closed": "open",@@ -328,14 +329,24 @@ def _newer_status_contradiction(candidates.sort(key=lambda item: item.published_at or "", reverse=True)for item in candidates:text = f"{item.title} {item.snippet} {item.body}"+ statuses_by_priority: dict[int, set[str]] = defaultdict(set)for match in _STATUS_PATTERN.finditer(text):asserted_subject = [token.lower()for token in re.findall(r"[A-Za-z0-9]+", match.group("subject"))if len(token) >= 3]- if asserted_subject == subject_tokens and match.group("status").lower() == opposite:+ if asserted_subject == subject_tokens:+ status = match.group("status").lower()+ if status in {opposite, claim.original_value}:+ priority = _STATUS_COPULA_PRIORITY[match.group("copula")]+ statuses_by_priority[priority].add(status)+ if statuses_by_priority:+ priority = max(statuses_by_priority)+ statuses = statuses_by_priority[priority]+ if opposite in statuses and (priority == 0 or len(statuses) == 1):return item+ return Nonereturn Nonediff --git a/skills/last30days/scripts/lib/grok_x.py b/skills/last30days/scripts/lib/grok_x.pyindex 8199c56a..6636ed5c 100644--- a/skills/last30days/scripts/lib/grok_x.py+++ b/skills/last30days/scripts/lib/grok_x.py@@ -49,6 +49,7 @@ from pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuplefrom . import log, usage+from .dates import x_date_filtersfrom .relevance import token_overlap_relevance as _compute_relevance# One copy of the snowflake, handle-grammar, and generated-sequence helpers# lives in x_api; grok_x keeps its private names for its callers and@@ -129,7 +130,7 @@ def _fanout_queries(topic: str, from_date: str, to_date: str, calls: int) -> Lis(person/product). "Rome Italy" → no phrase-quote (place/disambiguation)."Peter Steinberger" → phrase-quote in one variant (proper name)."""- window = f"since:{from_date} until:{to_date}"+ window = x_date_filters(from_date, to_date)# First variant: unquoted AND (multi-word topics naturally AND their terms)variants = [f"{topic} {window}",@@ -424,7 +425,7 @@ def _validate_items(created = _decode_snowflake(item.get("post_id"))if created is None:continue- if not (lo <= created <= hi.replace(hour=23, minute=59, second=59)):+ if not (lo.date() <= created.date() <= hi.date()):continuekept.append(item)@@ -1133,9 +1134,9 @@ def search_handles(continue# AND topic only when explicitly requested (extracted handles)if and_topic and topic:- query = f"from:{clean} {topic} since:{from_date} until:{to_date}"+ query = f"from:{clean} {topic} {x_date_filters(from_date, to_date)}"else:- query = f"from:{clean} since:{from_date} until:{to_date}"+ query = f"from:{clean} {x_date_filters(from_date, to_date)}"items, _, revoked = _run_query(query,from_date, to_date, limit=count_per, relevance_topic=topic,@@ -1176,7 +1177,7 @@ def search_mentions(if not clean:continueitems, _, revoked = _run_query(- f"@{clean} -from:{clean} since:{from_date} until:{to_date}",+ f"@{clean} -from:{clean} {x_date_filters(from_date, to_date)}",from_date, to_date, limit=count_per, relevance_topic=topic,attempts=1, deadline=deadline, cancel=cancel,)@@ -1225,7 +1226,7 @@ def search_name()query = " ".join(part for part in- [phrase, excludes, f"min_faves:{min_faves}", f"since:{from_date}", f"until:{to_date}"]+ [phrase, excludes, f"min_faves:{min_faves}", x_date_filters(from_date, to_date)]if part)items, _, revoked = _run_query(diff --git a/skills/last30days/scripts/lib/grounding.py b/skills/last30days/scripts/lib/grounding.pyindex 681fd7af..dd767b7a 100644--- a/skills/last30days/scripts/lib/grounding.py+++ b/skills/last30days/scripts/lib/grounding.py@@ -294,6 +294,19 @@ def _parse_serper_date(raw: str, now: datetime | None = None) -> str | None:# Dispatcher# ---------------------------------------------------------------------------+def configured_backend(config: dict) -> str | None:+ """Return the first configured search API backend, excluding keyless search."""+ for backend, key in (+ ("brave", "BRAVE_API_KEY"),+ ("exa", "EXA_API_KEY"),+ ("serper", "SERPER_API_KEY"),+ ("parallel", "PARALLEL_API_KEY"),+ ):+ if config.get(key):+ return backend+ return None++def web_search(query: str,date_range: tuple[str, str],@@ -302,21 +315,9 @@ def web_search() -> tuple[list[dict], dict]:"""Run web search with the specified or auto-detected backend."""if backend == "auto":- if config.get("BRAVE_API_KEY"):- backend = "brave"- elif config.get("EXA_API_KEY"):- backend = "exa"- elif config.get("SERPER_API_KEY"):- backend = "serper"- elif config.get("PARALLEL_API_KEY"):- backend = "parallel"- elif env.keyless_web_allowed(config):- # No paid key and the host has no native search -> use the keyless- # floor. On a native-search host this branch is skipped (the model- # supplies web results itself), so the engine returns nothing here.- backend = "keyless"- else:- return [], {}+ backend = configured_backend(config) or (+ "keyless" if env.keyless_web_allowed(config) else "none"+ )items: list[dict] = []artifact: dict = {}if backend == "brave":diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 08d763d2..2de77ce9 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -85,7 +85,7 @@ from . import (from .cluster import cluster_candidatesfrom . import fusionfrom . import render-from .fusion import collapse_duplicate_urls, weighted_rrf+from .fusion import collapse_duplicate_urls, source_item_key, weighted_rrfDISCOVERY_SOURCES = ("reddit", "hackernews", "digg", "x")_DISCOVERY_GENERIC_DOMAIN_TERMS = {@@ -2359,10 +2359,14 @@ def run(config["_hiring_signals_mode"] = Trueif not requested_sources:available = ["jobs"]+ available = [source for source in available if source not in excluded_sources]if not available:raise RuntimeError("No sources are available for this run.")- planner_requested_sources = requested_sources+ planner_requested_sources = (+ [source for source in requested_sources if source not in excluded_sources]+ if requested_sources else None+ )if hiring_signals_mode and not planner_requested_sources:planner_requested_sources = ["jobs"]@@ -3045,6 +3049,14 @@ def run(bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,elapsed=time.monotonic() - run_started,)+ retained_markets = {+ source_item_key(item) for item in items_by_source.get("polymarket", [])+ }+ for key, stream in bundle.items_by_source_and_query.items():+ if key[1] == "polymarket":+ bundle.items_by_source_and_query[key] = [+ item for item in stream if source_item_key(item) in retained_markets+ ]source_status = _finalize_source_status(bundle.source_status, items_by_source)candidates = weighted_rrf(diff --git a/skills/last30days/scripts/lib/reddit.py b/skills/last30days/scripts/lib/reddit.pyindex 1f9cf7cc..d4836380 100644--- a/skills/last30days/scripts/lib/reddit.py+++ b/skills/last30days/scripts/lib/reddit.py@@ -621,16 +621,12 @@ def search_reddit(else:out_of_range += 1- if in_range:- all_items = in_range- if out_of_range:- _log(f"Filtered {out_of_range} posts outside date range")- else:- _log(f"No posts within date range, keeping all {len(all_items)}")+ all_items = in_range+ if out_of_range:+ _log(f"Filtered {out_of_range} posts outside date range")# === Phase 6: Relevance floor + relevance-weighted ranking ===- # Drop the off-topic tail when enough on-topic posts remain (guard mirrors- # the date filter: keep all if too few clear the floor). When too few clear+ # Drop the off-topic tail when enough on-topic posts remain. When too few clear# the soft floor, still strip zero-overlap posts (relevance exactly 0 = no# title/body token match at all, never on-topic) whenever anything relevant# remains, so viral high-upvote junk can't fill the section. Then rank bydiff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.pyindex abf50894..bee4cb4f 100644--- a/skills/last30days/scripts/lib/render.py+++ b/skills/last30days/scripts/lib/render.py@@ -1765,7 +1765,7 @@ def _escape_markdown_plain_text(value: str) -> str:return _MARKDOWN_PLAIN_TEXT_ESCAPES.sub(r"\\\1", value)-def _markdown_url_link(url: str) -> str:+def _markdown_url_link(url: str, *, label: str | None = None) -> str:"""Render ``url`` as a markdown link when it's safe to, else escaped text.Source URLs are untrusted API responses, not authored content: `(`/`)`/@@ -1800,9 +1800,11 @@ def _markdown_url_link(url: str) -> str:except ValueError:safe_destination = False+ display = sanitized_url if label is None else _escape_markdown_plain_text(label)if safe_destination:- return f"[{sanitized_url}]({sanitized_url})"- return _escape_markdown_plain_text(sanitized_url)+ return f"[{display}]({sanitized_url})"+ escaped_url = _escape_markdown_plain_text(sanitized_url)+ return escaped_url if label is None else f"{display} ({escaped_url})"def render_full(report: schema.Report, save_path: str | None = None) -> str:@@ -3721,15 +3723,15 @@ def _digg_posts_for(item: schema.SourceItem | None, limit: int = 3) -> list[dictdef _format_digg_quote(post: dict, body_limit: int = 200) -> str:"""Format a Digg-attached X post as an inline 'via Digg' quote line."""- handle = post.get("username") or ""- x_url = post.get("x_url") or ""- body = (post.get("body") or "").replace("\n", " ").strip()- if len(body) > body_limit:- body = body[: body_limit - 1].rstrip() + "…"+ handle = _safe_title(post.get("username") or "")+ x_url = _defang_engine_sentinels(post.get("x_url") or "")+ body = _format_untrusted_evidence(+ " ".join((post.get("body") or "").split()), body_limit,+ )if x_url and handle:- return f"[@{handle}]({x_url}) via Digg: {body}"+ return f"{_markdown_url_link(x_url, label=f'@{handle}')} via Digg: {body}"if handle:- return f"@{handle} via Digg: {body}"+ return f"@{_escape_markdown_plain_text(handle)} via Digg: {body}"return f"via Digg: {body}"diff --git a/skills/last30days/scripts/lib/rerank.py b/skills/last30days/scripts/lib/rerank.pyindex 4fd954a1..dbada221 100644--- a/skills/last30days/scripts/lib/rerank.py+++ b/skills/last30days/scripts/lib/rerank.py@@ -807,25 +807,27 @@ def _candidate_haystack(candidate: schema.Candidate) -> str:would see."""parts: list[str] = [candidate.title or "", candidate.snippet or ""]- metadata = candidate.metadata or {}-- transcript_snippet = metadata.get("transcript_snippet") or ""- if isinstance(transcript_snippet, str):- parts.append(transcript_snippet)-- for hl in metadata.get("transcript_highlights") or []:- if isinstance(hl, str):- parts.append(hl)-- for tc in metadata.get("top_comments") or []:- if isinstance(tc, dict):- parts.append(str(tc.get("excerpt", "") or tc.get("text", "") or ""))- elif isinstance(tc, str):- parts.append(tc)-- for insight in metadata.get("comment_insights") or []:- if isinstance(insight, str):- parts.append(insight)+ metadata_sources = [candidate.metadata or {}]+ metadata_sources.extend(item.metadata or {} for item in candidate.source_items)++ for metadata in metadata_sources:+ transcript_snippet = metadata.get("transcript_snippet") or ""+ if isinstance(transcript_snippet, str):+ parts.append(transcript_snippet)++ for hl in metadata.get("transcript_highlights") or []:+ if isinstance(hl, str):+ parts.append(hl)++ for tc in metadata.get("top_comments") or []:+ if isinstance(tc, dict):+ parts.append(str(tc.get("excerpt", "") or tc.get("text", "") or ""))+ elif isinstance(tc, str):+ parts.append(tc)++ for insight in metadata.get("comment_insights") or []:+ if isinstance(insight, str):+ parts.append(insight)return " ".join(parts).lower()diff --git a/skills/last30days/scripts/lib/resolve.py b/skills/last30days/scripts/lib/resolve.pyindex 12388a7d..14e6b11c 100644--- a/skills/last30days/scripts/lib/resolve.py+++ b/skills/last30days/scripts/lib/resolve.py@@ -1,6 +1,6 @@"""Auto-resolve subreddits, X handles, and current events context for a topic.-Uses web search (Brave/Exa/Serper) to discover relevant communities and context+Uses web search (Brave/Exa/Serper/Parallel) to discover relevant communities and contextbefore the planner runs. This is the engine-side equivalent of SKILL.md Steps0.55/0.75 which use Claude Code's WebSearch tool."""@@ -69,15 +69,8 @@ def _merge_category_peers(topic: str, subreddits: list[str]) -> tuple[list[str],def _has_backend(config: dict) -> bool:- """Check if any web search backend is available."""- return bool(- config.get("BRAVE_API_KEY")- or config.get("EXA_API_KEY")- or config.get("SERPER_API_KEY")- or config.get("PARALLEL_API_KEY")- or config.get("OPENROUTER_API_KEY")- or config.get("PERPLEXITY_API_KEY")- )+ """Require a configured search API; the keyless floor is not peer discovery."""+ return grounding.configured_backend(config) is not Nonedef _extract_subreddits(items: list[dict]) -> list[str]:@@ -429,7 +422,7 @@ def auto_resolve(topic: str, config: dict) -> dict:Args:topic: The research topic.- config: Dict with API keys (BRAVE_API_KEY, EXA_API_KEY, SERPER_API_KEY).+ config: Dict with a Brave, Exa, Serper, or Parallel API key.Returns:Dict with keys: subreddits, x_handle, github_user, github_repos,diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 36069dc5..a3c0ea9d 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -710,11 +710,12 @@ def write_api_key(Reuses the same secret-safe write path as ``write_setup_config`` so thevalue lands with restrictive permissions and round-trips through- ``env.load_env_file``. Idempotent by default: if ``key_name`` is already- present in the file, nothing is written and the existing value is+ ``env.load_env_file``. Idempotent by default: if ``key_name`` already has+ a nonempty parsed value, nothing is written and the existing value ispreserved (we never clobber a key the user may have set by hand). With``replace=True`` an existing line is rewritten in place instead, so anexplicit ``setup --store-key`` can rotate a rejected credential.+ Empty assignments are replaced so a signup key becomes usable.Args:env_path: Path to the .env file (e.g. ~/.config/last30days/.env).@@ -739,7 +740,9 @@ def write_api_key(stripped = line.strip()if stripped and not stripped.startswith("#") and "=" in stripped:if _env_line_key(stripped) == key_name:- if replace:+ from .env import load_env_file++ if replace or not load_env_file(env_path).get(key_name):return _replace_env_line(env_path, existing_content, key_name, api_key)return True # Already configured; do not duplicatediff --git a/skills/last30days/scripts/lib/sqlite_snapshot.py b/skills/last30days/scripts/lib/sqlite_snapshot.pynew file mode 100644index 00000000..39822e6b--- /dev/null+++ b/skills/last30days/scripts/lib/sqlite_snapshot.py@@ -0,0 +1,27 @@+"""Bounded, consistent snapshots of browser SQLite databases."""++from contextlib import closing+from pathlib import Path+import sqlite3+import time+++def copy_snapshot(source: Path, destination: str, *, timeout: float = 1.0) -> None:+ """Back up committed database state, including WAL, to a private temp file."""+ source = Path(source)+ # Preserve the OS permission error used to explain browser-access denials;+ # sqlite3.connect otherwise turns it into a generic OperationalError.+ with source.open("rb"):+ pass++ deadline = time.monotonic() + timeout++ def check_deadline(_status: int, _remaining: int, _total: int) -> None:+ if time.monotonic() >= deadline:+ raise sqlite3.OperationalError("Timed out taking browser database snapshot")++ with (+ closing(sqlite3.connect(source.resolve().as_uri() + "?mode=ro", uri=True, timeout=0)) as reader,+ closing(sqlite3.connect(destination, timeout=0)) as writer,+ ):+ reader.backup(writer, pages=128, progress=check_deadline, sleep=0.01)diff --git a/skills/last30days/scripts/lib/trustpilot.py b/skills/last30days/scripts/lib/trustpilot.pyindex f61ecea2..9f08d9af 100644--- a/skills/last30days/scripts/lib/trustpilot.py+++ b/skills/last30days/scripts/lib/trustpilot.py@@ -64,7 +64,11 @@ NO_BROWSER_ENV = "LAST30DAYS_TRUSTPILOT_NO_BROWSER"DOMAIN_DOMINANCE_FACTOR = 50# Domain-like token, e.g. "chownow.com", "nothing.tech".-_DOMAIN_RE = re.compile(r"\b[a-z0-9][a-z0-9-]*\.(com|io|co|net|org|app|ai|dev|gg|tech|shop|store)\b")+_DOMAIN_RE = re.compile(+ r"(?<![\w.-])(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+"+ r"(?:com|io|co|net|org|app|ai|dev|gg|tech|shop|store)"+ r"(?:\.[a-z]{2,63})*(?![\w-]|\.[\w-])"+)# Generic tokens that disqualify a short capitalized phrase from being a brand._GENERIC_TOKENS = {diff --git a/skills/last30days/scripts/lib/web_search_keyless.py b/skills/last30days/scripts/lib/web_search_keyless.pyindex 443e2d90..6cab6602 100644--- a/skills/last30days/scripts/lib/web_search_keyless.py+++ b/skills/last30days/scripts/lib/web_search_keyless.py@@ -161,8 +161,7 @@ def _search_startpage(query: str, count: int) -> list[dict]:return []items: list[dict] = []result_matches = list(_SP_RESULT_RE.finditer(text))- desc_matches = list(_SP_DESC_RE.finditer(text))- for match in result_matches:+ for idx, match in enumerate(result_matches):if len(items) >= count:breaktarget = html.unescape(match.group("href"))@@ -172,12 +171,9 @@ def _search_startpage(query: str, count: int) -> list[dict]:title = _strip_html(h2.group("title") if h2 else match.group("inner"))if not title:continue- # First description block that appears after this result's title anchor.- snippet = ""- for desc in desc_matches:- if desc.start() > match.end():- snippet = _strip_html(desc.group("snippet"))- break+ next_start = result_matches[idx + 1].start() if idx + 1 < len(result_matches) else len(text)+ desc = _SP_DESC_RE.search(text, match.end(), next_start)+ snippet = _strip_html(desc.group("snippet")) if desc else ""items.append(_to_item(len(items), title, target, snippet))return itemsdiff --git a/skills/last30days/scripts/lib/xquik.py b/skills/last30days/scripts/lib/xquik.pyindex 973dcf85..32f4eec8 100644--- a/skills/last30days/scripts/lib/xquik.py+++ b/skills/last30days/scripts/lib/xquik.py@@ -12,6 +12,7 @@ from datetime import datetimefrom typing import Any, Dict, List, Optionalfrom . import http, log+from .dates import x_date_filtersfrom .relevance import token_overlap_relevance as _compute_relevancefrom .x_api import is_own_post@@ -88,7 +89,7 @@ def search_xquik(Args:topic: Search topicfrom_date: Start date (YYYY-MM-DD)- to_date: End date (YYYY-MM-DD)+ to_date: Inclusive end date (YYYY-MM-DD)depth: Research depth - "quick", "default", or "deep"token: Xquik API keydeadline: Optional shared wall-clock deadline (``time.monotonic()``@@ -111,7 +112,7 @@ def search_xquik(if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):_log("chain deadline reached; skipping remaining queries")return {"items": all_items, "error": "Xquik research cancelled or timed out"}- q = f"{query_text} since:{from_date} until:{to_date}"+ q = f"{query_text} {x_date_filters(from_date, to_date)}"items, auth_error = _execute_search(q, cfg["limit"], token,label=query_text, id_prefix="XQ",@@ -256,7 +257,7 @@ def search_handles(handle = str(raw).lstrip("@").strip()if not handle:continue- q = f"from:{handle} since:{from_date} until:{to_date}"+ q = f"from:{handle} {x_date_filters(from_date, to_date)}"got, auth_error = _execute_search(q, count_per, token,label=f"from:{handle}", id_prefix="XF",@@ -311,7 +312,7 @@ def search_mentions(handle = str(raw).lstrip("@").strip()if not handle:continue- q = f"@{handle} since:{from_date} until:{to_date}"+ q = f"@{handle} {x_date_filters(from_date, to_date)}"got, auth_error = _execute_search(q, count_per, token,label=f"@{handle}", id_prefix="XA",diff --git a/skills/last30days/scripts/setup-pass.sh b/skills/last30days/scripts/setup-pass.shindex 0e995daf..1dce4431 100755--- a/skills/last30days/scripts/setup-pass.sh+++ b/skills/last30days/scripts/setup-pass.sh@@ -19,6 +19,7 @@set -euo pipefailPREFIX="${LAST30DAYS_PASS_PREFIX:-last30days/}"+STORE_DIR="${PASSWORD_STORE_DIR:-${HOME}/.password-store}"# Mirrors lib/env.py::KEYCHAIN_KEYS — kept in sync via# tests/test_env_pass.py::test_pass_keys_match_setup_script.ALL_KEYS=(@@ -99,7 +100,9 @@ fiadded=0; skipped=0; replaced=0for key in "${TARGETS[@]}"; do- if pass show "${PREFIX}${key}" >/dev/null 2>&1; then+ # Existence must not depend on GPG decryption or a successful pinentry prompt.+ entry="${STORE_DIR}/${PREFIX}${key}.gpg"+ if [[ -e "${entry}" || -L "${entry}" ]]; thenexisting=1elseexisting=0@@ -116,9 +119,19 @@ for key in "${TARGETS[@]}"; doskipped=$((skipped + 1))continuefi+ # pass treats piped input as overwrite consent, even without --force.+ if [[ "${REPLACE}" -eq 0 && (-e "${entry}" || -L "${entry}") ]]; then+ printf " %-28s (set while prompting, skipping — use --replace to overwrite)\n" "${key}"+ skipped=$((skipped + 1))+ continue+ fi# Don't let one failed insert (gpg misconfig, missing store key, disk) abort# the whole batch under `set -e`; report it and move on.- if ! printf '%s\n' "$value" | pass insert -m -f "${PREFIX}${key}" >/dev/null; then+ insert_args=(-m)+ if [[ "${REPLACE}" -eq 1 ]]; then+ insert_args+=(-f)+ fi+ if ! printf '%s\n' "$value" | pass insert "${insert_args[@]}" "${PREFIX}${key}" >/dev/null; thenecho " failed: $key (pass insert error)" >&2skipped=$((skipped + 1))continuediff --git a/skills/last30days/scripts/store.py b/skills/last30days/scripts/store.pyindex 70ffeac6..d4c2a73d 100644--- a/skills/last30days/scripts/store.py+++ b/skills/last30days/scripts/store.py@@ -598,7 +598,7 @@ def store_findings(new_engagement = f.get("engagement_score") or 0if existing:update_rows.append((- max(new_engagement, existing["engagement_score"] or 0),+ new_engagement,run_id,existing["id"],))@@ -621,7 +621,7 @@ def store_findings("""UPDATE findings SETlast_seen = datetime('now'),sighting_count = sighting_count + 1,- engagement_score = ?,+ engagement_score = max(coalesce(engagement_score, 0), ?),run_id = ?WHERE id = ?""",update_rows,diff --git a/tests/test_chrome_cookies.py b/tests/test_chrome_cookies.pyindex b0a83eca..9cd6d630 100644--- a/tests/test_chrome_cookies.py+++ b/tests/test_chrome_cookies.py@@ -35,7 +35,7 @@ def test_cookie_copy_permission_denial_is_not_reported_as_missing(tmp_path):db = tmp_path / "Cookies"db.touch()with mock.patch(- "lib.chrome_cookies.shutil.copyfile",+ "lib.chrome_cookies.copy_snapshot",side_effect=PermissionError(1, "Operation not permitted", str(db)),):with pytest.raises(PermissionError):@@ -49,7 +49,7 @@ def test_temporary_storage_denial_is_not_blamed_on_browser_access(tmp_path):db.touch()denied_temp = tmp_path / "temporary.sqlite"with mock.patch(- "lib.chrome_cookies.shutil.copyfile",+ "lib.chrome_cookies.copy_snapshot",side_effect=PermissionError(13, "Permission denied", str(denied_temp)),):assert _extract_chromium_cookies_macos(@@ -230,14 +230,14 @@ def test_denied_default_copy_uses_complete_pair_in_later_profile(tmp_path):(".x.com", "auth_token", "dummy-auth", b""),(".x.com", "ct0", "dummy-ct0", b""),])- real_copyfile = shutil.copyfile+ real_copyfile = chrome_cookies.copy_snapshotdef guarded_copyfile(source, target):- if source == str(blocked):+ if Path(source) == blocked:raise PermissionError(1, "Operation not permitted", str(blocked))return real_copyfile(source, target)- with mock.patch("lib.chrome_cookies.shutil.copyfile", side_effect=guarded_copyfile):+ with mock.patch("lib.chrome_cookies.copy_snapshot", side_effect=guarded_copyfile):found = chrome_cookies._extract_chromium_cookies_any_profile(tmp_path, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"])@@ -411,7 +411,9 @@ class TestUnencryptedCookies:real_connect = sqlite3.connectdef assert_temp_copy_locked(path, *args, **kwargs):- if Path(str(path)) != db_path:+ if kwargs.get("uri"):+ assert path == db_path.resolve().as_uri() + "?mode=ro"+ elif Path(str(path)) != db_path:assert Path(str(path)).stat().st_mode & 0o777 == 0o600return real_connect(path, *args, **kwargs)diff --git a/tests/test_cookie_extract.py b/tests/test_cookie_extract.pyindex 78f1f20e..137d10f1 100644--- a/tests/test_cookie_extract.py+++ b/tests/test_cookie_extract.py@@ -25,7 +25,7 @@ def test_firefox_database_permission_denial_survives_extractor(tmp_path):db = tmp_path / "cookies.sqlite"db.touch()with patch(- "lib.cookie_extract.shutil.copyfile",+ "lib.cookie_extract.copy_snapshot",side_effect=PermissionError(1, "Operation not permitted", str(db)),):with pytest.raises(PermissionError):@@ -194,11 +194,11 @@ class TestExtractFirefoxCookies:})blocked = profiles_dir / "xyz789.other" / "cookies.sqlite"- real_copyfile = cookie_extract.shutil.copyfile+ real_copyfile = cookie_extract.copy_snapshotrequested = []def guarded_copyfile(source, target):- if source == str(blocked):+ if Path(source) == blocked:raise PermissionError(1, "Operation not permitted", str(blocked))return real_copyfile(source, target)@@ -207,7 +207,7 @@ class TestExtractFirefoxCookies:requested.append(cookie_names)return cookie_extract._try_firefox_dir(profiles_dir, domain, cookie_names)- with patch("lib.cookie_extract.shutil.copyfile", side_effect=guarded_copyfile), patch(+ with patch("lib.cookie_extract.copy_snapshot", side_effect=guarded_copyfile), patch("lib.cookie_extract.extract_cookies",side_effect=extract_requested,):@@ -274,14 +274,14 @@ class TestExtractFirefoxCookies:})blocked = profiles_dir / "abc123.default-release" / "cookies.sqlite"- real_copyfile = cookie_extract.shutil.copyfile+ real_copyfile = cookie_extract.copy_snapshotdef guarded_copyfile(source, target):- if source == str(blocked):+ if Path(source) == blocked:raise PermissionError(1, "Operation not permitted", str(blocked))return real_copyfile(source, target)- with patch("lib.cookie_extract.shutil.copyfile", side_effect=guarded_copyfile):+ with patch("lib.cookie_extract.copy_snapshot", side_effect=guarded_copyfile):found = cookie_extract._try_firefox_dir(profiles_dir, ".x.com", ["auth_token", "ct0"])@@ -306,7 +306,9 @@ class TestExtractFirefoxCookies:real_connect = sqlite3.connectdef assert_temp_copy_locked(path, *args, **kwargs):- if Path(str(path)) != db_path:+ if kwargs.get("uri"):+ assert path == db_path.resolve().as_uri() + "?mode=ro"+ elif Path(str(path)) != db_path:assert Path(str(path)).stat().st_mode & 0o777 == 0o600return real_connect(path, *args, **kwargs)diff --git a/tests/test_cr20_auth.py b/tests/test_cr20_auth.pynew file mode 100644index 00000000..f004b6fe--- /dev/null+++ b/tests/test_cr20_auth.py@@ -0,0 +1,275 @@+"""Offline regressions for credential persistence and browser snapshots."""++from __future__ import annotations++import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import time++import pytest++import last30days as cli+from lib import chrome_cookies, cookie_extract, env, setup_wizard, sqlite_snapshot+++SCRIPTS = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts"+++def password_store(tmp_path, monkeypatch):+ store = tmp_path / "dummy password store"+ entry = store / "last30days" / "OPENAI_API_KEY.gpg"+ entry.parent.mkdir(parents=True)+ binary_dir = tmp_path / "bin"+ binary_dir.mkdir()+ calls = tmp_path / "pass-calls.txt"+ binary = binary_dir / "pass"+ binary.write_text(+ f"#!{sys.executable}\n"+ "import os, pathlib, sys\n"+ "args = sys.argv[1:]\n"+ "with open(os.environ['DUMMY_PASS_CALLS'], 'a') as f:\n"+ " f.write(' '.join(args) + '\\n')\n"+ "entry = pathlib.Path(os.environ['PASSWORD_STORE_DIR']) / (args[-1] + '.gpg')\n"+ "if args[0] == 'show':\n"+ " if os.environ.get('DUMMY_DECRYPT_FAILURE') == '1':\n"+ " sys.exit(2)\n"+ " sys.exit(0 if entry.exists() else 1)\n"+ "if args[0] == 'insert':\n"+ " # pass yesno() accepts non-TTY input even without --force.\n"+ " entry.write_text(sys.stdin.read())\n"+ " sys.exit(0)\n"+ "sys.exit(3)\n",+ encoding="utf-8",+ )+ binary.chmod(0o700)+ monkeypatch.setenv("PATH", str(binary_dir) + os.pathsep + os.environ["PATH"])+ monkeypatch.setenv("PASSWORD_STORE_DIR", str(store))+ monkeypatch.setenv("DUMMY_PASS_CALLS", str(calls))+ return entry, calls+++def _run_setup_pass(*args):+ return subprocess.run(+ ["bash", str(SCRIPTS / "setup-pass.sh"), *args, "OPENAI_API_KEY"],+ input="dummy-new-key\n", text=True, capture_output=True, timeout=10,+ )+++def test_pass_decryption_failure_cannot_overwrite_existing_entry(password_store, monkeypatch):+ entry, calls = password_store+ entry.write_text("dummy-original-encrypted-value\n")+ monkeypatch.setenv("DUMMY_DECRYPT_FAILURE", "1")++ result = _run_setup_pass()++ assert entry.read_text() == "dummy-original-encrypted-value\n"+ assert "insert" not in (calls.read_text() if calls.exists() else "")+ assert "skipping" in result.stdout+++def test_pass_missing_entry_is_inserted_without_force(password_store):+ entry, calls = password_store+ result = _run_setup_pass()+ assert result.returncode == 0, result.stderr+ assert entry.read_text() == "dummy-new-key\n"+ assert "added=1 replaced=0" in result.stdout+ assert " -f " not in calls.read_text()+++def test_pass_existing_entry_is_skipped_without_replace(password_store):+ entry, calls = password_store+ entry.write_text("dummy-original-encrypted-value\n")+ result = _run_setup_pass()+ assert result.returncode == 0, result.stderr+ assert entry.read_text() == "dummy-original-encrypted-value\n"+ assert "insert" not in (calls.read_text() if calls.exists() else "")+++def test_pass_explicit_replace_updates_existing_entry(password_store):+ entry, calls = password_store+ entry.write_text("dummy-original-encrypted-value\n")+ result = _run_setup_pass("--replace")+ assert result.returncode == 0, result.stderr+ assert entry.read_text() == "dummy-new-key\n"+ assert "added=0 replaced=1" in result.stdout+ assert "insert -m -f last30days/OPENAI_API_KEY" in calls.read_text()+++def test_pass_entry_created_while_prompting_is_not_overwritten(password_store):+ entry, calls = password_store+ process = subprocess.Popen(+ ["bash", str(SCRIPTS / "setup-pass.sh"), "OPENAI_API_KEY"],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True,+ )+ try:+ assert process.stdout.read(31) == f" {'OPENAI_API_KEY':<28} "+ entry.write_text("dummy-concurrently-created-key\n")+ stdout, stderr = process.communicate("dummy-new-key\n", timeout=10)+ assert process.returncode == 0, stderr+ assert entry.read_text() == "dummy-concurrently-created-key\n"+ assert "insert" not in (calls.read_text() if calls.exists() else "")+ assert "skipping" in stdout+ finally:+ if process.poll() is None:+ process.kill()+ process.communicate()++[email protected]("assignment", [+ "SCRAPECREATORS_API_KEY=",+ 'SCRAPECREATORS_API_KEY=""',+ "export SCRAPECREATORS_API_KEY='' # awaiting signup",+ "SCRAPECREATORS_API_KEY= # awaiting signup",+])+def test_signup_persists_usable_key_over_empty_assignment(tmp_path, monkeypatch, capsys, assignment):+ env_path = tmp_path / ".env"+ env_path.write_text(assignment + "\nSETUP_COMPLETE=true\n")+ monkeypatch.setattr(env, "CONFIG_FILE", env_path)+ monkeypatch.setattr(sys, "argv", ["last30days.py", "setup", "--github"])+ monkeypatch.setattr(setup_wizard, "run_github_auth", lambda: {+ "status": "success", "api_key": "dummy-signup-key-0123456789",+ })++ assert cli.main() == 0++ output = capsys.readouterr()+ assert env.load_env_file(env_path)["SCRAPECREATORS_API_KEY"] == "dummy-signup-key-0123456789"+ assert '"persisted": true' in output.out+ assert "dummy-signup-key-0123456789" not in output.out + output.err+ assert env.load_env_file(env_path)["SETUP_COMPLETE"] == "true"+ assert env_path.read_text().count("SCRAPECREATORS_API_KEY") == 1+ if os.name != "nt":+ assert env_path.stat().st_mode & 0o777 == 0o600+++def test_signup_writer_preserves_nonempty_duplicate_assignment(tmp_path):+ env_path = tmp_path / ".env"+ original = 'SCRAPECREATORS_API_KEY=""\nSCRAPECREATORS_API_KEY=dummy-user-key\n'+ env_path.write_text(original)+ assert setup_wizard.write_api_key(env_path, "dummy-signup-key")+ assert env_path.read_text() == original+ assert env.load_env_file(env_path)["SCRAPECREATORS_API_KEY"] == "dummy-user-key"++[email protected]("browser", ["firefox", "chrome"])+def test_browser_snapshot_reads_committed_wal_without_changing_database(tmp_path, browser):+ database = tmp_path / "cookie database #1.sqlite"+ table = "moz_cookies" if browser == "firefox" else "cookies"+ host = "host" if browser == "firefox" else "host_key"+ connection = sqlite3.connect(database)+ try:+ connection.execute("PRAGMA journal_mode=WAL")+ connection.execute("PRAGMA wal_autocheckpoint=0")+ connection.execute(+ f"CREATE TABLE {table} (name TEXT, value TEXT, {host} TEXT, encrypted_value BLOB)"+ )+ connection.execute(+ f"INSERT INTO {table} VALUES (?, ?, ?, ?)",+ ("auth_token", "dummy-old-cookie", ".x.com", b""),+ )+ connection.commit()+ connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ connection.execute(f"UPDATE {table} SET value = ?", ("dummy-new-cookie",))+ connection.commit()+ connection.execute(f"UPDATE {table} SET value = ?", ("dummy-uncommitted-cookie",))+ wal = database.with_name(database.name + "-wal")+ assert wal.stat().st_size > 0+ before_database, before_wal = database.read_bytes(), wal.read_bytes()++ if browser == "firefox":+ result = cookie_extract._query_cookies_db(database, ".x.com", ["auth_token"])+ else:+ result = chrome_cookies._extract_chromium_cookies_macos(+ database, "Dummy Safe Storage", ".x.com", ["auth_token"]+ )++ assert result == {"auth_token": "dummy-new-cookie"}+ assert database.read_bytes() == before_database+ assert wal.read_bytes() == before_wal+ finally:+ connection.close()++[email protected]("browser", ["firefox", "chrome"])+def test_locked_browser_snapshot_times_out_and_removes_private_copy(tmp_path, monkeypatch, browser):+ database = tmp_path / "locked.sqlite"+ connection = sqlite3.connect(database)+ connection.execute("CREATE TABLE locked (value TEXT)")+ connection.commit()+ connection.execute("BEGIN EXCLUSIVE")+ copies = []++ def bounded_snapshot(source, destination):+ copies.append(Path(destination))+ sqlite_snapshot.copy_snapshot(source, destination, timeout=0.05)++ module = cookie_extract if browser == "firefox" else chrome_cookies+ monkeypatch.setattr(module, "copy_snapshot", bounded_snapshot)+ started = time.monotonic()+ try:+ if browser == "firefox":+ result = cookie_extract._query_cookies_db(database, ".x.com", ["auth_token"])+ else:+ result = chrome_cookies._extract_chromium_cookies_macos(+ database, "Dummy Safe Storage", ".x.com", ["auth_token"]+ )+ assert result is None+ assert time.monotonic() - started < 1+ assert len(copies) == 1+ assert not copies[0].exists()+ finally:+ connection.close()+++def test_snapshot_preserves_source_permission_error(tmp_path, monkeypatch):+ database = tmp_path / "denied.sqlite"+ real_open = Path.open++ def guarded_open(path, *args, **kwargs):+ if path == database:+ raise PermissionError(13, "Permission denied", str(path))+ return real_open(path, *args, **kwargs)++ monkeypatch.setattr(Path, "open", guarded_open)+ with pytest.raises(PermissionError) as error:+ sqlite_snapshot.copy_snapshot(database, str(tmp_path / "copy.sqlite"))+ assert error.value.filename == str(database)++[email protected]("failure", ["missing_table", "malformed_cookie"])+def test_chromium_snapshot_query_failure_removes_wal_sidecars(tmp_path, monkeypatch, failure):+ database = tmp_path / "Cookies"+ copies = tmp_path / "private-copies"+ copies.mkdir()+ real_mkstemp = chrome_cookies.tempfile.mkstemp+ monkeypatch.setattr(+ chrome_cookies.tempfile, "mkstemp",+ lambda **kwargs: real_mkstemp(dir=copies, **kwargs),+ )+ connection = sqlite3.connect(database)+ try:+ connection.execute("PRAGMA journal_mode=WAL")+ connection.execute("PRAGMA wal_autocheckpoint=0")+ if failure == "missing_table":+ connection.execute("CREATE TABLE other (value TEXT)")+ else:+ connection.execute(+ "CREATE TABLE cookies (name TEXT, value TEXT, host_key TEXT, encrypted_value BLOB)"+ )+ connection.execute(+ "INSERT INTO cookies VALUES (?, ?, ?, ?)", ("auth_token", "", ".x.com", 42)+ )+ connection.commit()++ assert chrome_cookies._extract_chromium_cookies_macos(+ database, "Dummy Safe Storage", ".x.com", ["auth_token"]+ ) is None++ assert list(copies.iterdir()) == []+ finally:+ connection.close()diff --git a/tests/test_cr20_entrypoints.py b/tests/test_cr20_entrypoints.pynew file mode 100644index 00000000..0a0c6f2c--- /dev/null+++ b/tests/test_cr20_entrypoints.py@@ -0,0 +1,343 @@+import json+import sys+from unittest import mock++import pytest++import last30days as cli+from lib import hosted, setup_wizard+from tests.test_last_run_state import _diag, _report+from tests.competitor_cli_audit_helpers import run_competitor_cli++[email protected]("topic", [+ "setup", "doctor", "library feed", "library search example", "queue list",+ "queue cover example", "ordinary research", "--mock",+])+def test_research_only_dispatches_reserved_topics_as_research(monkeypatch, topic, capsys):+ research = mock.Mock(side_effect=lambda **kwargs: _report(kwargs["topic"]))+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())+ for name in ("_run_library_feed", "_run_library_search", "_run_queue_list", "_run_queue_cover"):+ monkeypatch.setattr(cli, name, mock.Mock(side_effect=AssertionError("administrative dispatch")))+ monkeypatch.setattr(setup_wizard, "run_auto_setup", mock.Mock(side_effect=AssertionError("setup invoked")))+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "--research-only", "--emit=json", "--json-profile=raw", "--mock",+ "--no-browser-cookies", "--save-dir", "", "--", topic,+ ])++ assert cli.main() == 0+ research.assert_called_once()+ assert research.call_args.kwargs["topic"] == topic+ assert json.loads(capsys.readouterr().out)["topic"] == topic+ assert not cli.env.CONFIG_FILE.exists()+++def test_explicit_setup_still_dispatches(monkeypatch, capsys):+ setup = mock.Mock(return_value={})+ monkeypatch.setattr(setup_wizard, "run_auto_setup", setup)+ monkeypatch.setattr(sys, "argv", ["last30days.py", "setup", "--no-browser-cookies"])++ assert cli.main() == 0+ setup.assert_called_once()+ assert cli.env.CONFIG_FILE.exists()+++def test_main_dedicated_subreddits_do_not_leak_to_peers(monkeypatch, tmp_path):+ observed = run_competitor_cli(+ monkeypatch, tmp_path,+ args=["--dedicated-subreddits", "MainHome", "--subreddits", "MainCategory"],+ config={"BRAVE_API_KEY": "dummy-brave-key"}, has_backend=True,+ resolutions={"PeerOne": {"subreddits": ["PeerHome"]}, "PeerTwo": {}},+ )++ assert observed.calls["MainBrand"]["config"]["_dedicated_subreddits"] == ["MainHome"]+ assert observed.calls["MainBrand"]["subreddits"] == ["MainCategory"]+ assert observed.calls["PeerOne"]["subreddits"] == ["PeerHome"]+ assert observed.calls["PeerTwo"]["subreddits"] is None+ for peer in ("PeerOne", "PeerTwo"):+ assert "_dedicated_subreddits" not in observed.calls[peer]["config"]++[email protected]("window, cached_from, reuse", [+ ([], "2026-05-01", False),+ (["--days=30", "--as-of=2026-05-31"], "2026-05-01", True),+ (["--days=7", "--as-of=2026-05-31"], "2026-05-01", False),+ (["--days=30", "--as-of=2020-01-31"], "2026-05-01", False),+ pytest.param(["--days=0", "--as-of=2026-05-31"], "2026-05-01", False, id="zero-days-rejects-thirty-day-cache"),+ pytest.param(["--days=0", "--as-of=2026-05-31"], "2026-05-31", True, id="zero-days-reuses-same-day-cache"),+])+def test_html_cache_respects_requested_window(monkeypatch, tmp_path, window, cached_from, reuse, capsys):+ report = _report("OpenClaw")+ report.range_from, report.range_to = cached_from, "2026-05-31"+ monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: {})+ assert cli._write_last_run(report.topic, report)+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("# Cached synthesis", encoding="utf-8")+ research = mock.Mock(return_value=report)+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "OpenClaw", "--emit=html", "--synthesis-file", str(synthesis), *window,+ ])++ assert cli.main() == 0+ assert research.call_count == (0 if reuse else 1)+ if "--days=0" in window and not reuse:+ assert research.call_args.kwargs["lookback_days"] == 0+ assert ("Reusing cached report" in capsys.readouterr().err) == reuse+++def test_comparison_html_cache_survives_plan_cleanup(monkeypatch, tmp_path, capsys):+ plan = tmp_path / "competitors.json"+ plan.write_text(json.dumps({"PeerOne": {"subreddits": ["peerone"]}}), encoding="utf-8")+ run_competitor_cli(monkeypatch, tmp_path, args=["--competitors-plan", str(plan)])+ plan.unlink()+ capsys.readouterr()+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("# Comparison synthesis\n\nMainBrand and peers.", encoding="utf-8")+ research = mock.Mock(side_effect=AssertionError("cached export must not research"))+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "MainBrand", "--cached-report", "--emit=html",+ "--synthesis-file", str(synthesis),+ ])++ assert cli.main() == 0+ output = capsys.readouterr().out+ assert "Comparison synthesis" in output+ assert "PeerOne" in output and "PeerTwo" in output+ research.assert_not_called()++[email protected]("expired", [False, True])+def test_cache_only_export_does_not_fall_back_to_research(monkeypatch, tmp_path, expired):+ if expired:+ assert cli._write_last_run("OpenClaw", _report("OpenClaw"))+ path = cli.env.CONFIG_DIR / "last-report.json"+ payload = json.loads(path.read_text())+ payload["timestamp"] = "2020-01-01T00:00:00+00:00"+ path.write_text(json.dumps(payload))+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("Existing synthesis", encoding="utf-8")+ research = mock.Mock(side_effect=AssertionError("unexpected research"))+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "OpenClaw", "--cached-report", "--emit=html",+ "--synthesis-file", str(synthesis),+ ])++ assert cli.main() == 2+ research.assert_not_called()++[email protected]("initial, followup, reused", [+ (["--search=reddit"], ["--search=reddit"], True),+ (["--search=reddit"], ["--search=x"], False),+ (["--subreddits=Home"], ["--subreddits=Other"], False),+ ([], ["--hiring-signals"], False),+ (["--web-backend=none"], ["--web-backend=auto"], False),+])+def test_cache_matches_explicit_research_scope(monkeypatch, tmp_path, initial, followup, reused):+ report = _report("OpenClaw")+ research = mock.Mock(return_value=report)+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")+ monkeypatch.setattr(sys, "argv", ["last30days.py", "OpenClaw", *initial])+ assert cli.main() == 0+ research.reset_mock()+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("Existing synthesis", encoding="utf-8")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "OpenClaw", "--emit=html", "--synthesis-file", str(synthesis), *followup,+ ])++ assert cli.main() == 0+ assert research.call_count == (0 if reused else 1)+++def test_cache_matches_plan_content_not_temporary_filename(monkeypatch, tmp_path):+ plan = tmp_path / "plan.json"+ plan.write_text(json.dumps({"subqueries": [{"search_query": "first"}]}))+ options = cli._cache_research_options(cli.build_parser().parse_args(["OpenClaw", "--plan", str(plan)]))+ assert cli._write_last_run("OpenClaw", _report("OpenClaw"), research_options=options)+ same_plan = tmp_path / "new-plan.json"+ same_plan.write_text(plan.read_text())+ same_options = cli._cache_research_options(cli.build_parser().parse_args(["OpenClaw", "--plan", str(same_plan)]))+ assert cli._load_last_report_cache("OpenClaw", research_options=same_options)+ plan.write_text(json.dumps({"subqueries": [{"search_query": "different"}]}))+ changed_options = cli._cache_research_options(cli.build_parser().parse_args(["OpenClaw", "--plan", str(plan)]))+ assert cli._load_last_report_cache("OpenClaw", research_options=changed_options) is None++[email protected]("cached", [False, True])+def test_cached_export_never_calls_hosted_research(monkeypatch, tmp_path, cached, capsys):+ if cached:+ assert cli._write_last_run("OpenClaw", _report("OpenClaw"))+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("# Stored report export", encoding="utf-8")+ remote = mock.Mock(return_value=123)+ local = mock.Mock(side_effect=AssertionError("unexpected local research"))+ monkeypatch.setattr(hosted, "run_hosted", remote)+ monkeypatch.setattr(cli.pipeline, "run", local)+ monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key")+ monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example.test")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "OpenClaw", "--cached-report", "--emit=html",+ "--synthesis-file", str(synthesis),+ ])++ assert cli.main() == (0 if cached else 2)+ remote.assert_not_called()+ local.assert_not_called()+ if cached:+ assert "Stored report export" in capsys.readouterr().out+++def test_ordinary_synthesis_rejects_changed_source_exclusions(monkeypatch, tmp_path):+ config = {"EXCLUDE_SOURCES": "reddit", "SCRAPECREATORS_API_KEY": "dummy-private-key"}+ monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: dict(config))+ research = mock.Mock(side_effect=lambda **kwargs: _report(kwargs["topic"]))+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")+ monkeypatch.setattr(sys, "argv", ["last30days.py", "OpenClaw"])+ assert cli.main() == 0+ assert "dummy-private-key" not in (cli.env.CONFIG_DIR / "last-report.json").read_text()+ research.reset_mock()+ config["EXCLUDE_SOURCES"] = "x"+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("Stored synthesis", encoding="utf-8")+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "OpenClaw", "--emit=html", "--synthesis-file", str(synthesis),+ ])++ assert cli.main() == 0+ research.assert_called_once()+ assert research.call_args.kwargs["config"]["EXCLUDE_SOURCES"] == "x"++[email protected]("other_mode", ["--welcome", "--preflight", "--discover=ai", "--verify-freshness"])+def test_cache_only_rejects_other_modes_before_dispatch(monkeypatch, tmp_path, other_mode):+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("Stored synthesis", encoding="utf-8")+ monkeypatch.setattr(cli.env, "get_config", mock.Mock(side_effect=AssertionError("dispatch began")))+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "OpenClaw", "--cached-report", "--emit=html", "--synthesis-file", str(synthesis), other_mode,+ ])++ with pytest.raises(SystemExit) as exc:+ cli.main()+ assert exc.value.code == 2+++def test_cache_only_without_topic_rejects_freshness_before_dispatch(monkeypatch, tmp_path):+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("Stored synthesis", encoding="utf-8")+ monkeypatch.setattr(cli.env, "get_config", mock.Mock(side_effect=AssertionError("dispatch began")))+ monkeypatch.setattr(cli, "_run_cached_freshness", mock.Mock(side_effect=AssertionError("freshness dispatched")))+ monkeypatch.setattr(sys, "argv", [+ "last30days.py", "--cached-report", "--emit=html", "--synthesis-file", str(synthesis), "--verify-freshness",+ ])++ with pytest.raises(SystemExit) as exc:+ cli.main()+ assert exc.value.code == 2+++def corpus_cache_cli(monkeypatch, tmp_path):+ projects = {name: tmp_path / name for name in ("project-a", "project-b")}+ for name, directory in projects.items():+ notes = directory / "notes"+ notes.mkdir(parents=True)+ (notes / "mcp.md").write_text(+ f"MCP servers provide local tools and resources. Private notes from {name}.",+ encoding="utf-8",+ )+ synthesis = tmp_path / "synthesis.md"+ synthesis.write_text("# MCP server synthesis", encoding="utf-8")+ config = {}+ research = mock.Mock(wraps=cli.pipeline.run)+ monkeypatch.setattr(cli.pipeline, "run", research)+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())+ monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: dict(config))+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")++ def run(project, *, cli_path=None, config_path=None, synthesize=False, cached_only=False):+ monkeypatch.chdir(projects[project])+ config.clear()+ if config_path is not None:+ config["LAST30DAYS_CORPUS_DIRS"] = config_path+ argv = [+ "last30days.py", "MCP servers", "--mock", "--quick", "--search=corpus",+ "--no-browser-cookies", "--corpus-all-time", "--save-dir=",+ ]+ if cli_path is not None:+ argv += ["--corpus", cli_path]+ if synthesize:+ argv += ["--emit=html", "--synthesis-file", str(synthesis)]+ else:+ argv += ["--emit=json", "--json-profile=raw"]+ if cached_only:+ argv.append("--cached-report")+ monkeypatch.setattr(sys, "argv", argv)+ return cli.main()++ return projects, research, run++[email protected]("configured", [False, True], ids=["cli", "config"])+def test_relative_corpus_cache_cannot_cross_project_directories(corpus_cache_cli, configured, capsys):+ projects, research, run = corpus_cache_cli+ scope = {"config_path" if configured else "cli_path": "notes"}+ assert run("project-a", **scope) == 0+ first = json.loads(capsys.readouterr().out)+ assert "project-a" in first["items_by_source"]["corpus"][0]["body"]+ research.reset_mock()++ assert run("project-b", synthesize=True, **scope) == 0+ research.assert_called_once()+ assert research.call_args.kwargs["config"]["_CORPUS_DIRS"] == [str(projects["project-b"] / "notes")]+ stored = json.loads((cli.env.CONFIG_DIR / "last-report.json").read_text())+ assert "project-b" in stored["reports"][0]["report"]["items_by_source"]["corpus"][0]["body"]++[email protected]("initial_layer, followup_layer", [+ ("cli_path", "cli_path"), ("config_path", "config_path"),+ ("config_path", "cli_path"), ("cli_path", "config_path"),+])+def test_corpus_cache_matches_effective_paths_across_aliases_and_layers(+ corpus_cache_cli, initial_layer, followup_layer,+):+ projects, research, run = corpus_cache_cli+ assert run("project-a", **{initial_layer: "notes"}) == 0+ research.reset_mock()++ assert run("project-b", synthesize=True, **{followup_layer: str(projects["project-a"] / "notes")}) == 0+ research.assert_not_called()++[email protected]("explicit, configured, expected", [+ (None, "notes", 0),+ ("notes", None, 2),+ ("absolute-a", None, 0),+ ("absolute-a", "notes", 2),+])+def test_cached_export_corpus_override_matches_effective_directories(+ corpus_cache_cli, explicit, configured, expected,+):+ projects, research, run = corpus_cache_cli+ assert run("project-a", config_path="notes") == 0+ research.reset_mock()+ if explicit == "absolute-a":+ explicit = str(projects["project-a"] / "notes")++ assert run("project-b", cli_path=explicit, config_path=configured, synthesize=True, cached_only=True) == expected+ research.assert_not_called()diff --git a/tests/test_cr20_evidence.py b/tests/test_cr20_evidence.pynew file mode 100644index 00000000..e274670e--- /dev/null+++ b/tests/test_cr20_evidence.py@@ -0,0 +1,69 @@+import pytest++from lib import cluster, fusion, normalize, render, rerank, schema, signals++[email protected]("source, field, value", [+ ("youtube", "transcript_highlights", ["{entity} handles long sessions well."]),+ ("youtube", "transcript_snippet", "A detailed review of {entity}."),+ ("youtube", "top_comments", [{"text": "I use {entity} every day.", "likes": 25}]),+ ("reddit", "comment_insights", ["The discussion recommends {entity}."]),+ ("reddit", "top_comments", [{"excerpt": "{entity} works well.", "score": 25}]),+])[email protected]("entity, grounded", [("Hermes Agent", True), ("Unrelated Toolkit", False)])+def test_retained_enrichment_controls_entity_grounding_and_visible_evidence(+ source, field, value, entity, grounded,+):+ import json++ enrichment = json.loads(json.dumps(value).replace("{entity}", entity))+ items = normalize.normalize_source_items(+ source,+ [{+ "id": "weekly-notes",+ "title": "Weekly field notes",+ "url": "https://example.com/weekly-notes",+ "date": "2026-10-20",+ "engagement": {"views": 1000000, "score": 100},+ field: enrichment,+ }],+ "2026-09-22", "2026-10-22",+ )+ items[0].metadata["unrelated_provider_field"] = "Hermes Agent"+ plan = schema.QueryPlan(+ intent="research", freshness_mode="balanced_recent", cluster_mode="none",+ raw_topic="Hermes Agent",+ subqueries=[schema.SubQuery(+ label="primary", search_query="Hermes Agent", ranking_query="Hermes Agent",+ sources=[source],+ )],+ source_weights={source: 1.0},+ )+ items = signals.annotate_stream(+ items, "Hermes Agent", plan.freshness_mode, reference_date="2026-10-22",+ )+ candidates = fusion.weighted_rrf(+ {("primary", source): items}, plan, pool_limit=10,+ range_from="2026-09-22", range_to="2026-10-22",+ )+ ranked = rerank.rerank_candidates(+ topic="Hermes Agent", plan=plan, candidates=candidates,+ provider=None, model=None, shortlist_size=10,+ )+ report = schema.Report(+ topic="Hermes Agent", range_from="2026-09-22", range_to="2026-10-22",+ generated_at="2026-10-22T12:00:00Z",+ provider_runtime=schema.ProviderRuntime(+ reasoning_provider=None, planner_model=None, rerank_model=None,+ ),+ query_plan=plan, ranked_candidates=ranked,+ clusters=cluster.cluster_candidates(ranked, plan),+ items_by_source={source: items}, errors_by_source={},+ )++ text = render.render_compact(report)++ assert len(ranked) == 1+ assert ("entity-miss" not in ranked[0].explanation) is grounded+ assert ("Weekly field notes" in text) is grounded+ assert ("Nothing solid this window" not in text) is groundeddiff --git a/tests/test_cr20_pipeline.py b/tests/test_cr20_pipeline.pynew file mode 100644index 00000000..fb005e41--- /dev/null+++ b/tests/test_cr20_pipeline.py@@ -0,0 +1,217 @@+import pytest++from lib import env, pipeline, reddit, reddit_public, render++[email protected]("excluded", [False, True])[email protected]("selection", ["automatic", "requested", "hiring", "host-plan"])+def test_jobs_dispatch_respects_exclusion(monkeypatch, excluded, selection):+ dispatched = []++ def retrieve(**kwargs):+ dispatched.append(kwargs["source"])+ return [], {}++ monkeypatch.setattr(pipeline, "_retrieve_stream", retrieve)+ monkeypatch.setattr(pipeline, "which", lambda _name: None)+ config = {"EXCLUDE_SOURCES": "jobs"} if excluded else {}+ requested = ["reddit", "jobs"] if selection == "requested" else None+ if selection == "hiring":+ requested = ["reddit"]+ external_plan = None+ if selection == "host-plan":+ external_plan = {+ "intent": "research",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "topic",+ "subqueries": [{+ "label": "primary",+ "search_query": "OpenAI",+ "ranking_query": "OpenAI",+ "sources": ["reddit", "jobs"],+ }],+ }++ report = pipeline.run(+ topic="OpenAI",+ config=config,+ depth="quick",+ requested_sources=requested,+ hiring_signals_mode=selection == "hiring",+ external_plan=external_plan,+ web_backend="none",+ )++ assert "reddit" in dispatched+ assert ("jobs" in dispatched) is not excluded+ assert any("jobs" in sq.sources for sq in report.query_plan.subqueries) is not excluded+ assert any(status.source == "jobs" and status.attempted for status in report.source_status.values()) is not excluded+++def test_jobs_only_hiring_run_rejects_excluded_source_before_dispatch(monkeypatch):+ dispatched = []++ def retrieve(**kwargs):+ dispatched.append(kwargs["source"])+ return [], {}++ monkeypatch.setattr(pipeline, "_retrieve_stream", retrieve)+ with pytest.raises(RuntimeError, match="No sources are available"):+ pipeline.run(+ topic="OpenAI",+ config={"EXCLUDE_SOURCES": "jobs"},+ depth="quick",+ hiring_signals_mode=True,+ web_backend="none",+ )+ assert dispatched == []++[email protected]("include_match", [False, True])[email protected]("filter_kind", ["topic", "keywords"])+def test_polymarket_rejections_are_absent_from_fusion_and_output(+ monkeypatch, filter_kind, include_match,+):+ topic = "Hermes vs OpenClaw" if filter_kind == "topic" else "Warriors"+ rejected_title = "Glasgow Warriors rugby championship"+ accepted_title = "Hermes launch by December?" if filter_kind == "topic" else "Warriors win NBA finals?"+ rejected = {+ "id": "rugby",+ "title": rejected_title,+ "url": "https://polymarket.com/event/glasgow-rugby",+ "date": "2026-10-01",+ "volume1mo": 100000,+ "relevance": 1.0,+ }+ accepted = {+ "id": "accepted",+ "title": accepted_title,+ "url": "https://polymarket.com/event/relevant-market",+ "date": "2026-10-01",+ "volume1mo": 100000,+ "relevance": 1.0,+ }+ markets = [rejected, accepted] if include_match else [rejected]+ monkeypatch.setattr(pipeline, "_retrieve_stream", lambda **_kwargs: (markets, {}))+ fused_titles = []+ weighted_rrf = pipeline.weighted_rrf++ def observe_fusion(streams, *args, **kwargs):+ fused_titles.extend(item.title for items in streams.values() for item in items)+ return weighted_rrf(streams, *args, **kwargs)++ monkeypatch.setattr(pipeline, "weighted_rrf", observe_fusion)+ config = {"_polymarket_keywords": ["nba", "gsw"]} if filter_kind == "keywords" else {}+ report = pipeline.run(+ topic=topic,+ config=config,+ depth="default",+ requested_sources=["polymarket"],+ web_backend="none",+ as_of_date="2026-10-22",+ external_plan={+ "intent": "research",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "topic",+ "subqueries": [{+ "label": label,+ "search_query": "Warriors Hermes",+ "ranking_query": "Warriors Hermes",+ "sources": ["polymarket"],+ } for label in ("primary", "secondary")],+ },+ )++ expected = {accepted_title} if include_match else set()+ assert {item.title for item in report.items_by_source["polymarket"]} == expected+ assert set(fused_titles) == expected+ assert {candidate.title for candidate in report.ranked_candidates} == expected+ assert report.source_status["polymarket"].items_returned == len(expected)+ assert rejected_title not in render.render_compact(report)++[email protected]("freshness_mode", ["strict_recent", "balanced_recent", "evergreen_ok"])[email protected]("sc_date", ["2026-08-01", "2026-09-22", "2026-10-22", None])+def test_reddit_sc_date_filter_precedes_enrichment_and_public_fallback(+ monkeypatch, freshness_mode, sc_date,+):+ comment_requests = []+ public_requests = []+ stale_url = "https://www.reddit.com/r/music/comments/stale/old_contract/"+ recent_url = "https://www.reddit.com/r/music/comments/current/tour_schedule/"+ public_url = "https://www.reddit.com/r/music/comments/public/album_release/"+ sc_posts = [{+ "id": "stale",+ "title": "Kanye old contract dispute",+ "url": stale_url,+ "created_at": "2026-08-01",+ "subreddit": "music",+ "score": 100,+ "num_comments": 20,+ }, {+ "id": "current",+ "title": "Kanye new tour schedule released",+ "url": recent_url,+ "created_at": sc_date,+ "subreddit": "music",+ "score": 80,+ "num_comments": 10,+ }]++ def sc_response(url, **kwargs):+ assert url.startswith(reddit.SCRAPECREATORS_BASE)+ if url.endswith("/post/comments"):+ comment_requests.append(kwargs["params"]["url"])+ return {"comments": [{+ "body": "Kanye tour dates match the newly announced schedule.",+ "author": "dummy-fan",+ "score": 12,+ "created_utc": 1791504000,+ }]}+ assert url.endswith("/search")+ return {"posts": sc_posts}++ def public_response(*args, **kwargs):+ public_requests.append((args, kwargs))+ return [{+ "id": "public",+ "title": "Kanye album release announced",+ "url": public_url,+ "date": "2026-10-01",+ "subreddit": "music",+ "engagement": {"score": 100, "num_comments": 20},+ "relevance": 1.0,+ }]++ monkeypatch.setattr(reddit.http, "get", sc_response)+ monkeypatch.setattr(reddit_public, "search_reddit_public", public_response)+ report = pipeline.run(+ topic="Kanye",+ config={+ "SCRAPECREATORS_API_KEY": "dummy-scrapecreators-key",+ env.REDDIT_BACKEND_PIN_VAR: "scrapecreators",+ },+ depth="quick",+ requested_sources=["reddit"],+ web_backend="none",+ as_of_date="2026-10-22",+ external_plan={+ "intent": "research",+ "freshness_mode": freshness_mode,+ "cluster_mode": "topic",+ "subqueries": [{+ "label": "primary",+ "search_query": "Kanye",+ "ranking_query": "Kanye",+ "sources": ["reddit"],+ }],+ },+ )++ all_stale = sc_date == "2026-08-01"+ expected_url = public_url if all_stale else recent_url+ assert {item.url for item in report.items_by_source["reddit"]} == {expected_url}+ assert bool(public_requests) is all_stale+ assert comment_requests == ([] if all_stale else [recent_url])+ if not all_stale:+ assert report.items_by_source["reddit"][0].metadata["top_comments"][0]["score"] == 12diff --git a/tests/test_cr20_resolve.py b/tests/test_cr20_resolve.pynew file mode 100644index 00000000..0149350e--- /dev/null+++ b/tests/test_cr20_resolve.py@@ -0,0 +1,156 @@+from pathlib import Path+from urllib.parse import parse_qs, urlparse++import pytest++from lib import competitors, dates, grounding, resolve+from tests.skill_contract import reference_text++[email protected](autouse=True)+def _first_party_modules():+ scripts = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts"+ assert Path(grounding.__file__).resolve().is_relative_to(scripts)+ assert Path(resolve.__file__).resolve().is_relative_to(scripts)++[email protected]("key", ["OPENROUTER_API_KEY", "PERPLEXITY_API_KEY"])[email protected]("native_search", ["0", "1"])+def test_unsupported_search_credentials_do_not_claim_autoresolve(+ monkeypatch, capsys, key, native_search,+):+ config = {key: "dummy-key", "LAST30DAYS_NATIVE_SEARCH": native_search}++ def unexpected_request(*args, **kwargs):+ pytest.fail("Unsupported search credentials must not trigger requests")++ monkeypatch.setattr(grounding.http, "request", unexpected_request)+ monkeypatch.setattr(grounding.http, "get_text", unexpected_request)+ result = resolve.auto_resolve("Widgetworks", config)++ assert not resolve._has_backend(config)+ assert result["searches_run"] == 0+ assert result["subreddits"] == []+ assert "No web search backend available" in capsys.readouterr().err+ assert competitors.discover_competitors("Widgetworks", 2, config) == []++[email protected]("backend,key", [+ ("brave", "BRAVE_API_KEY"),+ ("exa", "EXA_API_KEY"),+ ("serper", "SERPER_API_KEY"),+ ("parallel", "PARALLEL_API_KEY"),+])+def test_supported_search_credentials_resolve_through_real_dispatcher(+ monkeypatch, backend, key,+):+ calls = []++ def request(method, url, **kwargs):+ calls.append((method, url))+ body = kwargs.get("json_data", {})+ query = (+ parse_qs(urlparse(url).query).get("q", [""])[0]+ or body.get("query")+ or body.get("q")+ or (body.get("search_queries") or [""])[0]+ )+ if "subreddit" in query:+ title, snippet = "r/widgetworks discussion", "Community updates"+ elif "handle" in query:+ title, snippet = "Widgetworks on X", "Follow @widgetworks"+ else:+ title, snippet = "Widgetworks update", "Widgetworks announced a new product."+ item = {+ "title": title,+ "url": "https://example.org/article",+ "link": "https://example.org/article",+ "description": snippet,+ "snippet": snippet,+ "text": snippet,+ "excerpts": [snippet],+ }+ return {"web": {"results": [item]}, "results": [item], "organic": [item]}++ monkeypatch.setattr(grounding.http, "request", request)+ config = {key: "dummy-key", "LAST30DAYS_NATIVE_SEARCH": "1"}+ result = resolve.auto_resolve("Widgetworks", config)++ assert resolve._has_backend(config)+ assert result["searches_run"] == 4+ assert result["subreddits"] == ["widgetworks"]+ assert result["x_handle"] == "widgetworks"+ assert "announced a new product" in result["context"]+ assert len(calls) == 4+ assert all(backend in url for _, url in calls)+++def test_non_latin_auto_search_uses_available_exa_without_brave(monkeypatch):+ calls = []++ def request(method, url, **kwargs):+ calls.append((method, url, kwargs))+ return {"results": [{+ "title": "קפה עלית",+ "url": "https://example.org/coffee",+ "text": "עדכונים על קפה עלית",+ }]}++ monkeypatch.setattr(grounding.http, "request", request)+ topic = "קפה עלית"+ items, artifact = grounding.web_search(+ topic, dates.get_date_range(30), {"EXA_API_KEY": "dummy-key"},+ )++ assert artifact["label"] == "exa"+ assert items[0]["title"] == topic+ assert calls[0][1] == "https://api.exa.ai/search"+ assert calls[0][2]["json_data"]["query"] == topic+++def test_non_latin_auto_search_keeps_keyless_floor(monkeypatch):+ html = (+ '<a class="result__a" href="https://example.org/coffee">קפה עלית</a>'+ '<a class="result__snippet">עדכונים על קפה עלית</a>'+ )+ monkeypatch.setattr(grounding.http, "get_text", lambda *args, **kwargs: html)+ items, artifact = grounding.web_search("קפה עלית", dates.get_date_range(30), {})+ assert items[0]["title"] == "קפה עלית"+ assert artifact["keyless_backend"] == "ddg"+++def test_native_search_host_does_not_start_keyless_search(monkeypatch):+ def unexpected_request(*args, **kwargs):+ pytest.fail("Native-search hosts supply their own web results")++ monkeypatch.setattr(grounding.http, "get_text", unexpected_request)+ assert grounding.web_search(+ "קפה עלית", dates.get_date_range(30), {"LAST30DAYS_NATIVE_SEARCH": "1"},+ ) == ([], {})+++def test_explicit_unavailable_backend_still_reports_configuration_error():+ with pytest.raises(RuntimeError, match="BRAVE_API_KEY is required"):+ grounding.web_search(+ "קפה עלית", dates.get_date_range(30), {"EXA_API_KEY": "dummy-key"},+ backend="brave",+ )+++def test_non_latin_runbook_preserves_available_backend_selection():+ runbook = reference_text("research-runbook")+ section = runbook.split("**Class 5:", 1)[1].split("**Pre-Flight decision flow", 1)[0]+ assert "Leave `--web-backend` unset" in section+ assert "host's native web search" in section+ assert "Never force `--web-backend brave`" in section+ assert "Force `--web-backend brave`" not in section+ assert "| `--web-backend brave` | Step 0.45 Class 5 |" not in runbook+++def test_competitor_instructions_only_claim_supported_search_backends():+ text = reference_text("competitors")+ capability = text.split("**Engine-internal auto-resolve:**", 1)[1].split("\n", 1)[0]+ for key in ("BRAVE_API_KEY", "EXA_API_KEY", "SERPER_API_KEY", "PARALLEL_API_KEY"):+ assert key in capability+ assert "PERPLEXITY_API_KEY" not in capability+ assert "OPENROUTER_API_KEY" not in capabilitydiff --git a/tests/test_cr20_sources.py b/tests/test_cr20_sources.pynew file mode 100644index 00000000..b5505285--- /dev/null+++ b/tests/test_cr20_sources.py@@ -0,0 +1,238 @@+import json+import re+import subprocess+from datetime import datetime+from pathlib import Path+from urllib.parse import parse_qs, urlsplit++import pytest++from lib import dates, grok_x, subproc, trustpilot, web_search_keyless, xquik+++def test_adapters_are_imported_from_this_checkout():+ scripts = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts"+ for module in (dates, grok_x, trustpilot, web_search_keyless, xquik):+ assert Path(module.__file__).resolve().is_relative_to(scripts)+++def _grok_query(cmd):+ prompt = cmd[cmd.index("-p") + 1]+ prefix = "Query (JSON string literal): "+ return json.loads(next(line[len(prefix):] for line in prompt.splitlines() if line.startswith(prefix)))+++def _search_grok(lane, start, end):+ if lane == "topic":+ return grok_x.search_x("boundary subject", start, end, depth="deep")["items"]+ if lane == "from":+ return grok_x.search_handles(["subject"], "boundary subject", start, end)[0]+ if lane == "from-topic":+ return grok_x.search_handles(["subject"], "boundary subject", start, end, and_topic=True)[0]+ if lane == "mentions":+ return grok_x.search_mentions(["subject"], start, end)[0]+ return grok_x.search_name("Boundary Subject", start, end)[0]+++def _search_xquik(lane, start, end):+ if lane == "topic":+ return xquik.search_xquik("boundary subject", start, end, depth="deep", token="dummy-key")["items"]+ if lane == "from":+ return xquik.search_handles(["subject"], "boundary subject", start, end, token="dummy-key")+ return xquik.search_mentions(["subject"], start, end, token="dummy-key")++[email protected]("lane", ["topic", "from", "from-topic", "mentions", "name"])[email protected]("end,exclusive", [+ ("2024-02-29", "2024-03-01"),+ ("2024-12-31", "2025-01-01"),+ ("9999-12-30", "9999-12-31"),+ ("9999-12-31", None),+])+def test_grok_all_lanes_request_the_inclusive_end_date(monkeypatch, lane, end, exclusive):+ queries = []++ def run(cmd, **kwargs):+ queries.append(_grok_query(cmd))+ return subprocess.CompletedProcess(cmd, 0, "[]", "")++ monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok")+ monkeypatch.setattr(grok_x, "_check_cli_version", lambda *args: None)+ monkeypatch.setattr(grok_x.subprocess, "run", run)+ _search_grok(lane, "2024-02-01", end)+ assert queries+ for query in queries:+ assert "since:2024-02-01" in query.split()+ assert [part for part in query.split() if part.startswith("until:")] == (+ [f"until:{exclusive}"] if exclusive else []+ )++[email protected]("lane", ["topic", "from", "mentions"])[email protected]("end,exclusive", [+ ("2024-02-29", "2024-03-01"),+ ("2024-12-31", "2025-01-01"),+ ("9999-12-30", "9999-12-31"),+ ("9999-12-31", None),+])+def test_xquik_all_lanes_request_the_inclusive_end_date(monkeypatch, lane, end, exclusive):+ queries = []++ def get(url, **kwargs):+ queries.append(parse_qs(urlsplit(url).query)["q"][0])+ return {"tweets": []}++ monkeypatch.setattr(xquik.http, "get", get)+ _search_xquik(lane, "2024-02-01", end)+ assert queries+ for query in queries:+ assert "since:2024-02-01" in query.split()+ assert [part for part in query.split() if part.startswith("until:")] == (+ [f"until:{exclusive}"] if exclusive else []+ )+++def _snowflake(timestamp):+ instant = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))+ return str((int(instant.timestamp() * 1000) - 1288834974657) << 22)++[email protected]("adapter,lane", [+ ("grok", "topic"), ("grok", "from"), ("grok", "from-topic"),+ ("grok", "mentions"), ("grok", "name"),+ ("xquik", "topic"), ("xquik", "from"), ("xquik", "mentions"),+])+def test_x_adapters_retain_final_day_but_not_following_day(monkeypatch, adapter, lane):+ timestamps = ["2024-02-29T23:59:59.999Z", "2024-03-01T00:00:00Z"]+ handle = "subject" if lane.startswith("from") else "observer"++ def matching(query):+ match = re.search(r"\buntil:(\d{4}-\d{2}-\d{2})\b", query)+ return [stamp for stamp in timestamps if match is None or stamp[:10] < match.group(1)]++ def grok_run(cmd, **kwargs):+ posts = [+ {"url": f"https://x.com/{handle}/status/{_snowflake(stamp)}", "text": "boundary subject", "likes": 10}+ for stamp in matching(_grok_query(cmd))+ ]+ return subprocess.CompletedProcess(cmd, 0, json.dumps(posts), "")++ def xquik_get(url, **kwargs):+ query = parse_qs(urlsplit(url).query)["q"][0]+ return {"tweets": [+ {"id": _snowflake(stamp), "author": {"username": handle}, "text": "boundary subject", "createdAt": stamp}+ for stamp in matching(query)+ ]}++ monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok")+ monkeypatch.setattr(grok_x, "_check_cli_version", lambda *args: None)+ monkeypatch.setattr(grok_x.subprocess, "run", grok_run)+ monkeypatch.setattr(xquik.http, "get", xquik_get)+ search = _search_grok if adapter == "grok" else _search_xquik+ items = search(lane, "2024-02-01", "2024-02-29")+ assert [item["url"] for item in items] == [f"https://x.com/{handle}/status/{_snowflake(timestamps[0])}"]+++def test_grok_validates_the_whole_inclusive_day():+ timestamps = ["2024-02-29T23:59:59.999Z", "2024-03-01T00:00:00Z"]+ posts = [+ {"url": f"https://x.com/observer/status/{_snowflake(stamp)}", "text": "boundary subject", "likes": 10, "created_at": stamp}+ for stamp in timestamps+ ]+ items = grok_x.parse_x_response({"text": json.dumps(posts)}, "boundary subject", "2024-02-01", "2024-02-29")+ assert [item["date"] for item in items] == ["2024-02-29"]+++def trustpilot_cli(monkeypatch):+ calls = []+ trustpilot._reset_state_for_tests()++ def run(cmd, **kwargs):+ calls.append(cmd)+ if cmd[1] == "auth":+ data = {"isFresh": True}+ elif cmd[1] == "search":+ data = {"hits": [{"displayName": "Currys", "domain": "currys.co.uk", "numberOfReviews": 100}]}+ else:+ data = {"name": "Selected company", "domain": cmd[2], "reviewCount": 100}+ return subproc.SubprocResult(returncode=0, stdout=json.dumps(data), stderr="")++ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)+ monkeypatch.setattr(trustpilot.subproc, "run_with_timeout", run)+ yield calls+ trustpilot._reset_state_for_tests()++[email protected]("topic,domain", [+ ("currys.co.uk", "currys.co.uk"),+ ("woolworths.com.au", "woolworths.com.au"),+ ("reviews of https://www.currys.co.uk/help", "www.currys.co.uk"),+ ("Reviews of WOOLWORTHS.COM.AU.", "woolworths.com.au"),+ ("chownow.com.other", "chownow.com.other"),+ ("my-brand.com", "my-brand.com"),+])+def test_trustpilot_domain_topics_reach_the_cli_intact(trustpilot_cli, topic, domain):+ response = trustpilot.search_trustpilot(topic, "2026-10-01", "2026-10-22")+ items = trustpilot.parse_trustpilot_response(response, query=topic)+ assert [call[2] for call in trustpilot_cli if call[1] == "info"] == [domain]+ assert [item["url"] for item in items] == [f"https://www.trustpilot.com/review/{domain}"]+ assert not [call for call in trustpilot_cli if call[1] == "search"]+++def test_trustpilot_explicit_domain_overrides_the_topic(trustpilot_cli):+ response = trustpilot.search_trustpilot(+ "currys.co.uk", "2026-10-01", "2026-10-22", explicit_domain="www.woolworths.com.au"+ )+ assert response["results"][0]["domain"] == "www.woolworths.com.au"+ assert [call[2] for call in trustpilot_cli if call[1] == "info"] == ["www.woolworths.com.au"]+ assert not [call for call in trustpilot_cli if call[1] == "search"]+++def test_trustpilot_company_names_still_resolve_through_search(trustpilot_cli):+ response = trustpilot.search_trustpilot("Currys", "2026-10-01", "2026-10-22")+ assert response["results"][0]["domain"] == "currys.co.uk"+ assert [call[2] for call in trustpilot_cli if call[1] == "search"] == ["Currys"]+ assert [call[2] for call in trustpilot_cli if call[1] == "info"] == ["currys.co.uk"]++[email protected]("count", [1, 3])+def test_startpage_keeps_snippets_with_their_results(monkeypatch, tmp_path, count):+ second_snippet = f"Only for the second result: {tmp_path.name}"+ page = f'''+ <a class="result-title result-link" href="https://first.example"><h2>First result</h2></a>+ <a class="result-title result-link" href="https://second.example"><h2>Second result</h2></a>+ <p class="description">{second_snippet}</p>+ <a class="result-title result-link" href="https://third.example"><h2>Third & final</h2></a><p class="description">Third snippet</p>+ '''++ def get_text(url, **kwargs):+ return page if urlsplit(url).hostname == "www.startpage.com" else ""++ monkeypatch.setattr(web_search_keyless.http, "get_text", get_text)+ items, artifact = web_search_keyless.keyless_search(+ "example", ("2026-10-01", "2026-10-22"), {}, count=count+ )+ assert artifact["keyless_backend"] == "startpage"+ assert [(item["title"], item["url"], item["snippet"]) for item in items] == [+ ("First result", "https://first.example", ""),+ ("Second result", "https://second.example", second_snippet),+ ("Third & final", "https://third.example", "Third snippet"),+ ][:count]+++def test_startpage_titleless_result_still_bounds_the_previous_snippet(monkeypatch, tmp_path):+ misplaced = f"Titleless result description: {tmp_path.name}"+ page = f'''+ <a class="result-title" href="https://first.example"><h2>First result</h2></a>+ <a class="result-title" href="https://empty.example"><h2></h2></a>+ <p class="description">{misplaced}</p>+ <a class="result-title" href="https://third.example"><h2>Third result</h2></a>+ <p class="description">Third snippet</p>+ '''+ monkeypatch.setattr(web_search_keyless.http, "get_text", lambda *args, **kwargs: page)+ items = web_search_keyless._search_startpage("example", 3)+ assert [(item["url"], item["snippet"]) for item in items] == [+ ("https://first.example", ""),+ ("https://third.example", "Third snippet"),+ ]diff --git a/tests/test_cr20_store.py b/tests/test_cr20_store.pynew file mode 100644index 00000000..79ea6e75--- /dev/null+++ b/tests/test_cr20_store.py@@ -0,0 +1,132 @@+"""Regression coverage for concurrent engagement updates in the research store."""++import sqlite3+import threading+from concurrent.futures import ThreadPoolExecutor++import pytest++import store+++def database(tmp_path, monkeypatch):+ path = tmp_path / "research.db"+ monkeypatch.setattr(store, "_db_override", path)+ store.init_db()+ topic = store.add_topic("Concurrent research")+ return path, topic["id"]++[email protected]("existing", [True, False], ids=["existing-row", "insert-conflict"])+def test_concurrent_observations_keep_maximum_and_each_run_history(database, monkeypatch, existing):+ path, topic_id = database+ finding = {+ "source": "reddit",+ "source_url": "https://reddit.com/r/test/concurrent",+ "source_title": "Concurrent observation",+ }+ expected_history = []+ expected_counts = []+ if existing:+ initial_run = store.record_run(topic_id)+ assert store.store_findings(initial_run, topic_id, [{**finding, "engagement_score": 10}]) == {+ "new": 1, "updated": 0,+ }+ expected_history.append((initial_run, 10.0))+ expected_counts.append((initial_run, 1, 0))+ runs = {score: store.record_run(topic_id) for score in (100, 50)}++ read_barrier = threading.Barrier(2, timeout=5)+ high_committed = threading.Event()+ worker = threading.local()+ observed = {}+ real_connect = store._connect++ class GatedCursor:+ def __init__(self, cursor, score):+ self.cursor = cursor+ self.score = score++ def fetchall(self):+ rows = self.cursor.fetchall()+ observed[self.score] = [row["engagement_score"] for row in rows]+ read_barrier.wait()+ if self.score == 50:+ assert high_committed.wait(timeout=5), "The high observation did not commit"+ return rows++ class GatedConnection:+ def __init__(self, connection):+ self.connection = connection++ def execute(self, sql, parameters=()):+ cursor = self.connection.execute(sql, parameters)+ if sql.startswith("SELECT id, source_url, engagement_score FROM findings WHERE source_url IN"):+ return GatedCursor(cursor, worker.score)+ return cursor++ def __getattr__(self, name):+ return getattr(self.connection, name)++ monkeypatch.setattr(store, "_connect", lambda: GatedConnection(real_connect()))++ def observe(score):+ worker.score = score+ result = store.store_findings(runs[score], topic_id, [{**finding, "engagement_score": score}])+ if score == 100:+ high_committed.set()+ return result++ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = {score: executor.submit(observe, score) for score in (100, 50)}+ results = {score: future.result(timeout=10) for score, future in futures.items()}++ assert observed == {100: [10.0] if existing else [], 50: [10.0] if existing else []}+ assert results == {+ 100: {"new": 0 if existing else 1, "updated": 1 if existing else 0},+ 50: {"new": 0, "updated": 1},+ }+ expected_history.extend([(runs[100], 100.0), (runs[50], 50.0)])+ expected_counts.extend([+ (runs[100], 0 if existing else 1, 1 if existing else 0),+ (runs[50], 0, 1),+ ])+ with sqlite3.connect(path) as connection:+ aggregate = connection.execute(+ "SELECT engagement_score, sighting_count, run_id FROM findings"+ ).fetchall()+ history = connection.execute(+ "SELECT run_id, engagement_score FROM finding_sightings ORDER BY run_id"+ ).fetchall()+ counts = connection.execute(+ "SELECT id, findings_new, findings_updated FROM research_runs ORDER BY id"+ ).fetchall()+ assert aggregate == [(100.0, 3 if existing else 2, runs[50])]+ assert history == expected_history+ assert counts == expected_counts+++ "stored,incoming,expected",+ [(10, 50, 50), (100, 50, 100), (None, 50, 50), (100, None, 100), (None, None, 0)],+)+def test_existing_engagement_preserves_maximum_and_handles_null(database, stored, incoming, expected):+ path, topic_id = database+ finding = {"source": "reddit", "source_url": "https://reddit.com/r/test/sequential"}+ initial_run = store.record_run(topic_id)+ store.store_findings(initial_run, topic_id, [{**finding, "engagement_score": stored}])+ if stored is None:+ with sqlite3.connect(path) as connection:+ connection.execute("UPDATE findings SET engagement_score = NULL")+ run = store.record_run(topic_id)+ assert store.store_findings(run, topic_id, [{**finding, "engagement_score": incoming}]) == {+ "new": 0, "updated": 1,+ }+ with sqlite3.connect(path) as connection:+ assert connection.execute("SELECT engagement_score, sighting_count FROM findings").fetchall() == [+ (expected, 2),+ ]+ assert connection.execute(+ "SELECT engagement_score FROM finding_sightings WHERE run_id = ?", (run,)+ ).fetchone() == (incoming or 0,)diff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex ab36e994..1f4c0b02 100644--- a/tests/test_doc_flag_contract.py+++ b/tests/test_doc_flag_contract.py@@ -107,6 +107,8 @@ def test_html_reference_documents_structured_cache_reuse():assert "No matching cached report data" in textassert "LAST30DAYS_REPORT_CACHE_TTL_SECONDS" in textassert "default: one hour" in text+ assert "--cached-report" in text+ assert "Do not replay --plan, --competitors-plan" in textdef test_configuration_documents_report_cache_ttl():diff --git a/tests/test_freshness.py b/tests/test_freshness.pyindex 9908e756..b4f1e2b6 100644--- a/tests/test_freshness.py+++ b/tests/test_freshness.py@@ -1,5 +1,7 @@import json+import pytest+import last30days as clifrom lib import freshness, github, health, hosted, http, planner, polymarket, render, schema, stocktwits@@ -326,6 +328,285 @@ def test_status_assertion_without_positive_rederivation_is_unsupported():assert "re-derived" in (verdict.detail or "")[email protected]("original_status, opposite_status", [+ ("open", "closed"), ("closed", "open"),+])+def test_latest_matching_status_blocks_an_intermediate_contradiction(+ original_status, opposite_status,+):+ original = _item(+ "reddit", item_id="original",+ title=f"Widget API is {original_status}",+ published_at="2026-07-01T10:00:00Z",+ )+ intermediate = _item(+ "grounding", item_id="intermediate",+ title=f"Widget API is {opposite_status}",+ published_at="2026-07-05T10:00:00Z",+ url="https://status.example.com/widget/intermediate",+ )+ latest = _item(+ "grounding", item_id="latest",+ title=f"Widget API is {original_status}",+ published_at="2026-07-09T10:00:00Z",+ url="https://status.example.com/widget/latest",+ )+ unrelated = _item(+ "grounding", item_id="unrelated",+ title=f"Other API is {opposite_status}",+ published_at="2026-07-10T10:00:00Z",+ )+ report = _report(original, latest, intermediate, unrelated)++ verdicts = freshness.verify_report(report)+ by_item = {verdict.source_item_id: verdict for verdict in verdicts}++ assert by_item[original.item_id].verdict == "unsupported"+ assert by_item[original.item_id].current_value is None+ assert by_item[original.item_id].evidence_url == ""+ assert by_item[intermediate.item_id].verdict == "contradicted"+ assert by_item[intermediate.item_id].current_value == original_status+ assert by_item[intermediate.item_id].evidence_url == latest.url+ assert by_item[intermediate.item_id].evidence_timestamp == latest.published_at+++def test_newest_opposite_status_wins_over_intermediate_agreement():+ original = _item(+ "reddit", item_id="original", title="Widget API is open",+ published_at="2026-07-01T10:00:00Z",+ )+ report = _report(original)+ latest = _item(+ "grounding", item_id="latest", title="Widget API is closed",+ published_at="2026-07-09T10:00:00Z",+ url="https://status.example.com/widget/latest",+ )+ report.items_by_source["grounding"] = [+ _item(+ "grounding", item_id="intermediate", title="Widget API is open",+ published_at="2026-07-05T10:00:00Z",+ ),+ latest,+ ]++ verdict = freshness.verify_report(report)[0]++ assert verdict.verdict == "contradicted"+ assert verdict.current_value == "closed"+ assert verdict.evidence_url == latest.url+ assert verdict.evidence_timestamp == latest.published_at++[email protected]("original_status, opposite_status", [+ ("open", "closed"), ("closed", "open"),+])[email protected]("agreement_field, contradiction_field", [+ ("title", "snippet"), ("title", "body"),+ ("snippet", "body"), ("body", "title"),+])+def test_newest_item_agreement_cannot_hide_its_contradictory_assertion(+ original_status, opposite_status, agreement_field, contradiction_field,+):+ original = _item(+ "reddit", item_id="original", title=f"Widget API is {original_status}",+ published_at="2026-07-01T10:00:00Z",+ )+ fields = {"title": "Status update", "snippet": "", "body": ""}+ fields[agreement_field] = f"Widget API was {original_status}"+ fields[contradiction_field] = f"Widget API is {opposite_status}"+ latest = _item(+ "grounding", item_id="latest", **fields,+ published_at="2026-07-09T10:00:00Z",+ url="https://status.example.com/widget/latest",+ )+ report = _report(original)+ report.items_by_source["grounding"] = [latest]++ verdict = freshness.verify_report(report)[0]++ assert verdict.verdict == "contradicted"+ assert verdict.current_value == opposite_status+ assert verdict.evidence_url == latest.url+ assert verdict.evidence_timestamp == latest.published_at++[email protected]("original_status, opposite_status", [+ ("open", "closed"), ("closed", "open"),+])[email protected]("current_field, historical_field", [+ ("title", "body"), ("body", "title"),+ ("title", "snippet"), ("snippet", "title"),+ ("snippet", "body"), ("body", "snippet"),+])+def test_current_agreement_is_not_overridden_by_historical_opposite(+ original_status, opposite_status, current_field, historical_field,+):+ original = _item(+ "reddit", item_id="original", title=f"Widget API is {original_status}",+ published_at="2026-07-01T10:00:00Z",+ )+ fields = {"title": "Status update", "snippet": "", "body": ""}+ fields[current_field] = f"Widget API is {original_status}"+ fields[historical_field] = f"Widget API was {opposite_status}"+ report = _report(original)+ report.items_by_source["grounding"] = [_item(+ "grounding", item_id="latest", **fields,+ published_at="2026-07-09T10:00:00Z",+ )]++ verdict = freshness.verify_report(report)[0]++ assert verdict.verdict == "unsupported"+ assert verdict.current_value is None+ assert verdict.evidence_url == ""++[email protected]("field", ["title", "snippet", "body"])[email protected]("current_first", [True, False])[email protected]("current_status", ["open", "closed"])+def test_current_status_wins_over_history_within_one_field(field, current_first, current_status):+ original = _item(+ "reddit", item_id="original", title="Widget API is open",+ published_at="2026-07-01T10:00:00Z",+ )+ historical_status = "closed" if current_status == "open" else "open"+ sentences = [f"Widget API is {current_status}.", f"Widget API was {historical_status}."]+ fields = {"title": "Status update", "snippet": "", "body": ""}+ fields[field] = " ".join(sentences if current_first else reversed(sentences))+ latest = _item(+ "grounding", item_id="latest", **fields,+ published_at="2026-07-09T10:00:00Z",+ url="https://status.example.com/widget/latest",+ )+ report = _report(original)+ report.items_by_source["grounding"] = [latest]++ verdict = freshness.verify_report(report)[0]++ if current_status == "open":+ assert verdict.verdict == "unsupported"+ assert verdict.current_value is None+ assert verdict.evidence_url == ""+ else:+ assert verdict.verdict == "contradicted"+ assert verdict.current_value == "closed"+ assert verdict.evidence_url == latest.url+ assert verdict.evidence_timestamp == latest.published_at++[email protected]("title, body", [+ ("Widget API is open", "Widget API is closed"),+ ("Widget API is closed", "Widget API is open"),+])+def test_conflicting_current_statuses_in_latest_item_remain_unsupported(title, body):+ original = _item(+ "reddit", item_id="original", title="Widget API is open",+ published_at="2026-07-01T10:00:00Z",+ )+ report = _report(original)+ report.items_by_source["grounding"] = [+ _item(+ "grounding", item_id="intermediate", title="Widget API is closed",+ published_at="2026-07-05T10:00:00Z",+ ),+ _item(+ "grounding", item_id="latest", title=title, body=body,+ published_at="2026-07-09T10:00:00Z",+ ),+ ]++ verdict = freshness.verify_report(report)[0]++ assert verdict.verdict == "unsupported"+ assert verdict.current_value is None+ assert verdict.evidence_url == ""++[email protected]("verb", ["is", "remains", "was", "became", "has been"])+def test_standalone_supported_copulas_preserve_status_verification(verb):+ original = _item(+ "reddit", item_id="original", title="Widget API is open",+ published_at="2026-07-01T10:00:00Z",+ )+ report = _report(original)+ latest = _item(+ "grounding", item_id="latest", title=f"Widget API {verb} closed",+ snippet="Other API is open",+ published_at="2026-07-09T10:00:00Z",+ url="https://status.example.com/widget/latest",+ )+ report.items_by_source["grounding"] = [latest]++ verdict = freshness.verify_report(report)[0]++ assert verdict.verdict == "contradicted"+ assert verdict.current_value == "closed"+ assert verdict.evidence_url == latest.url+ assert verdict.evidence_timestamp == latest.published_at++[email protected]("current_verb, historical_verb", [+ ("remains", "was"), ("is", "became"),+ ("is", "has been"), ("has been", "was"),+])[email protected]("current_status", ["open", "closed"])+def test_explicit_current_status_takes_precedence_over_less_current_forms(+ current_verb, historical_verb, current_status,+):+ original = _item(+ "reddit", item_id="original", title="Widget API is open",+ published_at="2026-07-01T10:00:00Z",+ )+ historical_status = "closed" if current_status == "open" else "open"+ latest = _item(+ "grounding", item_id="latest",+ title=f"Widget API {historical_verb} {historical_status}",+ body=f"Widget API {current_verb} {current_status}",+ published_at="2026-07-09T10:00:00Z",+ url="https://status.example.com/widget/latest",+ )+ report = _report(original)+ report.items_by_source["grounding"] = [latest]++ verdict = freshness.verify_report(report)[0]++ if current_status == "open":+ assert verdict.verdict == "unsupported"+ assert verdict.current_value is None+ assert verdict.evidence_url == ""+ else:+ assert verdict.verdict == "contradicted"+ assert verdict.current_value == "closed"+ assert verdict.evidence_url == latest.url+ assert verdict.evidence_timestamp == latest.published_at++[email protected]("unrelated_status", ["closed", "open"])+def test_newest_item_agreement_ignores_another_subjects_status(unrelated_status):+ original = _item(+ "reddit", item_id="original", title="Widget API is open",+ published_at="2026-07-01T10:00:00Z",+ )+ report = _report(original)+ report.items_by_source["grounding"] = [+ _item(+ "grounding", item_id="intermediate", title="Widget API is closed",+ published_at="2026-07-05T10:00:00Z",+ ),+ _item(+ "grounding", item_id="latest", title="Widget API is open",+ snippet=f"Other API is {unrelated_status}",+ published_at="2026-07-09T10:00:00Z",+ ),+ ]++ verdict = freshness.verify_report(report)[0]++ assert verdict.verdict == "unsupported"+ assert verdict.current_value is None+ assert verdict.evidence_url == ""++def test_status_contradiction_requires_subject_bound_to_opposite_status():original = _item("reddit",diff --git a/tests/test_grok_lanes_pipeline.py b/tests/test_grok_lanes_pipeline.pyindex 3dc3aa82..8b848654 100644--- a/tests/test_grok_lanes_pipeline.py+++ b/tests/test_grok_lanes_pipeline.py@@ -7,6 +7,8 @@ name. The third is not redundant with the second -- most discussion never"""import inspect+import json+import subprocessimport pytest@@ -78,7 +80,7 @@ def test_name_lane_failure_does_not_abort_the_run():assert "NAME-lane" in block-def test_by_lane_does_not_and_the_topic_by_default():+def test_by_lane_does_not_and_the_topic_by_default(monkeypatch):"""A prior defect emptied the from-lane by ANDing the topic into it.The `and_topic` parameter now exists for extracted handles that need to@@ -87,13 +89,35 @@ def test_by_lane_does_not_and_the_topic_by_default():from lib import grok_xsig = inspect.signature(grok_x.search_handles)assert "topic" in sig.parameters- # and_topic parameter should default to Falseassert "and_topic" in sig.parametersassert sig.parameters["and_topic"].default is False- body = inspect.getsource(grok_x.search_handles)- assert "from:{clean}" in body- # The default path (and_topic=False) should not include {topic} in the query- assert 'query = f"from:{clean} since:{from_date}' in body+ queries = []+ post_url = "https://x.com/steipete/status/2087568620465607078"++ def run(cmd, **kwargs):+ if "--version" in cmd:+ return subprocess.CompletedProcess(cmd, 0, "grok 1.0.46 (2765805b9442) [stable]", "")+ prompt = cmd[cmd.index("-p") + 1]+ prefix = "Query (JSON string literal): "+ query_lines = [line[len(prefix):] for line in prompt.splitlines() if line.startswith(prefix)]+ assert len(query_lines) == 1+ queries.append(json.loads(query_lines[0]))+ posts = [{"url": post_url, "text": "Released a new agent toolkit.", "likes": 10}]+ return subprocess.CompletedProcess(cmd, 0, json.dumps(posts), "")++ monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok")+ monkeypatch.setattr(grok_x.subprocess, "run", run)+ for options in ({}, {"and_topic": True}):+ items, revoked = grok_x.search_handles(+ ["steipete"], "Peter Steinberger", "2026-07-14", "2026-08-13", **options+ )+ assert [item["url"] for item in items] == [post_url]+ assert revoked is False++ assert queries == [+ "from:steipete since:2026-07-14 until:2026-08-14",+ "from:steipete Peter Steinberger since:2026-07-14 until:2026-08-14",+ ]diff --git a/tests/test_html_reference_engine_path.py b/tests/test_html_reference_engine_path.pyindex f3195a56..9f7e8d93 100644--- a/tests/test_html_reference_engine_path.py+++ b/tests/test_html_reference_engine_path.py@@ -49,6 +49,12 @@ def _engine_command(block):def test_documented_local_export_uses_runtime_skill_directory(tmp_path):blocks = re.findall(r"```bash\n(.*?)```", reference_text("save-html-brief"), re.DOTALL)env, output = _command_environment(tmp_path)+ initial = subprocess.run(+ [sys.executable, str(SKILL / "scripts/last30days.py"), env["TOPIC"],+ "--mock", "--quick", "--search=reddit", "--no-browser-cookies"],+ cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30,+ )+ assert initial.returncode == 0, initial.stderrcommand = _engine_command(blocks[0])result = subprocess.run([@@ -75,7 +81,7 @@ def test_documented_publish_command_reaches_engine_parser(tmp_path):blocks = re.findall(r"```bash\n(.*?)```", reference_text("save-html-brief"), re.DOTALL)env, _ = _command_environment(tmp_path)result = subprocess.run(- ["bash", "-ec", "SCOPE_FLAGS=(--help)\n" + blocks[1]],+ ["bash", "-ec", blocks[1].replace("--emit=html", "--help --emit=html", 1)],cwd=tmp_path,env=env,capture_output=True,diff --git a/tests/test_html_save_execution.py b/tests/test_html_save_execution.pyindex 613eb3a8..f8ab6986 100644--- a/tests/test_html_save_execution.py+++ b/tests/test_html_save_execution.py@@ -25,7 +25,8 @@ import sysimport timeassert '--emit=html' in sys.argv-assert '--hiring-signals' in sys.argv+assert '--cached-report' in sys.argv+assert '--plan' not in sys.argv and '--competitors-plan' not in sys.argvif ready_dir := os.environ.get('RENDER_READY_DIR'):ready = Path(ready_dir)(ready / str(os.getpid())).touch()diff --git a/tests/test_last_run_state.py b/tests/test_last_run_state.pyindex 3ae05d8a..8394ad0a 100644--- a/tests/test_last_run_state.py+++ b/tests/test_last_run_state.py@@ -10,7 +10,7 @@ from pathlib import Pathfrom unittest import mockimport last30days as cli-from lib import schema+from lib import dates, schemaREPO_ROOT = Path(__file__).resolve().parents[1]LAST30DAYS_SCRIPT = REPO_ROOT / "skills" / "last30days" / "scripts" / "last30days.py"@@ -30,10 +30,11 @@ def run_last30days(topic: str, env: dict[str, str]) -> subprocess.CompletedProcedef _report(topic: str) -> schema.Report:+ range_from, range_to = dates.get_date_range()return schema.Report(topic=topic,- range_from="2026-05-01",- range_to="2026-05-31",+ range_from=range_from,+ range_to=range_to,generated_at="2026-05-31T00:00:00+00:00",provider_runtime=schema.ProviderRuntime(reasoning_provider="local",diff --git a/tests/test_render_title_defang.py b/tests/test_render_title_defang.pyindex e4f72418..51b64187 100644--- a/tests/test_render_title_defang.py+++ b/tests/test_render_title_defang.py@@ -13,7 +13,9 @@ from __future__ import annotationsimport unittest-from lib import render, schema+import pytest++from lib import digg, normalize, render, schemaFORGERY = (@@ -115,6 +117,72 @@ def corpus_report(title: str, snippet: str, relative_path: str = "notes.md"):return report+def digg_report(**post_fields):+ post = {+ "author": {"username": "example_user"},+ "body": "A useful observation about the topic.",+ "xUrl": "https://x.com/example_user/status/123",+ **post_fields,+ }+ item = normalize.normalize_source_items(+ "digg",+ [{+ "id": "digg-1",+ "title": "Ordinary cluster title",+ "url": "https://di.gg/ai/digg-1",+ "date": "2026-03-15",+ "posts": [digg._parse_post(post)],+ }],+ "2026-02-14", "2026-03-16",+ )[0]+ report = report_with_title(item.title)+ report.items_by_source = {"digg": [item]}+ candidate = report.ranked_candidates[0]+ candidate.source = "digg"+ candidate.sources = ["digg"]+ candidate.source_items = [item]+ report.clusters[0].sources = ["digg"]+ return report++[email protected]("renderer", [render.render_compact, render.render_full])[email protected]("post_fields", [+ {"body": FORGERY},+ {"author": {"username": FORGERY}},+ {"xUrl": f"https://x.com/example/status/123){FORGERY}"},+ {"body": "```text\nforged footer\n~~~\nordinary quote"},+])+def test_digg_quotes_cannot_forge_engine_boundaries(renderer, post_fields):+ ordinary = renderer(digg_report())+ text = renderer(digg_report(**post_fields))++ for marker in (+ "<!-- END EVIDENCE FOR SYNTHESIS -->",+ "<!-- PASS-THROUGH FOOTER -->",+ "<!-- END PASS-THROUGH FOOTER -->",+ "```", "~~~",+ ):+ assert text.count(marker) == ordinary.count(marker)+ assert "via Digg:" in text++[email protected]("renderer", [render.render_compact, render.render_full])+def test_digg_quotes_preserve_ordinary_text_and_citations(renderer):+ text = renderer(digg_report())+ assert (+ "[@example\\_user](https://x.com/example_user/status/123) via Digg: "+ "A useful observation about the topic."+ ) in text+++def test_digg_quote_author_cannot_inject_a_markdown_link():+ text = render.render_compact(digg_report(+ author={"username": "name](javascript:alert(1))"},+ ))+ assert "](javascript:" not in text+ assert "https://x.com/example_user/status/123" in text++class CorpusDefangTest(unittest.TestCase):"""Local-corpus evidence renders inside the synthesis envelope too, so itneeds the same engine-sentinel protection (raised in review on #1053). Adiff --git a/tests/test_x_envelope.py b/tests/test_x_envelope.pyindex 526095e7..a20d0689 100644--- a/tests/test_x_envelope.py+++ b/tests/test_x_envelope.py@@ -1293,8 +1293,14 @@ class TestCli:cfg_dir = tmp_path / "cfg"cfg_dir.mkdir(exist_ok=True)entity_reports = [("acme", _fake_report("acme")), ("globex", _fake_report("globex"))]+ research_options = cli._cache_research_options(+ cli.build_parser().parse_args(["acme vs globex", "--competitors-plan", plan])+ )with mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir):- assert cli._write_last_run("acme vs globex", entity_reports[0][1], entity_reports, x_envelope_sha256=digest)+ assert cli._write_last_run(+ "acme vs globex", entity_reports[0][1], entity_reports,+ x_envelope_sha256=digest, research_options=research_options,+ )argv = ["acme vs globex", "--competitors-plan", plan, "--emit", "html", "--synthesis-file", str(synth)]with mock.patch.object(cli, "_render_save_and_print", return_value=0) as render:rc, _, err = _cli(argv, tmp_path)diff --git a/tests/test_xquik.py b/tests/test_xquik.pyindex a8a49105..f4aec1e0 100644--- a/tests/test_xquik.py+++ b/tests/test_xquik.py@@ -240,8 +240,8 @@ class TestSearchXquik(unittest.TestCase):self.assertEqual([parse_qs(urlsplit(call.args[0]).query)["q"][0] for call in mock_get.call_args_list],[- "test topic since:2026-01-01 until:2026-03-01",- "topic variant since:2026-01-01 until:2026-03-01",+ "test topic since:2026-01-01 until:2026-03-02",+ "topic variant since:2026-01-01 until:2026-03-02",],)self.assertEqual(