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
feat: add safe permission preflight
Trevin Chowa431340fd235
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex fc696749..7dce8db0 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -45,6 +45,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--output <file>` - write the rendered output to an exact file path, using the format selected by `--emit`.- `--save-suffix <name>` - distinguish runs of the same topic (e.g. per client: `--save-suffix=acme`).- `--no-browser-cookies` - hard-disable browser-cookie extraction for this run, even when `FROM_BROWSER` is configured. MCP and folder-mode hosts use this for safe defaults.+- `--preflight` - print a human-readable permission preflight. It reports config source, project config trust/ignore state, browser-cookie plan, planned writes, optional commands, source availability, and endpoint overrides without reading browser cookies, writing setup/config/report files, or running research. Add `--emit=json` for machine-readable preflight JSON; use `--diagnose` when you need the full source diagnostic JSON.The footer line `📎 Raw results saved to ${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}/<slug>-raw.md` is the canonical pointer; if it shows backslashes on Windows update past v3.1.1.@@ -144,7 +145,7 @@ BSKY_APP_PASSWORD=<your-app-password>After editing: `chmod 600 ~/.config/last30days/.env` (or `chmod 600 .claude/last30days.env` if using the project-scoped variant).-**Troubleshooting:** if a source you expected to see isn't appearing in results, run `python3 scripts/last30days.py --diagnose`. It prints a safe preflight report for source availability, config source, browser-cookie plan, external command availability, write destinations, and ignored untrusted project config without reading browser cookies or running live provider probes.+**Troubleshooting:** if a source you expected to see isn't appearing in results, run `python3 scripts/last30days.py --preflight` for a human permission summary or `python3 scripts/last30days.py --diagnose` for full JSON diagnostics. Both are safe: they report source availability, config source, browser-cookie plan, external command availability, write destinations, and ignored untrusted project config without reading browser cookies or running live provider probes.### Perplexity source modesdiff --git a/README.md b/README.mdindex 18e3b3d7..0c80d7a9 100644--- a/README.md+++ b/README.md@@ -204,6 +204,8 @@ npx skills add mvanhorn/last30days-skill -gThe `-g` (global) flag installs to your user directory so the skill is available across all projects. Without `-g`, `npx skills` installs project-locally into `./.skills/` (committed with the repo). For a research-the-world tool, global is what you want.+Codex desktop and other folder-mode hosts can work in ordinary folders as well as Git repos. Before first research, ask the host agent to run the bundled `scripts/last30days.py --preflight` from the loaded skill directory; in a source checkout, the equivalent command is `python3 skills/last30days/scripts/last30days.py --preflight`. It shows the config source, browser-cookie plan, planned writes, optional commands, and ignored project config without reading cookies, writing files, or running research.+By default this installs for whichever harness `npx skills` detects. To target a specific one (or multiple):```bash@@ -314,7 +316,7 @@ See [CONFIGURATION.md](CONFIGURATION.md) for the full per-source key matrix, reaTwo things you'll likely want to know on day one:-**Where research files are saved.** `LAST30DAYS_MEMORY_DIR` defaults to `~/Documents/Last30Days/` (Windows: `C:\Users\<you>\Documents\Last30Days\`). Override by setting that env var to any path in your shell, or `--save-dir <path>` per run. Use `--output <file>` when you need the rendered result at an exact path, using the format selected by `--emit`. Use `--save-suffix=<name>` to keep multiple variations of the same topic separate (e.g. per client). Each `--save-dir` run produces `<slug>-raw[-suffix].md`.+**Where research files are saved.** `LAST30DAYS_MEMORY_DIR` defaults to `~/Documents/Last30Days/` (Windows: `C:\Users\<you>\Documents\Last30Days\`). Override by setting that env var to any path in your shell, or `--save-dir <path>` per run. Use `--output <file>` when you need the rendered result at an exact path, using the format selected by `--emit`. Use `--save-suffix=<name>` to keep multiple variations of the same topic separate (e.g. per client). Each `--save-dir` run produces `<slug>-raw[-suffix].md`. Run `python3 skills/last30days/scripts/last30days.py --preflight` to review planned writes before a research run.**Trend monitoring across runs.** The default mode produces a fresh markdown snapshot per run. To accumulate findings over time, add `--store` to persist into a SQLite database, then use [`scripts/watchlist.py`](skills/last30days/scripts/watchlist.py) for scheduled runs (with optional Slack / webhook delivery on new findings) and [`scripts/briefing.py`](skills/last30days/scripts/briefing.py) for daily / weekly digests. The full cadence pattern is in [CONFIGURATION.md](CONFIGURATION.md#trend-monitoring-store--watchlist--briefings).diff --git a/mcp/internal/tools/preflight.go b/mcp/internal/tools/preflight.gonew file mode 100644index 00000000..b1d2fefa--- /dev/null+++ b/mcp/internal/tools/preflight.go@@ -0,0 +1,85 @@+package tools++import (+ "context"+ "errors"+ "fmt"++ mcplib "github.com/mark3labs/mcp-go/mcp"+ "github.com/mark3labs/mcp-go/server"++ "github.com/mvanhorn/last30days-skill/mcp/internal/engine"+)++func registerPreflightTool(s *server.MCPServer, cfg Config) {+ s.AddTool(+ mcplib.NewTool("preflight",+ mcplib.WithDescription(+ "Safely summarize what last30days would read, write, execute, and contact "++ "without running research, saving files, or reading browser cookies.",+ ),+ mcplib.WithString("format", mcplib.Description("Output shape: 'text' (default) for a concise summary or 'json' for structured details.")),+ mcplib.WithReadOnlyHintAnnotation(true),+ mcplib.WithDestructiveHintAnnotation(false),+ mcplib.WithOpenWorldHintAnnotation(false),+ ),+ makePreflightHandler(cfg),+ )+}++func makePreflightHandler(cfg Config) server.ToolHandlerFunc {+ return func(ctx context.Context, req mcplib.CallToolRequest) (*mcplib.CallToolResult, error) {+ format, err := preflightFormatArgument(req.GetArguments())+ if err != nil {+ return mcplib.NewToolResultError(err.Error()), nil+ }++ src, err := engine.EngineFS()+ if err != nil {+ return mcplib.NewToolResultError(fmt.Sprintf("engine source unavailable: %v", err)), nil+ }+ cacheDir, err := engine.EnsureUserCache(src, cfg.Version)+ if err != nil {+ return mcplib.NewToolResultError(fmt.Sprintf(+ "engine extract failed: %v\nhint: set %s to a writable directory if the default cache location is locked down",+ err, engine.CacheEnvOverride,+ )), nil+ }++ res, runErr := engine.Run(ctx, engine.RunOptions{+ CacheDir: cacheDir,+ Args: preflightRunArgs(format),+ })+ if runErr != nil {+ return mcplib.NewToolResultError(formatRunError(runErr, res)), nil+ }+ return mcplib.NewToolResultText(string(res.Stdout)), nil+ }+}++func preflightRunArgs(format string) []string {+ runArgs := []string{"--preflight", "--no-browser-cookies", "--preflight-report-on-save-dir", mcpSaveDir()}+ if format == "json" {+ runArgs = append(runArgs, "--emit=json")+ }+ return runArgs+}++func preflightFormatArgument(args map[string]any) (string, error) {+ raw, ok := args["format"]+ if !ok {+ return "text", nil+ }+ value, ok := raw.(string)+ if !ok {+ return "", errors.New("format must be a string")+ }+ switch value {+ case "", "text":+ return "text", nil+ case "json":+ return "json", nil+ default:+ return "", fmt.Errorf("format must be 'text' or 'json', got %q", value)+ }+}diff --git a/mcp/internal/tools/preflight_test.go b/mcp/internal/tools/preflight_test.gonew file mode 100644index 00000000..c9585244--- /dev/null+++ b/mcp/internal/tools/preflight_test.go@@ -0,0 +1,62 @@+package tools++import (+ "strings"+ "testing"+)++func TestPreflightRunArgsDefaultTextIsSafe(t *testing.T) {+ t.Setenv("LAST30DAYS_MEMORY_DIR", "")+ args := preflightRunArgs("text")+ want := []string{+ "--preflight",+ "--no-browser-cookies",+ "--preflight-report-on-save-dir",+ "~/Documents/Last30Days",+ }+ if strings.Join(args, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("args = %#v, want %#v", args, want)+ }+}++func TestPreflightRunArgsJSONIsSafeAndStructured(t *testing.T) {+ t.Setenv("LAST30DAYS_MEMORY_DIR", "/tmp/last30days-reports")+ args := preflightRunArgs("json")+ want := []string{+ "--preflight",+ "--no-browser-cookies",+ "--preflight-report-on-save-dir",+ "/tmp/last30days-reports",+ "--emit=json",+ }+ if strings.Join(args, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("args = %#v, want %#v", args, want)+ }+}++func TestPreflightFormatArgumentDefaultsAndValidates(t *testing.T) {+ cases := []struct {+ name string+ args map[string]any+ want string+ wantErr bool+ }{+ {"missing defaults to text", map[string]any{}, "text", false},+ {"empty defaults to text", map[string]any{"format": ""}, "text", false},+ {"text passes", map[string]any{"format": "text"}, "text", false},+ {"json passes", map[string]any{"format": "json"}, "json", false},+ {"invalid rejected", map[string]any{"format": "xml"}, "", true},+ {"non-string rejected", map[string]any{"format": true}, "", true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, err := preflightFormatArgument(tc.args)+ if (err != nil) != tc.wantErr {+ t.Fatalf("err = %v, wantErr = %v", err, tc.wantErr)+ }+ if got != tc.want {+ t.Fatalf("got %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/mcp/internal/tools/research.go b/mcp/internal/tools/research.goindex 1232d130..d9e81240 100644--- a/mcp/internal/tools/research.go+++ b/mcp/internal/tools/research.go@@ -1,7 +1,4 @@-// Package tools owns the MCP tool surface for last30days. Today there is-// exactly one tool, research, mirroring the /last30days <topic> slash-// command available in Claude Code. Adding new tools means another file-// here plus an additional s.AddTool call in Register.+// Package tools owns the MCP tool surface for last30days.package toolsimport (@@ -26,6 +23,7 @@ type Config struct {// Register adds every tool this server exposes to s. The caller supplies a// Config so test harnesses can pin a version without touching globals.func Register(s *server.MCPServer, cfg Config) {+ registerPreflightTool(s, cfg)s.AddTool(mcplib.NewTool("research",mcplib.WithDescription(@@ -91,15 +89,19 @@ func makeResearchHandler(cfg Config) server.ToolHandlerFunc {func researchRunArgs(topic, emit string, save bool) []string {runArgs := []string{topic, "--emit=" + emit, "--no-browser-cookies"}if save {- saveDir := os.Getenv("LAST30DAYS_MEMORY_DIR")- if saveDir == "" {- saveDir = "~/Documents/Last30Days"- }- runArgs = append(runArgs, "--save-dir", saveDir)+ runArgs = append(runArgs, "--save-dir", mcpSaveDir())}return runArgs}+func mcpSaveDir() string {+ saveDir := os.Getenv("LAST30DAYS_MEMORY_DIR")+ if saveDir == "" {+ return "~/Documents/Last30Days"+ }+ return saveDir+}+func requireString(args map[string]any, name string) (string, error) {raw, ok := args[name]if !ok {diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex cb15cd7c..117da799 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -475,19 +475,21 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI**1. Welcome.** One short branded line, e.g.: `Welcome to /last30days - let me get you set up (about 30 seconds).`-**2. 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.**+**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 `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).- On **no** → run `FROM_BROWSER=off python3 skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp and Digg, still writes `SETUP_COMPLETE`.-**3. 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.+**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.-**4. 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.**+**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 `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.- 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 **no** → note they can run it later by asking to set up ScrapeCreators, then continue.-**5. Complete.** Once `SETUP_COMPLETE=true` is written, briefly confirm which sources are now active (read the `setup --github` JSON `persisted` field, or re-run safe `--diagnose`) 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.+**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.---@@ -1974,7 +1976,7 @@ Want another prompt? Just tell me what you're creating next.**What this skill does:**- Sends search queries to ScrapeCreators API (`api.scrapecreators.com`) for TikTok and Instagram search, and as a Reddit backup when public Reddit is unavailable (requires SCRAPECREATORS_API_KEY)- Legacy: Sends search queries to OpenAI's Responses API (`api.openai.com`) for Reddit discovery (fallback if no SCRAPECREATORS_API_KEY)-- Sends search queries to Twitter's GraphQL API (via optional user-provided AUTH_TOKEN/CT0 env vars - no browser session access), xAI's API (`api.x.ai`), Xquik's API (`xquik.com`), or the official X API v2 via xurl CLI (OAuth2, auto-detected when installed and authenticated) for X search+- Sends search queries to X/Twitter via optional user-provided `AUTH_TOKEN`/`CT0` env vars, explicit browser-cookie opt-in (`FROM_BROWSER` or setup consent), xAI's API (`api.x.ai` by default), Xquik's API (`xquik.com` by default), or the official X API v2 via xurl CLI (OAuth2, auto-detected when installed and authenticated)- Sends search queries to Algolia HN Search API (`hn.algolia.com`) for Hacker News story and comment discovery (free, no auth)- Sends search queries to Polymarket Gamma API (`gamma-api.polymarket.com`) for prediction market discovery (free, no auth)- Runs `yt-dlp` locally for YouTube search and transcript extraction (no API key, public data)@@ -1983,16 +1985,18 @@ Want another prompt? Just tell me what you're creating next.- Fetches public Reddit thread data from `reddit.com` for engagement metrics- Stores research findings in local SQLite database (watchlist mode only)- Saves research briefings as .md files to `LAST30DAYS_MEMORY_DIR` (defaults to `~/Documents/Last30Days`)+- Provides `--preflight` for a safe human-readable permission summary before research; it does not read browser-cookie values, write files, or run live research**What this skill does NOT do:**- Does not post, like, or modify content on any platform-- Does not access your Reddit, X, or YouTube accounts-- Does not share API keys between providers (OpenAI key only goes to api.openai.com, etc.)+- Does not access browser cookies unless explicitly configured or consented (`FROM_BROWSER`, manual X cookies, or setup with `--allow-browser-cookies`); `--preflight` and `--diagnose` do not read browser-cookie values+- Does not use Codex ChatGPT auth as an OpenAI provider credential+- Does not share API keys between providers- Does not log, cache, or write API keys to output files-- Does not send data to any endpoint not listed above+- Endpoint destinations follow configured provider base URLs; `--preflight` reports active and ignored endpoint overrides without printing secrets- Hacker News and Polymarket sources are always available (no API key, no binary dependency)- TikTok and Instagram sources require SCRAPECREATORS_API_KEY (10,000 free calls, then PAYG). Reddit uses ScrapeCreators only as a backup when public Reddit is unavailable.-- Can be invoked autonomously by agents via the Skill tool (runs inline, not forked); pass `--agent` for non-interactive report output+- Agent hosts invoke the slash-command skill contract; if `--agent` appears in the user's slash-command arguments, treat it as skill-level mode guidance, not a Python CLI flag.**Bundled scripts:** `scripts/last30days.py` (main research engine), `scripts/lib/` (search, enrichment, rendering modules), `scripts/lib/vendor/bird-search/` (vendored X search client, MIT licensed)diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 5746a54c..195a4aad 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -47,7 +47,7 @@ if os.name == "nt":SCRIPT_DIR = Path(__file__).parent.resolve()sys.path.insert(0, str(SCRIPT_DIR))-from lib import dates, env, html_render, pipeline, render, schema, ui+from lib import dates, env, html_render, permission_preflight, pipeline, render, schema, ui_child_pids: set[int] = set()_child_pids_lock = threading.Lock()@@ -293,6 +293,9 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--debug", action="store_true", help="Enable HTTP debug logging")parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures")parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability")+ parser.add_argument("--preflight", action="store_true",+ help="Print a safe human-readable permission preflight")+ parser.add_argument("--preflight-report-on-save-dir", help=argparse.SUPPRESS)parser.add_argument("--no-browser-cookies", action="store_true",help="Disable browser-cookie extraction even when FROM_BROWSER is configured")parser.add_argument("--save-dir", help="Optional directory for saving the rendered output")@@ -638,6 +641,7 @@ def _setup_allows_browser_cookies(args: argparse.Namespace, extra_argv: list[strreturn (not args.no_browser_cookiesand not args.diagnose+ and not args.preflightand "--allow-browser-cookies" in extra_argv)@@ -683,7 +687,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:if args.no_browser_cookies:browser_mode = "off"- elif args.diagnose:+ elif args.diagnose or args.preflight:browser_mode = "plan_only"elif topic.lower() == "setup":browser_mode = "read" if _setup_allows_browser_cookies(args, extra_argv) else "off"@@ -691,7 +695,7 @@ def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: librowser_mode = "read"return env.ConfigLoadPolicy(browser_cookies=browser_mode,- inspect_ignored_project_config=args.diagnose,+ inspect_ignored_project_config=args.diagnose or args.preflight,)@@ -724,6 +728,21 @@ def main() -> int:if config.get("LAST30DAYS_YOUTUBE_SSH_HOST") and "LAST30DAYS_YOUTUBE_SSH_HOST" not in os.environ:os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = config["LAST30DAYS_YOUTUBE_SSH_HOST"]+ if args.preflight:+ requested_sources = resolve_requested_sources(args.search, config)+ diag = pipeline.diagnose(config, requested_sources, safe=True)+ preflight = permission_preflight.build(+ config,+ diag,+ planned_save_dir=args.save_dir,+ report_on_save_dir=args.preflight_report_on_save_dir,+ )+ if args.emit == "json":+ print(json.dumps(preflight, indent=2, sort_keys=True))+ else:+ print(permission_preflight.render_text(preflight), end="")+ return 0+# Handle setup subcommandif topic.lower() == "setup":from lib import setup_wizarddiff --git a/skills/last30days/scripts/lib/permission_preflight.py b/skills/last30days/scripts/lib/permission_preflight.pynew file mode 100644index 00000000..553af4f8--- /dev/null+++ b/skills/last30days/scripts/lib/permission_preflight.py@@ -0,0 +1,224 @@+"""Permission preflight contract and human renderer."""++from __future__ import annotations++from typing import Any+++ENDPOINT_OVERRIDE_KEYS = {+ "BSKY_SEARCH_HOST",+ "LAST30DAYS_SEARXNG_URL",+ "LAST30DAYS_YOUTUBE_SSH_HOST",+ "OPENAI_BASE_URL",+ "XAI_BASE_URL",+ "XIAOHONGSHU_API_BASE",+}++PROVIDER_CREDENTIALS = {+ "google": "Google/Gemini API key",+ "openai": "OpenAI API key",+ "xai": "xAI API key",+ "openrouter": "OpenRouter API key",+ "perplexity": "Perplexity API key",+ "scrapecreators": "ScrapeCreators API key",+ "github": "GitHub token or gh auth",+}+++def _truthy(value: Any) -> bool:+ if value is None:+ return False+ return str(value).strip().lower() in {"1", "true", "yes", "on"}+++def _status(value: bool) -> str:+ return "available" if value else "unavailable"+++def build(+ config: dict[str, Any],+ diagnose: dict[str, Any],+ *,+ planned_save_dir: str | None = None,+ report_on_save_dir: str | None = None,+) -> dict[str, Any]:+ """Build a stable, secret-free permission preflight object."""+ browser = dict(diagnose.get("browser_cookies") or {})+ browser_mode = str(browser.get("mode") or "off")+ browser_browsers = list(browser.get("browsers") or [])+ browser_enabled = browser_mode in {"read", "plan_only"} and bool(browser_browsers)+ if browser_enabled:+ browser_status = "enabled_by_config"+ else:+ browser_status = "off"++ ignored_project_config = diagnose.get("ignored_project_config")+ config_source = str(diagnose.get("config_source") or "env_only")+ project_config_active = config_source.startswith("project:")+ trust_signal = _truthy(config.get("LAST30DAYS_TRUST_PROJECT_CONFIG"))+ if project_config_active:+ project_status = "trusted_active"+ elif ignored_project_config:+ project_status = "ignored_untrusted"+ else:+ project_status = "not_active"++ local_writes = list(diagnose.get("local_writes") or [])+ if planned_save_dir:+ local_writes = [{"kind": "report", "path": str(planned_save_dir)}]+ conditional_writes: list[dict[str, str]] = []+ if report_on_save_dir and not planned_save_dir:+ conditional_writes.append({"kind": "report_on_save", "path": str(report_on_save_dir)})++ providers = dict(diagnose.get("providers") or {})+ credentials = {+ "google": {"present": bool(providers.get("google")), "label": PROVIDER_CREDENTIALS["google"]},+ "openai": {"present": bool(providers.get("openai")), "label": PROVIDER_CREDENTIALS["openai"]},+ "xai": {"present": bool(providers.get("xai")), "label": PROVIDER_CREDENTIALS["xai"]},+ "openrouter": {"present": bool(providers.get("openrouter")), "label": PROVIDER_CREDENTIALS["openrouter"]},+ "perplexity": {"present": bool(providers.get("perplexity")), "label": PROVIDER_CREDENTIALS["perplexity"]},+ "scrapecreators": {+ "present": bool(diagnose.get("has_scrapecreators")),+ "label": PROVIDER_CREDENTIALS["scrapecreators"],+ },+ "github": {"present": bool(diagnose.get("has_github")), "label": PROVIDER_CREDENTIALS["github"]},+ }++ active_endpoint_overrides = sorted(+ key for key in ENDPOINT_OVERRIDE_KEYS if config.get(key)+ )+ ignored_endpoint_overrides = sorted(diagnose.get("ignored_endpoint_overrides") or [])+ external_commands = {+ name: {"status": _status(bool(available))}+ for name, available in sorted((diagnose.get("external_commands") or {}).items())+ }++ action_items: list[str] = []+ if ignored_project_config:+ action_items.append("Project config was ignored; set LAST30DAYS_TRUST_PROJECT_CONFIG=1 to trust it.")++ return {+ "status": "action_needed" if action_items else "ready",+ "safe": bool(diagnose.get("safe")),+ "local_reads": {+ "config_source": config_source,+ "project_config": {+ "status": project_status,+ "trusted": bool(project_config_active or trust_signal),+ "ignored_path": ignored_project_config,+ "ignored_keys": list(diagnose.get("ignored_project_config_keys") or []),+ },+ "browser_cookies": {+ "status": browser_status,+ "mode": browser_mode,+ "browsers": browser_browsers,+ "reads_values": False,+ },+ },+ "local_writes": local_writes,+ "conditional_writes": conditional_writes,+ "external_commands": external_commands,+ "credentials": credentials,+ "network": {+ "available_sources": list(diagnose.get("available_sources") or []),+ "native_search": bool(diagnose.get("native_search")),+ "endpoint_overrides": active_endpoint_overrides,+ "ignored_endpoint_overrides": ignored_endpoint_overrides,+ },+ "action_items": action_items,+ }+++def _format_names(names: list[str]) -> str:+ return ", ".join(names) if names else "none"+++def render_text(preflight: dict[str, Any]) -> str:+ """Render the permission preflight as concise user-facing text."""+ lines: list[str] = ["last30days preflight"]+ status = preflight.get("status")+ if status == "ready":+ lines.append("Status: Ready to research with safe defaults.")+ else:+ lines.append("Status: Ready, with item(s) to review.")++ reads = preflight.get("local_reads") or {}+ project = reads.get("project_config") or {}+ browser = reads.get("browser_cookies") or {}+ writes = list(preflight.get("local_writes") or [])+ conditional_writes = list(preflight.get("conditional_writes") or [])+ commands = preflight.get("external_commands") or {}+ credentials = preflight.get("credentials") or {}+ network = preflight.get("network") or {}++ lines.append("")+ lines.append("Local reads:")+ lines.append(f"- Config source: {reads.get('config_source') or 'env_only'}")+ if project.get("status") == "ignored_untrusted":+ ignored_keys = _format_names(list(project.get("ignored_keys") or []))+ lines.append(f"- Project config: ignored untrusted file ({ignored_keys})")+ elif project.get("status") == "trusted_active":+ lines.append("- Project config: trusted and active")+ else:+ lines.append("- Project config: not active")+ if browser.get("status") == "enabled_by_config":+ lines.append(+ "- Browser cookies: enabled by config for "+ + _format_names(list(browser.get("browsers") or []))+ + "; preflight did not read cookie values"+ )+ else:+ lines.append("- Browser cookies: off; no browser stores will be read")++ lines.append("")+ lines.append("Local writes:")+ if writes:+ for write in writes:+ lines.append(f"- {write.get('kind', 'file')}: {write.get('path')}")+ else:+ lines.append("- none planned")+ for write in conditional_writes:+ if write.get("kind") == "report_on_save":+ lines.append(f"- Report (if saved): {write.get('path')}")+ else:+ lines.append(f"- {write.get('kind', 'file')} (conditional): {write.get('path')}")++ present_credentials = [+ str(info.get("label") or name)+ for name, info in credentials.items()+ if info.get("present")+ ]+ lines.append("")+ lines.append("Credentials:")+ lines.append("- Present: " + _format_names(present_credentials))+ lines.append("- Values are not printed or written by preflight")++ unavailable_commands = [+ name for name, info in commands.items() if info.get("status") == "unavailable"+ ]+ lines.append("")+ if unavailable_commands:+ lines.append("Optional commands unavailable: " + _format_names(unavailable_commands))+ else:+ lines.append("Optional commands: available")++ endpoint_overrides = list(network.get("endpoint_overrides") or [])+ ignored_endpoint_overrides = list(network.get("ignored_endpoint_overrides") or [])+ lines.append("")+ lines.append("Network:")+ lines.append("- Available sources: " + _format_names(list(network.get("available_sources") or [])))+ if endpoint_overrides:+ lines.append("- Endpoint overrides active: " + _format_names(endpoint_overrides))+ if ignored_endpoint_overrides:+ lines.append("- Endpoint overrides ignored: " + _format_names(ignored_endpoint_overrides))++ action_items = list(preflight.get("action_items") or [])+ lines.append("")+ if action_items:+ lines.append("Next:")+ for item in action_items:+ lines.append(f"- {item}")+ else:+ lines.append("Next: run research normally, or configure optional sources if you need more coverage.")++ return "\n".join(lines) + "\n"diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 52f18ebd..8a322514 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -26,6 +26,7 @@ from . import (instagram,jobs,normalize,+ permission_preflight,perplexity,pinterest,planner,@@ -204,21 +205,13 @@ def diagnose("reads_values": False if safe else config.get("_BROWSER_COOKIE_MODE") == "read",}ignored_project_keys = list(config.get("_IGNORED_PROJECT_CONFIG_KEYS") or [])- endpoint_override_keys = {- "BSKY_SEARCH_HOST",- "LAST30DAYS_SEARXNG_URL",- "LAST30DAYS_YOUTUBE_SSH_HOST",- "OPENAI_BASE_URL",- "XAI_BASE_URL",- "XIAOHONGSHU_API_BASE",- }ignored_endpoint_overrides = [- key for key in ignored_project_keys if key in endpoint_override_keys+ key for key in ignored_project_keys if key in permission_preflight.ENDPOINT_OVERRIDE_KEYS]local_writes: list[dict[str, str]] = []if config.get("LAST30DAYS_MEMORY_DIR"):local_writes.append({"kind": "report", "path": str(config.get("LAST30DAYS_MEMORY_DIR"))})- return {+ diag = {"providers": providers_status,"local_mode": not reasoning_provider_available,"reasoning_provider": (config.get("LAST30DAYS_REASONING_PROVIDER") or "auto").lower(),@@ -244,6 +237,8 @@ def diagnose("credential_destinations": credential_destinations,"local_writes": local_writes,}+ diag["permission_preflight"] = permission_preflight.build(config, diag)+ return diagdef _inner_max_workers(stream_count: int, *, internal_subrun: bool) -> int:diff --git a/tests/test_codex_host_contract.py b/tests/test_codex_host_contract.pyindex 4f021164..9d150c89 100644--- a/tests/test_codex_host_contract.py+++ b/tests/test_codex_host_contract.py@@ -34,6 +34,16 @@ def test_non_modal_cookie_consent_uses_engine_allow_flag():assert consent < decline+def test_non_modal_preflight_runs_before_cookie_consent():+ prose = _prose_flow()+ preflight = prose.index("--preflight")+ consent = prose.index("Cookie consent")+ assert preflight < consent+ assert "does not read browser-cookie values" in prose+ assert "does not write setup/config/report files" in prose+ assert "does not run research" in prose++def test_non_modal_completion_mentions_safe_diagnose_and_project_trust():prose = _prose_flow()assert "safe `--diagnose`" in prosediff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex 5858475b..499d6478 100644--- a/tests/test_doc_flag_contract.py+++ b/tests/test_doc_flag_contract.py@@ -24,6 +24,8 @@ def test_configuration_documents_new_safety_flags():flags = _parser_flags()assert "--no-browser-cookies" in flagsassert "--no-browser-cookies" in text+ assert "--preflight" in flags+ assert "--preflight" in textassert "--save-dir" in textassert "--output" in text@@ -40,4 +42,5 @@ def test_agent_is_documented_as_skill_argument_not_python_flag():start = text.index("## Agent Mode (--agent flag)")agent_section = text[start:start + 2000]assert "If `--agent` appears in ARGUMENTS" in agent_section- assert "Skill tool" in text+ assert "slash-command skill contract" in text+ assert "not a Python CLI flag" in textdiff --git a/tests/test_doc_security_contract.py b/tests/test_doc_security_contract.pyindex 02a1f719..f20235c7 100644--- a/tests/test_doc_security_contract.py+++ b/tests/test_doc_security_contract.py@@ -34,6 +34,28 @@ def test_codex_auth_not_advertised_as_openai_fallback():assert "or Codex auth" not in config+def test_preflight_permission_contract_is_documented():+ config = CONFIGURATION.read_text(encoding="utf-8")+ skill = SKILL_MD.read_text(encoding="utf-8")+ readme = README.read_text(encoding="utf-8")++ for text in (config, skill, readme):+ assert "--preflight" in text+ assert "without reading browser cookies, writing setup/config/report files, or running research" in config+ assert "does not read browser-cookie values" in skill+ assert "without reading cookies, writing files, or running research" in readme+++def test_security_copy_avoids_stale_cookie_and_endpoint_claims():+ skill = SKILL_MD.read_text(encoding="utf-8")+ assert "no browser session access" not in skill+ assert "OpenAI key only goes to api.openai.com" not in skill+ assert "pass `--agent` for non-interactive report output" not in skill+ assert "Codex ChatGPT auth" in skill+ assert "Endpoint destinations follow configured provider base URLs" in skill+ assert "do not read browser-cookie values" in skill++def test_scrapecreators_copy_uses_canonical_free_call_count():text = "\n".join([diff --git a/tests/test_permission_preflight.py b/tests/test_permission_preflight.pynew file mode 100644index 00000000..76a3eaab--- /dev/null+++ b/tests/test_permission_preflight.py@@ -0,0 +1,224 @@+"""Tests for the safe permission preflight contract."""++from __future__ import annotations++import io+import json+import sys+from contextlib import redirect_stderr, redirect_stdout+from unittest import mock++import last30days as cli+from lib import env, permission_preflight, pipeline++DEFAULT_SAVE_DIR = "~" + "/Documents/Last30Days"+++def _diag(**overrides):+ base = {+ "providers": {+ "google": False,+ "openai": False,+ "xai": False,+ "openrouter": False,+ "perplexity": False,+ },+ "has_scrapecreators": False,+ "has_github": False,+ "available_sources": ["reddit", "hackernews", "polymarket"],+ "safe": True,+ "config_source": "env_only",+ "ignored_project_config": None,+ "ignored_project_config_keys": [],+ "ignored_endpoint_overrides": [],+ "browser_cookies": {"mode": "plan_only", "browsers": [], "reads_values": False},+ "external_commands": {"yt-dlp": False, "digg-pp-cli": False, "gh": False},+ "credential_destinations": {"global_env": None},+ "local_writes": [],+ "native_search": False,+ }+ base.update(overrides)+ return base+++def test_preflight_reports_safe_browser_default_without_cookie_values():+ diag = _diag()+ preflight = permission_preflight.build({}, diag)++ assert preflight["status"] == "ready"+ assert preflight["action_items"] == []+ browser = preflight["local_reads"]["browser_cookies"]+ assert browser == {+ "status": "off",+ "mode": "plan_only",+ "browsers": [],+ "reads_values": False,+ }+ text = permission_preflight.render_text(preflight)+ assert "Browser cookies: off" in text+ assert "cookie values" not in text+++def test_preflight_reports_configured_browser_without_reading_values():+ diag = _diag(+ browser_cookies={"mode": "plan_only", "browsers": ["firefox"], "reads_values": False}+ )+ preflight = permission_preflight.build({"FROM_BROWSER": "firefox"}, diag)++ browser = preflight["local_reads"]["browser_cookies"]+ assert browser["status"] == "enabled_by_config"+ assert browser["browsers"] == ["firefox"]+ assert browser["reads_values"] is False+ assert "preflight did not read cookie values" in permission_preflight.render_text(preflight)+++def test_preflight_reports_conditional_report_on_save_without_definite_write():+ preflight = permission_preflight.build(+ {},+ _diag(),+ report_on_save_dir=DEFAULT_SAVE_DIR,+ )++ assert preflight["local_writes"] == []+ assert preflight["conditional_writes"] == [+ {"kind": "report_on_save", "path": DEFAULT_SAVE_DIR}+ ]+ rendered = permission_preflight.render_text(preflight)+ assert "none planned" in rendered+ assert f"Report (if saved): {DEFAULT_SAVE_DIR}" in rendered+++def test_preflight_prefers_definite_save_dir_over_conditional_report_on_save(tmp_path):+ save_dir = tmp_path / "reports"+ preflight = permission_preflight.build(+ {},+ _diag(),+ planned_save_dir=str(save_dir),+ report_on_save_dir=DEFAULT_SAVE_DIR,+ )++ assert preflight["local_writes"] == [{"kind": "report", "path": str(save_dir)}]+ assert preflight["conditional_writes"] == []+++def test_preflight_reports_ignored_project_config_without_secret_values(tmp_path, monkeypatch):+ project_env = tmp_path / ".claude" / "last30days.env"+ project_env.parent.mkdir()+ project_env.write_text(+ "OPENAI_BASE_URL=https://attacker.example\nOPENAI_API_KEY=sk-not-reported\n",+ encoding="utf-8",+ )+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(env, "CONFIG_FILE", None)+ monkeypatch.setenv("OPENAI_API_KEY", "sk-global")+ monkeypatch.delenv("LAST30DAYS_TRUST_PROJECT_CONFIG", raising=False)++ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", return_value={}):+ config = env.get_config(+ policy=env.ConfigLoadPolicy(+ browser_cookies="plan_only",+ inspect_ignored_project_config=True,+ )+ )+ diag = pipeline.diagnose(config, safe=True)++ preflight = diag["permission_preflight"]+ assert preflight["local_reads"]["project_config"]["status"] == "ignored_untrusted"+ assert preflight["network"]["ignored_endpoint_overrides"] == ["OPENAI_BASE_URL"]+ rendered = permission_preflight.render_text(preflight)+ assert "Project config: ignored untrusted file" in rendered+ assert "OPENAI_API_KEY" in rendered+ assert "sk-not-reported" not in str(preflight)+ assert "sk-global" not in str(preflight)+ assert "sk-not-reported" not in rendered+ assert "sk-global" not in rendered+++def test_diagnose_uses_preflight_endpoint_override_key_set():+ ignored_keys = sorted(permission_preflight.ENDPOINT_OVERRIDE_KEYS) + ["UNRELATED_KEY"]+ diag = pipeline.diagnose(+ {+ "_IGNORED_PROJECT_CONFIG_KEYS": ignored_keys,+ "_BROWSER_COOKIE_MODE": "off",+ "_BROWSER_COOKIE_BROWSERS": [],+ },+ safe=True,+ )++ assert sorted(diag["ignored_endpoint_overrides"]) == sorted(+ permission_preflight.ENDPOINT_OVERRIDE_KEYS+ )+++def test_cli_preflight_uses_plan_only_policy_and_does_not_run_research(monkeypatch):+ seen: dict[str, object] = {}++ def fake_get_config(*, policy):+ seen["policy"] = policy+ return {"_BROWSER_COOKIE_MODE": policy.browser_cookies, "_BROWSER_COOKIE_BROWSERS": []}++ with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()) as diagnose, \+ mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("research should not run")), \+ mock.patch.object(sys, "argv", ["last30days.py", "--preflight"]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert seen["policy"].browser_cookies == "plan_only"+ assert seen["policy"].inspect_ignored_project_config is True+ diagnose.assert_called_once()+ assert "last30days preflight" in stdout.getvalue()+ assert "Local writes:" in stdout.getvalue()+++def test_cli_preflight_reports_explicit_save_dir(monkeypatch, tmp_path):+ save_dir = tmp_path / "reports"+ with mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \+ mock.patch.object(sys, "argv", ["last30days.py", "--preflight", "--save-dir", str(save_dir)]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert str(save_dir) in stdout.getvalue()+ assert "report" in stdout.getvalue()+++def test_cli_preflight_reports_conditional_save_dir(monkeypatch):+ with mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \+ mock.patch.object(+ sys,+ "argv",+ [+ "last30days.py",+ "--preflight",+ "--preflight-report-on-save-dir",+ DEFAULT_SAVE_DIR,+ ],+ ):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert f"Report (if saved): {DEFAULT_SAVE_DIR}" in stdout.getvalue()+++def test_cli_preflight_json_returns_structured_contract(monkeypatch):+ with mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \+ mock.patch.object(sys, "argv", ["last30days.py", "--preflight", "--emit=json"]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ payload = json.loads(stdout.getvalue())+ assert payload["local_reads"]["browser_cookies"]["status"] == "off"+ assert payload["conditional_writes"] == []+ assert payload["safe"] is True