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(setup-wizard): repair the first-run NUX (Chrome-first cookies, working GitHub signup, honest copy) (#744)
Matt Van Hornf857a5101f66
diff --git a/AGENTS.md b/AGENTS.mdindex 123ba9b1..570624d9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -43,7 +43,7 @@ Python 3.12+ required. Use `uv` for the env; the venv lives at `.venv/`.- Do not reduce `fail_under` in `pyproject.toml` (`[tool.coverage.report]`) without documenting why in the PR. The coverage gate is a floor meant to rise over time, not to be relaxed when new code is under-tested.- Every `lib/*.py` call to `log.source_log(...)` must pass `tty_only=False`. The default is `True`, which silently drops every line when stderr isn't a TTY (Claude Code, Codex, CI, captured output) — turning source observability into invisible failure. Enforced by `tests/test_source_log_visibility.py`.- **CLI-gated optional sources** (Digg via `digg-pp-cli`, YouTube via `yt-dlp`) activate only when `shutil.which` resolves the binary on the **agent subprocess PATH** — not merely when the file exists on disk. First-run setup installs Digg through `@mvanhorn/printing-press-library` (default `$HOME/.local/bin`); Hermes/OpenClaw gateways often need that directory on PATH. Setup must distinguish PATH-visible installs from off-PATH binaries and must not claim "now active" unless the engine gate would pass. See `docs/solutions/integration-issues/digg-cli-agent-path-setup-wizard.md`.-- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth) — it cannot prompt, so consent lives in `SKILL.md` Step 0. Step 0 has TWO branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, and a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI). Both ask before reading cookies, surface the macOS Full Disk Access fix on permission-denied, and offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. Threads/Pinterest are intentionally not surfaced in onboarding (power-user `INCLUDE_SOURCES` only).+- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth) — it cannot prompt, so consent lives in `SKILL.md` Step 0. Step 0 has TWO branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, and a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI). Both ask before reading cookies, surface the macOS Full Disk Access fix on permission-denied, and offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers: **Recommended** (TikTok + Instagram, on with the key) and **Everything** (also Threads, Pinterest, and YouTube/TikTok/Instagram comments via `INCLUDE_SOURCES`). Threads, Pinterest, and YouTube comments are opt-in (gated on `INCLUDE_SOURCES`), not auto-on with the key — they appear only in the Step 5 Everything option, never in the welcome or the Step 4 offer.## Security hygiene- Never commit real API keys, browser cookies, auth tokens, app passwords, access tokens, or `.env` contents.diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex f55b09d3..0c2dbe25 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -66,7 +66,7 @@ Both share the same consent points:1. **Browser cookies** - the model asks before reading anything. On yes it runs `setup --allow-browser-cookies`, which extracts Firefox/Safari cookies (never Chrome unless `FROM_BROWSER=auto` or a named Chromium browser is explicitly configured) to unlock X/Twitter and other logged-in sources, and installs yt-dlp + the keyless Digg CLI. On no it runs setup without `--allow-browser-cookies` (or with `FROM_BROWSER=off`), which skips all cookie reads and still installs the tools.2. **Full Disk Access (macOS)** - if a cookie read is permission-denied, the model surfaces the System Settings > Privacy & Security > Full Disk Access fix and offers one retry.-3. **ScrapeCreators GitHub signup** - offered on every first run (10,000 free calls). On consent it runs `setup --github`, which opens a browser for GitHub device-auth (or registers instantly via the `gh` CLI when installed) and, on success, **persists `SCRAPECREATORS_API_KEY` automatically** (0o600, masked in output) so TikTok, Instagram, X, YouTube comments, and the SC Reddit/YouTube backups activate on the next run. Decline anytime; you can run it later by asking to set up ScrapeCreators. (Threads and Pinterest are not surfaced in onboarding but remain available via `INCLUDE_SOURCES`.)+3. **ScrapeCreators GitHub signup** - offered on every first run (10,000 free calls). On consent it runs `setup --github`, which opens a browser for GitHub device-auth (or registers instantly via the `gh` CLI when installed) and, on success, **persists `SCRAPECREATORS_API_KEY` automatically** (0o600, masked in output) so TikTok, Instagram, and the SC Reddit/YouTube backups activate on the next run. Decline anytime; you can run it later by asking to set up ScrapeCreators. The Step 5 opt-in has two tiers: **Recommended** (TikTok + Instagram) and **Everything**, which also enables Threads, Pinterest, and YouTube/TikTok/Instagram comments via `INCLUDE_SOURCES`.Re-run onboarding by deleting `~/.config/last30days/.env`. The mechanical work lives in `scripts/lib/setup_wizard.py`; the consent conversation and both host flows are specified in `skills/last30days/SKILL.md` Step 0. The original v3.0.0 wizard is captured at `docs/reference/old-nux-wizard-v3.0.0.md`.@@ -93,7 +93,7 @@ The project-scoped file is useful for **intentional per-client setups**: drop a| StockTwits | none | auto-on for ticker/crypto topics only (gated by symbol detection); never registered for non-financial topics | yes (public API, ~200 req/hr per IP) || GitHub | `gh` CLI installed (uses your GitHub auth) | always on if `gh` present | yes || YouTube | `yt-dlp` CLI installed; `SCRAPECREATORS_API_KEY` adds a server-side transcript fallback used only when yt-dlp fails (429 / bot-gate) | always on if `yt-dlp` present; SC transcript fallback default-on when key set (no credit spent unless yt-dlp fails) | yes |-| YouTube comments | `SCRAPECREATORS_API_KEY` (default-on; suppress via `EXCLUDE_SOURCES=youtube_comments`) | top comments on the top ~3 videos by engagement | ~3 calls/run; 10K free calls |+| YouTube comments | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `youtube_comments` (opt-in; part of the Step 5 Everything tier) | top comments on the top ~3 videos by engagement | ~3 calls/run; 10K free calls || Digg | `digg-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install digg --cli-only`; binary defaults to `$HOME/.local/bin` — Hermes/OpenClaw agent subprocesses must inherit that dir on PATH for Digg to activate; prior pp-digg installs use the same path) | always on if `digg-pp-cli` on PATH | yes (free, keyless, read-only) || arXiv | `arxiv-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install arxiv --cli-only`) | always on if `arxiv-pp-cli` on PATH; fires on research/technical topics and stays quiet otherwise (relevance + 365-day recency gating) | yes (free, keyless) || Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; syncs a local headline cache once per run, then searches | yes (free, keyless) |diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 483eded8..b78befc2 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -424,16 +424,19 @@ Welcome to /last30days!I research any topic across Reddit, X, YouTube, and more - synthesizing what people are actually saying right now.Auto setup gives you the core sources free in about 30 seconds:-- X/Twitter - reads your browser cookies to authenticate (read live each run, never saved to disk).+- X/Twitter - reads your browser cookies to authenticate (read live each run, never saved to disk). I check Chrome first (fastest - a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari.- Reddit with comments - public JSON, no API key needed.- YouTube search + transcripts - installs yt-dlp (open source, 190K+ GitHub stars).- Digg - trending news, GitHub stars, and pipeline feeds - installs the free, keyless Digg CLI.- arXiv (📄) + Techmeme (📰) - research papers and tech-news headlines - install free, keyless Printing Press CLIs and run on any topic (arXiv is relevance + recency gated to research topics).+- StockTwits (📈) - retail trader sentiment - auto-on when your topic is a ticker or crypto (e.g. "$NVDA earnings", "bitcoin"), off for everything else.- Trustpilot (⭐) - brand/company review sentiment - opt-in (add `trustpilot` to `INCLUDE_SOURCES`), off by default because it can do a one-time ~10s headless browser cookie step on first company lookup. Install with `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`.- Hacker News + Polymarket + GitHub (auto-on if the `gh` CLI is installed) - always on, zero config.Want TikTok and Instagram too? ScrapeCreators adds those (10,000 free calls, scrapecreators.com). No kickbacks, no affiliation.+Power users can turn on more sources in the Manual Setup guide (LinkedIn, Bluesky, Perplexity, and others) - each needs its own credential, so they are off by default.+**Step 2 - Setup choice.** Then IMMEDIATELY call AskUserQuestion with ONLY this question and these options (do not repeat the welcome text inside the modal):Question: "How would you like to set up?"@@ -449,39 +452,40 @@ Options:**If the user picks Auto setup:**Get cookie consent first. Check if `BROWSER_CONSENT=true` already exists in `~/.config/last30days/.env`; if so, skip the consent prompt and run `setup --allow-browser-cookies` directly. Otherwise **call AskUserQuestion:**-Question: "Auto setup will scan your browser (Firefox/Safari) for x.com cookies to authenticate X search. Cookies are read live, not saved to disk. OK to proceed?"+Question: "Auto setup will scan your browser for x.com cookies to authenticate X search - I check Chrome first (a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari. Cookies are read live, not saved to disk. OK to proceed?"Options:- "Yes, scan my cookies for X" - run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (relative to the skill root). Append `BROWSER_CONSENT=true` to `.env` after setup completes.- "Skip X, just set up YouTube + Digg" - run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp and Digg.- "I have an xAI API key instead" - ask them to paste it, write `XAI_API_KEY` to `.env`, then run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup` (installs yt-dlp + Digg, no cookie read).-The consented `setup --allow-browser-cookies` run extracts cookies (Firefox/Safari by default - never Chrome, to avoid a macOS Keychain prompt, unless `FROM_BROWSER=auto` or a named Chromium browser was explicitly configured) and best-effort installs yt-dlp (YouTube) and the free, keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; Digg activates only when the binary is on the **agent subprocess PATH**, typically `$HOME/.local/bin`; setup reports honestly if installed off-PATH; recommend-only if `npx` is unavailable). Show the user what was found and installed - including whether Digg landed on PATH (active) or off-PATH (installed but not yet active).+The consented `setup --allow-browser-cookies` run extracts cookies (Chrome/Chromium family first via the Keychain with no Full Disk Access, then Firefox and Safari as fallbacks; the winning browser is pinned for future runs only when it is Firefox or Safari, so Chrome never re-triggers the Keychain prompt on later runs) and best-effort installs yt-dlp (YouTube) and the free, keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; Digg activates only when the binary is on the **agent subprocess PATH**, typically `$HOME/.local/bin`; setup reports honestly if installed off-PATH; recommend-only if `npx` is unavailable). Show the user what was found and installed - including whether Digg landed on PATH (active) or off-PATH (installed but not yet active).-**macOS Full Disk Access remediation.** After the `setup` run, inspect its stderr. If it contains `Permission denied reading Cookies.binarycookies` and the platform is macOS, the OS blocked the read - surface the fix instead of swallowing it: `macOS blocked the cookie read. To enable X/Twitter: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry of the `setup` command. If the user skips, continue.+**macOS Full Disk Access remediation (Safari fallback only).** Chrome and Firefox need no Full Disk Access; only the Safari fallback does. After the `setup` run, inspect its stderr. If it contains `Permission denied reading Cookies.binarycookies` and the platform is macOS, the OS blocked the Safari read - surface the fix instead of swallowing it: `macOS blocked the Safari cookie read. If your x.com login is in Chrome, you don't need this. To use Safari: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry of the `setup` command. If the user skips, continue.**Step 4: ScrapeCreators offer (every first run).** Show this as plain text, then a modal:-ScrapeCreators adds TikTok and Instagram - 10,000 free calls, no credit card. Your key also powers YouTube comments, a YouTube transcript fallback (used only when yt-dlp gets rate-limited), and a Reddit backup (if public Reddit gets rate-limited). (We don't get a cut.)+ScrapeCreators adds TikTok and Instagram - 10,000 free calls, no credit card. Your key also acts as a backup that keeps your free sources working when they hit rate limits: it fetches Reddit if public Reddit gets blocked, and YouTube search/transcripts if yt-dlp gets throttled. (We don't get a cut.) You can add even more sources in the next step.Before the modal, run `which gh` via Bash silently; store as gh_available.**Call AskUserQuestion:**-Question: "Want to add TikTok, Instagram, and the ScrapeCreators backups? (We don't get a cut.)"+Question: "Want to add TikTok and Instagram? Your key also keeps Reddit and YouTube working when they hit rate limits. (We don't get a cut.)"Options:-- "ScrapeCreators via GitHub (fastest, recommended)" - If gh_available, description: "Registers via GitHub CLI in ~2 seconds - no browser." If NOT gh_available, description: "Copies a one-time code to your clipboard and opens GitHub to authorize." After selection: if gh_available, display "Registering via GitHub CLI..."; if not, display "I'll copy a one-time code to your clipboard and open GitHub. When prompted for a device code, just paste (Cmd+V / Ctrl+V)." Then run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github` with a 5-minute timeout. Parse the JSON. On `status == "success"` the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (the raw key never appears - do not ask for or echo it); confirm "You're in! 10,000 free calls. TikTok, Instagram, YouTube comments, and the Reddit/YouTube backups are now active." On `status == "success"` but `"persisted": false` (key write failed, e.g. a permissions error), do NOT claim sources are active - tell the user the signup worked but saving the key failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the raw key is masked in output, so re-run `setup --github` or retrieve it from scrapecreators.com to get the value). On `status` `timeout`/`error`, show "GitHub auth didn't complete - no worries, sign up at scrapecreators.com or try again later," then offer the web option.+- "ScrapeCreators via GitHub (recommended - most free calls)" - description: "Opens GitHub, you enter a short code (~20-30s). Grants the full 10,000 free calls - more than the web signup." (Recommend this over the web option because the GitHub path grants more free calls.) After selection, tell the user: "GitHub will ask for a short code - I'll show it to you in a moment." Then **run `setup --github` in the BACKGROUND** (do not block the foreground): `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github` with a 5-minute timeout, run in the background. **Poll its stdout every ~2-3 seconds** and, the moment a line of the form `{"event":"device_code_ready","user_code":"XXXX-XXXX","verification_uri":"..."}` appears, immediately show the user their code and the URL: "Enter this code on the GitHub page: **XXXX-XXXX** (also copied to your clipboard)." Do NOT wait for the process to finish before showing the code - that is the bug this fixes. When the process exits, parse the **LAST** JSON line of stdout for the final status (stdout carries the early `device_code_ready` line plus the final status blob). On `status == "success"` the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (the raw key never appears - do not ask for or echo it); confirm "You're in! 10,000 free calls. TikTok, Instagram, and the Reddit/YouTube backups are now active." On `status == "already_registered"`, tell the user "You're already set up - your existing ScrapeCreators key is active." On `status == "success"` but `"persisted": false` (key write failed, e.g. a permissions error), do NOT claim sources are active - tell the user the signup worked but saving the key failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the raw key is masked in output, so re-run `setup --github` or retrieve it from scrapecreators.com to get the value). On `status` `timeout`/`denied`/`error`, show "GitHub auth didn't complete - no worries, sign up at scrapecreators.com or try again later," then offer the web option below.+ - **Host without background execution** (can't background a Bash process): run `setup --github` in the foreground, but tell the user first: "A short code will appear - watch for it and enter it on the GitHub page that opens." The engine prints the `device_code_ready` line and the code box to the terminal.- "Open scrapecreators.com (Google sign-in)" - run `open https://scrapecreators.com` via Bash, then ask them to paste the API key. Write `SCRAPECREATORS_API_KEY={key}` to `~/.config/last30days/.env`.- "I have a key" - accept the key, write to `.env`.-- "Skip for now" - proceed without ScrapeCreators.+- "Skip for now" - proceed without ScrapeCreators. No TikTok/Instagram, and no ScrapeCreators backup if Reddit or YouTube get rate-limited (your free sources still work).**Step 5: Source opt-in (only if a ScrapeCreators key was saved, not if skipped).** Plain text then modal:-Your ScrapeCreators key powers TikTok, Instagram, and YouTube comments. Want TikTok and Instagram on for every run? (Each adds one ScrapeCreators call per search.)+Your key is set - TikTok and Instagram are on for every run, plus the Reddit/YouTube backups. Want to add even more?**Call AskUserQuestion:**Question: "Which ScrapeCreators sources do you want on?"Options:-- "TikTok + Instagram (recommended)" - append `INCLUDE_SOURCES=tiktok,instagram` to `~/.config/last30days/.env`. Confirm: "TikTok and Instagram are on, plus the Reddit/YouTube backups if the free sources get rate-limited."-- "Just the basics - let's run my first search" - don't write the flag. Confirm: "Got it. ScrapeCreators will still serve as the Reddit and YouTube backups. You can add sources to `INCLUDE_SOURCES` in your `.env` anytime."+- "TikTok + Instagram (recommended)" - the default: TikTok and Instagram on every run (~2-4 credits per run), plus the Reddit/YouTube rate-limit backups. Write NO `INCLUDE_SOURCES` line (TikTok/Instagram are on automatically with the key). Confirm: "TikTok and Instagram are on, plus the Reddit/YouTube backups if the free sources get rate-limited."+- "Everything (Threads, Pinterest, comments)" - all of the above plus Threads, Pinterest, and YouTube + TikTok/Instagram comment sentiment. Widest coverage, more credits per run. Append `INCLUDE_SOURCES=tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments` to `~/.config/last30days/.env` (the list must include `tiktok,instagram` so they are not treated as excluded). Confirm: "Everything's on: TikTok, Instagram, Threads, Pinterest, and comment sentiment, plus the Reddit/YouTube backups."**Step 6: First-topic picker.** Once `SETUP_COMPLETE=true` is written, **call AskUserQuestion:**Question: "What do you want to research first?"@@ -508,18 +512,23 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI**2. Permission preflight.** Run `"${LAST30DAYS_PYTHON:-python3}" "${SKILL_DIR}/scripts/last30days.py" --preflight` using the directory of the `SKILL.md` you loaded, then summarize the human-readable result before setup: config source, project config trust/ignore state, planned browser-cookie mode, planned writes, optional commands, and active/ignored endpoint overrides. This is safe: it does not read browser-cookie values, does not write setup/config/report files, and does not run research. For Codex desktop and other folder-mode hosts, if hidden `.claude/last30days.env` project config is shown as ignored, tell the user it remains ignored unless `LAST30DAYS_TRUST_PROJECT_CONFIG=1` is set from the process environment or global config. Do not block normal research on missing optional commands; describe them as optional coverage.-**3. Cookie consent (ask BEFORE reading anything).** First check if `BROWSER_CONSENT=true` already exists in `~/.config/last30days/.env` (e.g. granted in a prior Claude Code session); if so, skip this prompt and run `setup --allow-browser-cookies` directly. Otherwise ask. Example: `I can read your browser cookies (Firefox/Safari) to unlock X/Twitter and other logged-in sources. Want me to? (yes / no)` **Wait for the answer.**- - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (and append `BROWSER_CONSENT=true` to `.env` after it completes). Extracts cookies (Firefox/Safari, never Chrome unless `FROM_BROWSER=auto` or a named Chromium browser was explicitly configured) and best-effort installs yt-dlp (YouTube) and the free, keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; activates only when on the agent subprocess PATH, typically `$HOME/.local/bin`; reports honestly if off-PATH; recommend-only if `npx` is unavailable).+**3. Cookie consent (ask BEFORE reading anything).** First check if `BROWSER_CONSENT=true` already exists in `~/.config/last30days/.env` (e.g. granted in a prior Claude Code session); if so, skip this prompt and run `setup --allow-browser-cookies` directly. Otherwise ask. Example: `I can read your browser cookies to unlock X/Twitter and other logged-in sources - I check Chrome first (a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari. Want me to? (yes / no)` **Wait for the answer.**+ - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (and append `BROWSER_CONSENT=true` to `.env` after it completes). Extracts cookies (Chrome/Chromium family first via the Keychain with no Full Disk Access, then Firefox and Safari; only a Firefox/Safari winner is pinned for later runs, so Chrome never re-prompts) and best-effort installs yt-dlp (YouTube) and the free, keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; activates only when on the agent subprocess PATH, typically `$HOME/.local/bin`; reports honestly if off-PATH; recommend-only if `npx` is unavailable).- On **no** → run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp and Digg, still writes `SETUP_COMPLETE`.**4. Full Disk Access remediation (macOS only).** After `setup`, inspect stderr. If it contains `Permission denied reading Cookies.binarycookies` on macOS, surface: `macOS blocked the cookie read. To enable X/Twitter: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry. If skipped, continue.-**5. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that unlock TikTok, Instagram, YouTube comments, plus a Reddit backup and a YouTube transcript fallback, and that it opens a GitHub authorization page. Ask, e.g.: `Want to unlock TikTok, Instagram, and more? I can sign you up for ScrapeCreators with GitHub (10,000 free calls) - it opens a browser to authorize. (yes / no)` **Wait for the answer.**- - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github`. A browser window opens; the user authorizes with the code shown. On success the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (never ask for or echo the raw key). Confirm the paid sources are active.+**5. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that add TikTok and Instagram, plus a backup that keeps Reddit and YouTube working when they hit rate limits (a Reddit backup and a YouTube transcript fallback), that GitHub signup grants the full 10,000 free calls (more than the web form), and that it opens a GitHub authorization page where you enter a short code. Ask, e.g.: `Want to unlock TikTok, Instagram, and more? I can sign you up for ScrapeCreators with GitHub (10,000 free calls, ~20-30s) - it opens a browser and you enter a short code. (yes / no)` **Wait for the answer.**+ - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github`. If your host can background a process, run it in the background and poll its stdout; the moment a `{"event":"device_code_ready","user_code":"XXXX-XXXX",...}` line appears, show the user the code and the GitHub URL immediately (do not wait for the process to finish). If you cannot background, run it in the foreground and tell the user to watch for the short code the engine prints, then enter it on the GitHub page. When the process exits, parse the **LAST** JSON line of stdout for the final status. On success the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (never ask for or echo the raw key). Confirm the paid sources are active.+ - On **`status == "already_registered"`** → tell the user they are already set up; their existing key is active.- On **success but `"persisted": false`** (auth completed yet the key write failed) → do NOT claim sources are active. Tell the user signup worked but saving failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the raw key is masked in output, so re-run `setup --github` or retrieve it from scrapecreators.com to get the value).- - On **timeout / denied** → tell the user it didn't complete and offer to retry or skip.+ - On **timeout / denied** → tell the user it didn't complete and offer to retry or the web signup at scrapecreators.com.- On **no** → note they can run it later by asking to set up ScrapeCreators, then continue.+**5b. Source tier (only if a key was saved).** Your key runs TikTok and Instagram on every search plus the Reddit/YouTube backups. Ask whether they want more, e.g.: `Want just TikTok + Instagram (recommended), or Everything - also Threads, Pinterest, and comment sentiment (more credits per run)? (recommended / everything)` **Wait for the answer.**+ - On **recommended** → write NO `INCLUDE_SOURCES` line (TikTok/Instagram are already on with the key). Confirm TikTok and Instagram are on plus the backups.+ - On **everything** → append `INCLUDE_SOURCES=tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments` to `~/.config/last30days/.env` (include `tiktok,instagram` so they are not treated as excluded). Confirm Threads, Pinterest, and comment sentiment are now on too.+**6. Complete.** Once `SETUP_COMPLETE=true` is written, briefly confirm which sources are now active (read the `setup --github` JSON `persisted` field, re-run `--preflight` for a human permission summary, or re-run safe `--diagnose` for JSON) and proceed to research. For Codex desktop, Cursor, Gemini CLI, and raw folder-mode hosts, hidden `.claude/last30days.env` project config is ignored unless `LAST30DAYS_TRUST_PROJECT_CONFIG=1` is set from the process environment or global config; do not tell the user a project file is active unless diagnose reports it as the config source.---diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 3a05b448..6f7b4e85 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -1000,8 +1000,16 @@ def main() -> int:# run, and mask it in stdout so the secret never lands in the host# model's captured Bash output.api_key = results.get("api_key")- if results.get("status") == "success" and api_key:- results["persisted"] = setup_wizard.write_api_key(env.CONFIG_FILE, api_key)+ status = results.get("status")+ if api_key:+ if status == "success":+ results["persisted"] = setup_wizard.write_api_key(env.CONFIG_FILE, api_key)+ elif status == "already_registered":+ results["persisted"] = True # key was already saved+ else:+ results.setdefault("persisted", False)+ # Mask for EVERY status that carries a key, not just success, so+ # the raw secret never reaches the host model's captured stdout.results["api_key"] = setup_wizard.mask_api_key(api_key)else:results["persisted"] = False@@ -1021,6 +1029,12 @@ def main() -> int:# silently skip the service that used the other one).found_browsers = set(results.get("cookies_found", {}).values())from_browser = found_browsers.pop() if len(found_browsers) == 1 else None+ # Pin only a silent winner (firefox/safari). Pinning a Chromium browser+ # would make every steady-state run re-read its Keychain-encrypted store+ # and can re-trigger the "Always Allow" prompt, so Chrome is used for the+ # first-run scan but never pinned.+ if from_browser in {"chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium"}:+ from_browser = Nonesetup_wizard.write_setup_config(env.CONFIG_FILE, from_browser=from_browser)results["env_written"] = Truesys.stderr.write(setup_wizard.get_setup_status_text(results) + "\n")diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex d5eba52b..be42fcf0 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -764,17 +764,16 @@ def is_ytdlp_available() -> bool:def is_youtube_comments_available(config: dict[str, Any]) -> bool:"""Check if YouTube comment enrichment is available.- Default-on when SCRAPECREATORS_API_KEY is set — the same key-only backup- tier as the YouTube transcript fallback (``is_youtube_sc_available``). Cost- is bounded by ``enrich_with_comments(max_videos=3)`` (~3 credits per run).- Suppress via ``EXCLUDE_SOURCES=youtube_comments``.+ Opt-in: requires SCRAPECREATORS_API_KEY AND ``youtube_comments`` in+ ``INCLUDE_SOURCES`` (mirrors ``is_tiktok_comments_available``). Cost is+ bounded by ``enrich_with_comments(max_videos=3)`` (~3 credits per run).- Note: TikTok/Instagram comments remain explicit ``INCLUDE_SOURCES`` opt-ins- (see ``is_tiktok_comments_available``); only YouTube comments are default-on.+ Part of the onboarding "Everything" tier — the "Recommended" tier+ (TikTok/Instagram, no INCLUDE_SOURCES) does not fetch comments."""if not config.get('SCRAPECREATORS_API_KEY'):return False- return 'youtube_comments' not in _parse_exclude_sources(config)+ return 'youtube_comments' in _parse_include_sources(config)def is_tiktok_comments_available(config: dict[str, Any]) -> bool:@@ -895,12 +894,12 @@ def _parse_exclude_sources(config: dict[str, Any]) -> set[str]:def is_threads_available(config: dict[str, Any]) -> bool:- """Check if Threads source is available.+ """Check if the Threads credential is available.- Returns True when SCRAPECREATORS_API_KEY is set. Threads runs alongside- TikTok and Instagram as part of the SC family — same key, same per-call- cost shape, so the same default-on rule applies. Suppress via- EXCLUDE_SOURCES=threads.+ Returns True when SCRAPECREATORS_API_KEY is set. This is an availability+ predicate only: whether Threads is actually *scheduled* is gated in the+ pipeline's ``available_sources`` by an ``INCLUDE_SOURCES=threads`` opt-in+ (the onboarding "Everything" tier), so a key alone no longer runs Threads."""return bool(config.get('SCRAPECREATORS_API_KEY'))diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex a1a58db6..f0a213e2 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -204,9 +204,19 @@ def available_sources(available.append("trustpilot")if requested_sources and "xiaohongshu" in requested_sources and env.is_xiaohongshu_available(config):available.append("xiaohongshu")- if env.is_threads_available(config):+ # Threads: opt-in via INCLUDE_SOURCES (same pattern as perplexity/linkedin).+ # Was auto-on with the key; gated so the onboarding "Everything" tier is a+ # real choice vs the "Recommended" (TikTok/Instagram) tier.+ if env.is_threads_available(config) and (+ "threads" in include_sources or (requested_sources and "threads" in requested_sources)+ ):available.append("threads")- if requested_sources and "pinterest" in requested_sources and env.is_pinterest_available(config):+ # Pinterest: opt-in via INCLUDE_SOURCES. Previously read requested_sources+ # only, so a persisted INCLUDE_SOURCES=pinterest never activated it; now it+ # honors both the per-run --sources list and the saved config.+ if env.is_pinterest_available(config) and (+ "pinterest" in include_sources or (requested_sources and "pinterest" in requested_sources)+ ):available.append("pinterest")# xquik is a backend of the single "x" source (see env.x_backend_chain),# not a separate parallel source — registered via the "x" entry above.diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 7138b45a..c114670d 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -8,6 +8,7 @@ presents it), but this module provides the detection and setup actions.import jsonimport loggingimport os+import reimport shutilimport subprocessimport time@@ -58,7 +59,13 @@ def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = Falscookie_config = dict(config)if not (cookie_config.get("FROM_BROWSER") or "").strip():- cookie_config["FROM_BROWSER"] = "firefox,safari"+ # Chromium-first: Chrome/Brave/etc. read cookies via the Keychain+ # with no Full Disk Access, so try them before Safari, whose+ # binarycookies read requires FDA (the dead-end most users hit).+ # firefox/safari stay as the silent fallbacks. Note: an explicit+ # comma list preserves this order (cookie_extraction_browsers);+ # "auto" would put the silent browsers first, so do not use it here.+ cookie_config["FROM_BROWSER"] = "chrome,brave,edge,vivaldi,arc,chromium,firefox,safari"browsers = cookie_extraction_browsers(cookie_config)for source_name, spec in COOKIE_DOMAINS.items():@@ -659,6 +666,24 @@ def run_openclaw_setup(config: Dict[str, Any]) -> Dict[str, Any]:_DEVICE_BASE = "https://api.scrapecreators.com/v1/github/device"+# A GitHub device code is always XXXX-XXXX (uppercase alphanumerics). We validate+# user_code against this before copying, labeling, or emitting it so a malformed+# or key-shaped value (e.g. a returning-account server response) is never+# mislabeled as a device code or leaked to stdout/clipboard.+_DEVICE_CODE_RE = re.compile(r"^[0-9A-Z]{4}-[0-9A-Z]{4}$")+++def _existing_scrapecreators_key() -> Optional[str]:+ """Return the SCRAPECREATORS_API_KEY already saved in the .env, if any."""+ try:+ from . import env as _env++ if _env.CONFIG_FILE and _env.CONFIG_FILE.exists():+ return _env.load_env_file(_env.CONFIG_FILE).get("SCRAPECREATORS_API_KEY") or None+ except Exception as exc: # never let a config-read failure block auth+ logger.debug("Could not read existing ScrapeCreators key: %s", exc)+ return None+def run_device_auth() -> Optional[Tuple[str, str, str, int]]:"""Start the device authorization flow.@@ -685,7 +710,11 @@ def run_device_auth() -> Optional[Tuple[str, str, str, int]]:interval = data.get("interval", 5)if not device_code or not user_code:- logger.warning("Device auth returned incomplete response: %s", data)+ # Log only the response's key names, never its values — a returning+ # account's response could carry a raw API key we must not write to logs.+ logger.warning(+ "Device auth returned incomplete response (keys: %s)", sorted(data.keys())+ )return Nonereturn (device_code, user_code, verification_uri or "", interval)@@ -811,6 +840,31 @@ def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:import sys+ # Step 1b: Validate the code shape BEFORE copying, labeling, or emitting it.+ # A non-conforming user_code (e.g. a key-shaped value) is never surfaced as a+ # GitHub device code; we stop rather than instruct the user to paste garbage.+ if not _DEVICE_CODE_RE.match(user_code):+ logger.warning("Device auth returned a non-device-shaped user_code; aborting.")+ return {+ "status": "error",+ "message": "ScrapeCreators returned an unexpected device-code format.",+ }++ # Step 1c: Surface the code immediately on stdout as a structured line so a+ # backgrounded caller can read and show it right away, instead of waiting for+ # the whole process to exit. The final status blob is still printed at exit,+ # so consumers parse the LAST JSON line for final status.+ print(+ json.dumps(+ {+ "event": "device_code_ready",+ "user_code": user_code,+ "verification_uri": verification_uri,+ }+ ),+ flush=True,+ )+# Step 2: Copy code to clipboard BEFORE opening browserclipboard_ok = Falseif sys.platform == "darwin":@@ -874,4 +928,16 @@ def run_github_auth(timeout: int = 300) -> Dict[str, Any]:Returns JSON-serializable dict with status, method, and api_key."""+ # Already-registered short-circuit: if a key is already saved, return it+ # without forcing another device dance. The key is returned raw here and+ # masked at the CLI boundary before print (see last30days.py), so it never+ # lands unmasked in the host's captured stdout.+ existing = _existing_scrapecreators_key()+ if existing:+ return {+ "status": "already_registered",+ "method": "existing",+ "api_key": existing,+ "persisted": True,+ }return run_full_device_auth(timeout=timeout)diff --git a/tests/test_env_v3.py b/tests/test_env_v3.pyindex 62c0a492..6bd1b0c5 100644--- a/tests/test_env_v3.py+++ b/tests/test_env_v3.py@@ -83,8 +83,13 @@ class ThreadsAvailabilityTests(unittest.TestCase):self.assertFalse(env.is_threads_available({}))self.assertFalse(env.is_threads_available({"INCLUDE_SOURCES": "threads"}))- def test_threads_does_not_require_include_sources(self):- """Regression guard: INCLUDE_SOURCES should not be needed."""+ def test_threads_availability_predicate_is_key_only(self):+ """is_threads_available is availability-only (key present).++ Scheduling is gated separately by INCLUDE_SOURCES in the pipeline's+ available_sources (see TestScrapeCreatorsTierGating) — the predicate+ itself only reports whether the credential exists.+ """self.assertTrue(env.is_threads_available({"SCRAPECREATORS_API_KEY": "k","INCLUDE_SOURCES": "",diff --git a/tests/test_github_device_auth.py b/tests/test_github_device_auth.pynew file mode 100644index 00000000..c2202223--- /dev/null+++ b/tests/test_github_device_auth.py@@ -0,0 +1,105 @@+"""Tests for the ScrapeCreators GitHub device-auth flow.++Covers the U4/U5/U6 fixes: the device code is surfaced on stdout as an early+structured line, a non-device-shaped user_code is never copied/labeled/emitted,+and an already-registered account short-circuits without a fresh device dance.++All hermetic — the network, clipboard, and browser are patched.+"""++import io+import json+from contextlib import redirect_stdout+from unittest.mock import patch++from lib import setup_wizard+++class TestUserCodeValidation:+ """U5: user_code must match the XXXX-XXXX device-code shape."""++ @patch("lib.setup_wizard.subprocess.run")+ @patch("lib.setup_wizard.run_device_auth")+ def test_malformed_user_code_is_rejected(self, mock_run_device, mock_subprocess_run):+ # mock_subprocess_run patches setup_wizard.subprocess.run; the only such+ # call in run_full_device_auth is the pbcopy of the code.+ # A key-shaped value (no dash, 28 chars) must never be treated as a code.+ mock_run_device.return_value = (+ "dev-code-123",+ "m08LboBUJpRz82AMyuCWP9sqwnk2",+ "https://github.com/login/device",+ 5,+ )+ out = io.StringIO()+ with redirect_stdout(out):+ result = setup_wizard.run_full_device_auth(timeout=1)++ assert result["status"] == "error"+ # Not copied to the clipboard (no pbcopy subprocess call)...+ mock_subprocess_run.assert_not_called()+ # ...and never emitted as a device_code_ready line.+ assert "device_code_ready" not in out.getvalue()+ assert "m08LboBUJpRz82AMyuCWP9sqwnk2" not in out.getvalue()+++class TestDeviceCodeReadyEmission:+ """U4: a validated code is emitted to stdout before polling."""++ @patch("webbrowser.open")+ @patch("lib.setup_wizard.subprocess.run")+ @patch("lib.setup_wizard.poll_device_auth")+ @patch("lib.setup_wizard.run_device_auth")+ def test_valid_code_emitted_to_stdout(+ self, mock_run_device, mock_poll, mock_pbcopy, mock_browser+ ):+ mock_run_device.return_value = (+ "dev-code-123",+ "819B-F71B",+ "https://github.com/login/device",+ 5,+ )+ mock_poll.return_value = None # simulate timeout, no token++ out = io.StringIO()+ with redirect_stdout(out):+ result = setup_wizard.run_full_device_auth(timeout=1)++ lines = [ln for ln in out.getvalue().splitlines() if ln.strip()]+ ready = [json.loads(ln) for ln in lines if "device_code_ready" in ln]+ assert ready, "expected a device_code_ready stdout line"+ assert ready[0]["user_code"] == "819B-F71B"+ assert ready[0]["verification_uri"] == "https://github.com/login/device"+ # The final status is still returned (timeout here).+ assert result["status"] == "timeout"+++class TestAlreadyRegistered:+ """U6: an existing key short-circuits without the device dance."""++ @patch("lib.setup_wizard.run_full_device_auth")+ @patch("lib.setup_wizard._existing_scrapecreators_key")+ def test_existing_key_short_circuits(self, mock_existing, mock_full):+ mock_existing.return_value = "sc_live_realkey1234567890"++ result = setup_wizard.run_github_auth(timeout=1)++ assert result["status"] == "already_registered"+ assert result["persisted"] is True+ mock_full.assert_not_called() # no device dance++ @patch("lib.setup_wizard.run_full_device_auth")+ @patch("lib.setup_wizard._existing_scrapecreators_key")+ def test_no_existing_key_runs_device_flow(self, mock_existing, mock_full):+ mock_existing.return_value = None+ mock_full.return_value = {"status": "success", "api_key": "sc_new"}++ result = setup_wizard.run_github_auth(timeout=1)++ assert result["status"] == "success"+ mock_full.assert_called_once()++ def test_already_registered_key_is_masked_before_output(self):+ # Defense-in-depth: the mask helper must not echo the raw key.+ masked = setup_wizard.mask_api_key("sc_live_realkey1234567890")+ assert "realkey" not in masked+ assert masked != "sc_live_realkey1234567890"diff --git a/tests/test_onboarding_contract.py b/tests/test_onboarding_contract.pyindex 81f042be..03888520 100644--- a/tests/test_onboarding_contract.py+++ b/tests/test_onboarding_contract.py@@ -56,7 +56,7 @@ class TestOnboardingContract(unittest.TestCase):"Welcome to /last30days!","How would you like to set up?","scan your browser", # cookie-consent modal- "Want to add TikTok, Instagram, and the ScrapeCreators backups?", # SC offer+ "Want to add TikTok and Instagram?", # SC offer"Which ScrapeCreators sources do you want on?", # source opt-in"What do you want to research first?", # topic picker]@@ -138,14 +138,66 @@ class TestOnboardingContract(unittest.TestCase):self.assertNotIn("1000 credits", self.step0)self.assertNotIn("100 free call", self.step0)- # --- Threads/Pinterest kept out of the onboarding offers ----- def test_threads_pinterest_absent_from_modal_and_prose(self):- """They stay a power-user INCLUDE_SOURCES note in the manual guide only."""- self.assertNotIn("Threads", self.modal)- self.assertNotIn("Pinterest", self.modal)- self.assertNotIn("Threads", self.prose)- self.assertNotIn("Pinterest", self.prose)+ # --- Threads/Pinterest live ONLY in the Step 5 "Everything" opt-in ---++ def _modal_step5(self):+ start = self.modal.index("**Step 5:")+ end = self.modal.index("**Step 6:", start)+ return self.modal[start:end]++ def _modal_before_step5(self):+ # Welcome (Step 1) through the Step 4 ScrapeCreators offer.+ return self.modal[: self.modal.index("**Step 5:")]++ def test_threads_pinterest_only_in_step5_everything(self):+ """Threads/Pinterest are offered in the Step 5 Everything tier, and++ must NOT appear in the welcome or the Step 4 offer (where they would+ read as default-on). They are opt-in via INCLUDE_SOURCES.+ """+ step5 = self._modal_step5()+ self.assertIn("Threads", step5)+ self.assertIn("Pinterest", step5)+ before = self._modal_before_step5()+ self.assertNotIn("Threads", before)+ self.assertNotIn("Pinterest", before)++ def test_everything_tier_writes_full_include_sources(self):+ """The Everything option persists the full opt-in list (incl. tiktok,instagram)."""+ step5 = self._modal_step5()+ self.assertIn("INCLUDE_SOURCES=tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments", step5)++ # --- Chrome-first cookie scan (U2/U3) ---++ def test_cookie_consent_leads_with_chrome(self):+ """Both flows tell the user Chrome is checked first, with the Keychain cue."""+ for slice_name, slice_text in (("modal", self.modal), ("prose", self.prose)):+ self.assertIn("Chrome", slice_text, f"{slice_name} cookie copy omits Chrome")+ self.assertIn("Always Allow", slice_text, f"{slice_name} omits the Keychain cue")++ def test_fda_reframed_as_safari_fallback(self):+ """Full Disk Access is framed as Safari-only, not the default path."""+ self.assertNotIn("scan your browser (Firefox/Safari)", self.modal)++ def test_stocktwits_surfaced_as_conditional(self):+ """StockTwits is advertised in the welcome as a ticker/crypto-gated source."""+ self.assertIn("StockTwits", self.modal)++ # --- Honest GitHub device-code copy (U4/U7) ---++ def test_no_false_instant_gh_promise(self):+ """The '~2 seconds - no browser' claim (a nonexistent code path) is gone."""+ self.assertNotIn("~2 seconds - no browser", self.step0)+ self.assertNotIn("Registers via GitHub CLI in ~2 seconds", self.step0)++ def test_device_code_surfacing_orchestration_present(self):+ """Both flows must surface the device code, not block on a spinner."""+ self.assertIn("device_code_ready", self.modal)+ self.assertIn("device_code_ready", self.prose)++ def test_already_registered_status_handled(self):+ self.assertIn("already_registered", self.modal)+ self.assertIn("already_registered", self.prose)# --- Legacy guarantees retained ---diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.pyindex 8d8c7a3e..11414be5 100644--- a/tests/test_pipeline_v3.py+++ b/tests/test_pipeline_v3.py@@ -1391,5 +1391,50 @@ class TestInnerMaxWorkers(unittest.TestCase):)+class TestScrapeCreatorsTierGating(unittest.TestCase):+ """The onboarding Recommended vs Everything tiers must be real.++ Recommended (key, no INCLUDE_SOURCES) = TikTok + Instagram only.+ Everything (INCLUDE_SOURCES lists them) = also Threads, Pinterest, ...+ """++ KEY = {"SCRAPECREATORS_API_KEY": "k"}++ def test_recommended_tier_runs_tiktok_instagram(self):+ avail = pipeline.available_sources(dict(self.KEY))+ self.assertIn("tiktok", avail)+ self.assertIn("instagram", avail)++ def test_threads_off_without_include_sources(self):+ self.assertNotIn("threads", pipeline.available_sources(dict(self.KEY)))++ def test_threads_on_with_include_sources(self):+ cfg = {**self.KEY, "INCLUDE_SOURCES": "threads"}+ self.assertIn("threads", pipeline.available_sources(cfg))++ def test_pinterest_off_without_include_sources(self):+ self.assertNotIn("pinterest", pipeline.available_sources(dict(self.KEY)))++ def test_pinterest_on_with_persisted_include_sources(self):+ # Regression: this failed before U6 because the pinterest gate read+ # requested_sources only and ignored a persisted INCLUDE_SOURCES.+ cfg = {**self.KEY, "INCLUDE_SOURCES": "pinterest"}+ self.assertIn("pinterest", pipeline.available_sources(cfg))++ def test_pinterest_on_via_requested_sources(self):+ # The per-run --sources path must still work.+ avail = pipeline.available_sources(dict(self.KEY), requested_sources=["pinterest"])+ self.assertIn("pinterest", avail)++ def test_everything_tier_enables_all(self):+ cfg = {+ **self.KEY,+ "INCLUDE_SOURCES": "tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments",+ }+ avail = pipeline.available_sources(cfg)+ self.assertIn("threads", avail)+ self.assertIn("pinterest", avail)++if __name__ == "__main__":unittest.main()diff --git a/tests/test_setup_wizard.py b/tests/test_setup_wizard.pyindex 943b87fe..4955b542 100644--- a/tests/test_setup_wizard.py+++ b/tests/test_setup_wizard.py@@ -105,6 +105,33 @@ class TestRunAutoSetup:assert results["cookies_found"]["x"] == "firefox"assert results["cookies_found"]["truthsocial"] == "firefox"+ @patch("lib.cookie_extract.extract_cookies_with_source")+ @patch("shutil.which")+ def test_default_scan_order_is_chromium_first(self, mock_which, mock_extract):+ """U1: with FROM_BROWSER unset, the scan tries Chrome before Safari.++ Safari is the only X-cookie source needing Full Disk Access; Chrome+ reads via the Keychain with no FDA. The wizard must try the Chromium+ family first so the common macOS user does not hit the FDA dead-end.+ """+ tried = []++ def side_effect(browser, domain, cookie_names):+ tried.append(browser)+ return None # never find cookies, so every browser is attempted++ mock_extract.side_effect = side_effect+ mock_which.return_value = None++ setup_wizard.run_auto_setup({}, allow_browser_cookies=True)++ # Order within the first domain's attempts must be chromium-first.+ assert "chrome" in tried and "safari" in tried+ assert tried.index("chrome") < tried.index("safari")+ assert tried.index("chrome") < tried.index("firefox")+ # And it must not route through the silent-first "auto" order.+ assert tried[0] == "chrome"+class TestYtdlpAutoInstall:"""Tests for yt-dlp auto-install via Homebrew in run_auto_setup()."""diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.pyindex 8ef5e571..91daf6f2 100644--- a/tests/test_youtube_yt.py+++ b/tests/test_youtube_yt.py@@ -1042,20 +1042,21 @@ class TestScTranscriptParsing(unittest.TestCase):class TestYoutubeCommentsGating(unittest.TestCase):- """YouTube comments default-on gating (U5)."""+ """YouTube comments are opt-in via INCLUDE_SOURCES (Everything tier)."""- def test_default_on_with_key_and_no_include_sources(self):+ def test_off_with_key_and_no_include_sources(self):+ """Recommended tier (key, no INCLUDE_SOURCES) does NOT fetch comments."""from lib import env- self.assertTrue(env.is_youtube_comments_available({"SCRAPECREATORS_API_KEY": "k"}))+ self.assertFalse(env.is_youtube_comments_available({"SCRAPECREATORS_API_KEY": "k"}))- def test_unavailable_without_key(self):+ def test_on_with_include_sources(self):from lib import env- self.assertFalse(env.is_youtube_comments_available({}))+ cfg = {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "youtube_comments"}+ self.assertTrue(env.is_youtube_comments_available(cfg))- def test_exclude_sources_suppresses(self):+ def test_unavailable_without_key(self):from lib import env- cfg = {"SCRAPECREATORS_API_KEY": "k", "EXCLUDE_SOURCES": "youtube_comments"}- self.assertFalse(env.is_youtube_comments_available(cfg))+ self.assertFalse(env.is_youtube_comments_available({"INCLUDE_SOURCES": "youtube_comments"}))def test_tiktok_comments_still_opt_in(self):"""Regression: TikTok comments must STILL require INCLUDE_SOURCES."""