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(hooks): stop running last30days on every session start (#1142)
Trevin Chow74fb24635711
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 36733d75..69260fde 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -66,7 +66,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `LAST30DAYS_LIBRARY_OWNER=<name>` - optional feed-level Atom author. Defaults to `last30days research library`.- `LAST30DAYS_LIBRARY_CONTEXT=on|off` - controls passive prior-run context on fresh research reports. It defaults to `on`; matching saved research appears in a short `From your library` section. Set `off` to skip the local index read and leave reports unchanged. Mock runs, eval replays, and internal fan-out subruns do not load library context, keeping fixtures deterministic.- `--publish-password <password>` - optional shared password for `--publish-html` or `library feed --publish`. Prefer `LAST30DAYS_PUBLISH_PASSWORD=<password>` instead so the password is not visible in the process list or shell history. Use a unique non-personal password; never reuse the user's own password. The provider's update key is treated as secret and is not written to stdout, HTML, raw output, or `.publish.json` metadata.-- `--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 the separate machine-readable preflight contract (`--json-profile` does not change it); use `--diagnose` when you need the full source diagnostic JSON.+- `--preflight` - optional permission inspector. 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. First-run setup does not require it. Add `--emit=json` for the separate machine-readable preflight contract (`--json-profile` does not change it); use `--diagnose` when you need the full source diagnostic JSON. `doctor` is the health surface.- `--welcome` - print the first-run welcome text (engine-owned; the skill relays it verbatim on first run). Safe: prints and exits, no reads or writes.- `--record-fixtures <dir>` - developer-only, hidden flag that records scrubbed source responses for the offline research-quality eval harness. It writes `<dir>/http.json`; see the [eval reference](docs/reference/eval.md) before recording or committing fixtures.- `setup --github-start` / `setup --github-poll` - the two-command ScrapeCreators GitHub device-auth split. `--github-start` submits the device flow, copies the code to the clipboard, opens the browser, and returns the code immediately (foreground); `--github-poll` waits for you to authorize and persists the key. `setup --github` still runs both in one shot for back-compat.@@ -106,9 +106,7 @@ Override the global location with `LAST30DAYS_CONFIG_DIR=/path` (or `LAST30DAYS_**File syntax.** One `KEY=value` per line; whitespace around the key and value is trimmed. A line starting with `#` is a comment, and a `#` preceded by whitespace after an unquoted value starts a trailing comment (`RATE=1 # req/sec` stores `1`). A `#` glued to the value is literal (`TOKEN=abc#123` stores `abc#123`). Wrap a value in matching `"` or `'` to keep spaces or a `#` verbatim (`NAME="Jane # Doe"` stores `Jane # Doe`); no backslash escapes or `$VAR` expansion are processed. An empty value is ignored (the one exception is `LAST30DAYS_YT_PLAYER_CLIENT=`, where empty is a deliberate disable), so a secret can never be set to `""`.-The project-scoped file is useful for **intentional per-client setups**: drop a `.claude/last30days.env` into each client folder (`SCRAPECREATORS_API_KEY`, `INCLUDE_SOURCES`, `LAST30DAYS_MEMORY_DIR`, `BSKY_HANDLE`, etc), then opt in with `LAST30DAYS_TRUST_PROJECT_CONFIG=1` from your shell or `~/.config/last30days/.env`. Folder-mode hosts such as Codex desktop do not trust hidden project config by default, and discovery stops at the git root so unrelated parent folders cannot silently influence runs. The SessionStart status hook (`hooks/scripts/check-config.sh`) uses the same trust gate — an untrusted repo's `.claude/last30days.env` is not read at session start.--**`LAST30DAYS_QUIET`** - quiet the SessionStart status hook. When truthy (`1`, `true`, `yes`, `on`), `hooks/scripts/check-config.sh` drops the first-run welcome and the ScrapeCreators tip while keeping the one-line status and the last-run summary. Useful once you have deliberately settled on a set of sources: without it, an install that never adds a key is advised to run the setup wizard at every session start indefinitely. Resolves like the other settings here, process environment first, then `~/.config/last30days/.env`, then a trusted project file. Unset or falsy leaves the output byte-for-byte as before.+The project-scoped file is useful for **intentional per-client setups**: drop a `.claude/last30days.env` into each client folder (`SCRAPECREATORS_API_KEY`, `INCLUDE_SOURCES`, `LAST30DAYS_MEMORY_DIR`, `BSKY_HANDLE`, etc), then opt in with `LAST30DAYS_TRUST_PROJECT_CONFIG=1` from your shell or `~/.config/last30days/.env`. Folder-mode hosts such as Codex desktop do not trust hidden project config by default, and discovery stops at the git root so unrelated parent folders cannot silently influence runs. An untrusted repo's `.claude/last30days.env` is not read.**`LAST30DAYS_API_KEY`** + **`LAST30DAYS_API_BASE`** - optional remote-API backend. Set BOTH to route research through a remote API endpoint instead of running the local sources: `LAST30DAYS_API_BASE` is the endpoint (there is no built-in default), and `LAST30DAYS_API_KEY` is the bearer key for it. When both are set (and `--mock` is not passed), the engine submits the topic to that endpoint, polls with progress on stderr, and prints the server's report; none of the per-source keys below are used for that run. A configured local corpus is the privacy exception: the engine bypasses the hosted backend and runs locally rather than forwarding file-derived input. Non-default `--register` selections are forwarded with the request so server-side synthesis uses the same audience preset. Leave either unset to run local sources exactly as normal. Unlike the other keys here, these two are read only from the **process environment** (export them in your shell or host config) - they are deliberately not loaded from the `.env` files above, so a project-scoped `.env` can never silently redirect research to a remote endpoint. The remote endpoint does not return the local `Report` needed for the versioned agent JSON profile; use `--emit=json --json-profile=raw` for its existing server-response JSON contract.@@ -300,10 +298,9 @@ everything is already in `.env`.Effective credential priority is: process env > trusted project config(`.claude/last30days.env`) > global config (`~/.config/last30days/.env`) >-macOS Keychain > `pass`(1). The SessionStart status hook also checks for-Keychain item **presence** under `last30days-<KEY>` without reading secret-values, so a Keychain-only setup is treated as configured instead of showing the-first-run welcome again.+macOS Keychain > `pass`(1). A Keychain-only setup still counts as configured:+the engine resolves `last30days-<KEY>` at runtime. First-run in SKILL.md+Step 0 must not treat a missing `.env` as unconfigured.| Platform | Source | Store keys with | Lookup convention ||---|---|---|---|diff --git a/README.de.md b/README.de.mdindex 34a1b513..8fe3e063 100644--- a/README.de.md+++ b/README.de.md@@ -215,7 +215,7 @@ npx skills add mvanhorn/last30days-skill -gDas Flag `-g` (global) installiert in dein Benutzerverzeichnis, sodass die Skill in allen Projekten verfügbar ist. Ohne `-g` installiert `npx skills` projektlokal nach `./.skills/` (und wird mit dem Repository eingecheckt). Für ein Werkzeug, mit dem du die ganze Welt recherchierst, willst du die globale Installation.-Codex Desktop und andere Hosts, die auf Ordnerebene arbeiten, funktionieren sowohl in gewöhnlichen Ordnern als auch in Git-Repositories. Bitte den Host-Agenten vor der ersten Recherche, das mitgelieferte `scripts/last30days.py --preflight` aus dem geladenen Skill-Verzeichnis auszuführen; in einem Checkout des Quellcodes lautet der entsprechende Befehl `python3 skills/last30days/scripts/last30days.py --preflight`. Er zeigt dir, woher die Konfiguration stammt, welche Browser-Cookies gelesen würden, welche Dateien geschrieben würden, welche optionalen Befehle es gibt und welche Projektkonfiguration ignoriert wird – ohne Cookies zu lesen, Dateien zu schreiben oder eine Recherche zu starten.+Codex Desktop und andere Hosts, die auf Ordnerebene arbeiten, funktionieren sowohl in gewöhnlichen Ordnern als auch in Git-Repositories. Um zu prüfen, was ein Lauf lesen und schreiben würde, ohne eine Recherche zu starten, führe das mitgelieferte `scripts/last30days.py --preflight` aus dem geladenen Skill-Verzeichnis aus; in einem Checkout des Quellcodes lautet der entsprechende Befehl `python3 skills/last30days/scripts/last30days.py --preflight`. Er zeigt dir, woher die Konfiguration stammt, welche Browser-Cookies gelesen würden, welche Dateien geschrieben würden, welche optionalen Befehle es gibt und welche Projektkonfiguration ignoriert wird – ohne Cookies zu lesen, Dateien zu schreiben oder eine Recherche zu starten. Die Ersteinrichtung braucht das nicht.Standardmäßig wird für den Host installiert, den `npx skills` erkennt. Um gezielt einen (oder mehrere) anzusprechen:@@ -333,7 +333,7 @@ Die vollständige Schlüsselmatrix pro Quelle, die Priorität der Reasoning-AnbiZwei Dinge, die du vermutlich schon am ersten Tag wissen willst:-**Wo die Rechercheergebnisse landen.** `LAST30DAYS_MEMORY_DIR` zeigt standardmäßig auf `~/Documents/Last30Days/` (unter Windows: `C:\Users\<you>\Documents\Last30Days\`). Überschreib das, indem du die Umgebungsvariable in deiner Shell auf einen beliebigen Pfad setzt, oder mit `--save-dir <path>` pro Durchlauf. Nutze `--output <file>`, wenn du das gerenderte Ergebnis an einem exakten Pfad brauchst – im Format, das `--emit` vorgibt. Mit `--save-suffix=<name>` hältst du mehrere Varianten desselben Themas auseinander (etwa pro Kunde). Jeder Durchlauf mit `--save-dir` erzeugt `<slug>-raw[-suffix].md`. Mit `python3 skills/last30days/scripts/last30days.py --preflight` siehst du vor einer Recherche, welche Dateien geschrieben würden.+**Wo die Rechercheergebnisse landen.** `LAST30DAYS_MEMORY_DIR` zeigt standardmäßig auf `~/Documents/Last30Days/` (unter Windows: `C:\Users\<you>\Documents\Last30Days\`). Überschreib das, indem du die Umgebungsvariable in deiner Shell auf einen beliebigen Pfad setzt, oder mit `--save-dir <path>` pro Durchlauf. Nutze `--output <file>`, wenn du das gerenderte Ergebnis an einem exakten Pfad brauchst – im Format, das `--emit` vorgibt. Mit `--save-suffix=<name>` hältst du mehrere Varianten desselben Themas auseinander (etwa pro Kunde). Jeder Durchlauf mit `--save-dir` erzeugt `<slug>-raw[-suffix].md`. Optional zeigt `python3 skills/last30days/scripts/last30days.py --preflight`, welche Dateien geschrieben würden, ohne eine Recherche zu starten.**Strukturierte Ausgabe für Agenten und Workflows.** Bitte `/last30days` um maschinenlesbares JSON, dann bekommst du das stabile, versionierte Agentenprofil. Für den direkten Einsatz der Engine in Skripten oder in der Entwicklung führst du `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json` aus; `--json-profile=raw` brauchst du nur, wenn du den unversionierten internen `Report`-Dump willst. Siehe die [Feldreferenz des JSON-Exports samt Versionierungsrichtlinie](docs/reference/json-export.md).diff --git a/README.es.md b/README.es.mdindex 17381156..a19abc70 100644--- a/README.es.md+++ b/README.es.md@@ -215,7 +215,7 @@ npx skills add mvanhorn/last30days-skill -gEl flag `-g` (global) instala en tu directorio de usuario, de modo que la skill queda disponible en todos los proyectos. Sin `-g`, `npx skills` instala solo en el proyecto, dentro de `./.skills/` (y se versiona con el repositorio). Para una herramienta que sirve para investigar el mundo entero, lo que quieres es la instalación global.-Codex de escritorio y otros hosts que trabajan a nivel de carpeta funcionan tanto en carpetas normales como en repositorios Git. Antes de la primera investigación, pídele al agente anfitrión que ejecute el `scripts/last30days.py --preflight` incluido desde el directorio de la skill cargada; en un clon del código fuente, el comando equivalente es `python3 skills/last30days/scripts/last30days.py --preflight`. Te muestra de dónde sale la configuración, qué cookies del navegador se leerían, qué archivos se escribirían, qué comandos opcionales hay y qué configuración de proyecto se ignora, todo ello sin leer cookies, sin escribir archivos y sin lanzar ninguna investigación.+Codex de escritorio y otros hosts que trabajan a nivel de carpeta funcionan tanto en carpetas normales como en repositorios Git. Para inspeccionar qué leería y escribiría una ejecución sin lanzar investigación, ejecuta el `scripts/last30days.py --preflight` incluido desde el directorio de la skill cargada; en un clon del código fuente, el comando equivalente es `python3 skills/last30days/scripts/last30days.py --preflight`. Te muestra de dónde sale la configuración, qué cookies del navegador se leerían, qué archivos se escribirían, qué comandos opcionales hay y qué configuración de proyecto se ignora, todo ello sin leer cookies, sin escribir archivos y sin lanzar ninguna investigación. La configuración del primer uso no lo exige.Por defecto se instala para el host que detecte `npx skills`. Para apuntar a uno concreto (o a varios):@@ -333,7 +333,7 @@ Consulta [CONFIGURATION.md](CONFIGURATION.md) para ver la matriz completa de claDos cosas que seguramente querrás saber desde el primer día:-**Dónde se guardan los archivos de investigación.** `LAST30DAYS_MEMORY_DIR` apunta por defecto a `~/Documents/Last30Days/` (en Windows: `C:\Users\<you>\Documents\Last30Days\`). Puedes cambiarlo definiendo esa variable de entorno en tu shell con la ruta que quieras, o con `--save-dir <path>` en una ejecución concreta. Usa `--output <file>` cuando necesites el resultado renderizado en una ruta exacta, con el formato que elijas en `--emit`. Usa `--save-suffix=<name>` para mantener separadas varias variantes del mismo tema (por cliente, por ejemplo). Cada ejecución con `--save-dir` genera `<slug>-raw[-suffix].md`. Ejecuta `python3 skills/last30days/scripts/last30days.py --preflight` para revisar qué se va a escribir antes de lanzar una investigación.+**Dónde se guardan los archivos de investigación.** `LAST30DAYS_MEMORY_DIR` apunta por defecto a `~/Documents/Last30Days/` (en Windows: `C:\Users\<you>\Documents\Last30Days\`). Puedes cambiarlo definiendo esa variable de entorno en tu shell con la ruta que quieras, o con `--save-dir <path>` en una ejecución concreta. Usa `--output <file>` cuando necesites el resultado renderizado en una ruta exacta, con el formato que elijas en `--emit`. Usa `--save-suffix=<name>` para mantener separadas varias variantes del mismo tema (por cliente, por ejemplo). Cada ejecución con `--save-dir` genera `<slug>-raw[-suffix].md`. Opcionalmente, ejecuta `python3 skills/last30days/scripts/last30days.py --preflight` para revisar qué se va a escribir sin lanzar una investigación.**Salida estructurada para agentes y flujos de trabajo.** Pídele a `/last30days` JSON legible por máquina y obtendrás el perfil de agente estable y versionado. Para usar el motor directamente en scripts o en desarrollo, ejecuta `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json`; añade `--json-profile=raw` solo si necesitas el volcado interno sin versionar de `Report`. Consulta la [referencia de campos de la exportación JSON y la política de versionado](docs/reference/json-export.md).diff --git a/README.fr.md b/README.fr.mdindex da0b186a..8e9f4059 100644--- a/README.fr.md+++ b/README.fr.md@@ -215,7 +215,7 @@ npx skills add mvanhorn/last30days-skill -gLe flag `-g` (global) installe dans votre répertoire utilisateur, ce qui rend la skill disponible dans tous vos projets. Sans `-g`, `npx skills` installe localement dans `./.skills/` (versionné avec le dépôt). Pour un outil qui sert à explorer le monde entier, c'est bien l'installation globale que vous voulez.-Codex desktop et les autres hôtes qui travaillent au niveau du dossier fonctionnent aussi bien dans un dossier ordinaire que dans un dépôt Git. Avant la première recherche, demandez à l'agent hôte de lancer le `scripts/last30days.py --preflight` fourni depuis le répertoire de la skill chargée ; dans un clone du dépôt source, la commande équivalente est `python3 skills/last30days/scripts/last30days.py --preflight`. Elle affiche l'origine de la configuration, le plan de lecture des cookies de navigateur, les fichiers qui seront écrits, les commandes optionnelles et la configuration projet ignorée — sans lire de cookies, sans écrire de fichier et sans lancer de recherche.+Codex desktop et les autres hôtes qui travaillent au niveau du dossier fonctionnent aussi bien dans un dossier ordinaire que dans un dépôt Git. Pour inspecter ce qu'une exécution lirait et écrirait sans lancer de recherche, lancez le `scripts/last30days.py --preflight` fourni depuis le répertoire de la skill chargée ; dans un clone du dépôt source, la commande équivalente est `python3 skills/last30days/scripts/last30days.py --preflight`. Elle affiche l'origine de la configuration, le plan de lecture des cookies de navigateur, les fichiers qui seront écrits, les commandes optionnelles et la configuration projet ignorée — sans lire de cookies, sans écrire de fichier et sans lancer de recherche. La configuration du premier lancement n'en a pas besoin.Par défaut, l'installation cible l'hôte que `npx skills` détecte. Pour en viser un en particulier (ou plusieurs) :@@ -333,7 +333,7 @@ Voir [CONFIGURATION.md](CONFIGURATION.md) pour la matrice complète des clés paDeux choses que vous voudrez sans doute savoir dès le premier jour :-**Où sont enregistrés les fichiers de recherche.** `LAST30DAYS_MEMORY_DIR` vaut par défaut `~/Documents/Last30Days/` (sous Windows : `C:\Users\<you>\Documents\Last30Days\`). Redéfinissez cette variable d'environnement dans votre shell pour pointer ailleurs, ou passez `--save-dir <path>` sur une exécution. Utilisez `--output <file>` quand vous voulez le résultat rendu à un chemin précis, dans le format choisi par `--emit`. Utilisez `--save-suffix=<name>` pour garder séparées plusieurs variantes d'un même sujet (par client, par exemple). Chaque exécution avec `--save-dir` produit `<slug>-raw[-suffix].md`. Lancez `python3 skills/last30days/scripts/last30days.py --preflight` pour vérifier les écritures prévues avant une recherche.+**Où sont enregistrés les fichiers de recherche.** `LAST30DAYS_MEMORY_DIR` vaut par défaut `~/Documents/Last30Days/` (sous Windows : `C:\Users\<you>\Documents\Last30Days\`). Redéfinissez cette variable d'environnement dans votre shell pour pointer ailleurs, ou passez `--save-dir <path>` sur une exécution. Utilisez `--output <file>` quand vous voulez le résultat rendu à un chemin précis, dans le format choisi par `--emit`. Utilisez `--save-suffix=<name>` pour garder séparées plusieurs variantes d'un même sujet (par client, par exemple). Chaque exécution avec `--save-dir` produit `<slug>-raw[-suffix].md`. Vous pouvez lancer `python3 skills/last30days/scripts/last30days.py --preflight` pour vérifier les écritures prévues sans lancer de recherche.**Sortie structurée pour les agents et les workflows.** Demandez à `/last30days` du JSON exploitable par une machine pour obtenir le profil d'agent stable et versionné. Pour un usage direct du moteur en script ou en développement, lancez `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json` ; n'ajoutez `--json-profile=raw` que si vous avez besoin du dump interne non versionné de `Report`. Voir la [référence des champs de l'export JSON et la politique de versionnement](docs/reference/json-export.md).diff --git a/README.ja.md b/README.ja.mdindex 2f27278c..ffdb73d5 100644--- a/README.ja.md+++ b/README.ja.md@@ -215,7 +215,7 @@ npx skills add mvanhorn/last30days-skill -g`-g`(グローバル)フラグを付けるとユーザーディレクトリにインストールされ、スキルをすべてのプロジェクトで使えます。`-g` を付けない場合、`npx skills` はプロジェクト内の `./.skills/` にインストールし、リポジトリと一緒にコミットされます。世界中を調べるためのツールなので、通常はグローバルが向いています。-Codex のデスクトップ版など、フォルダ単位で動くホストは、Git リポジトリでも普通のフォルダでも動作します。最初の調査を始める前に、読み込み済みのスキルディレクトリから同梱の `scripts/last30days.py --preflight` を実行するようホストのエージェントに頼んでください。ソースをチェックアウトしている場合、同等のコマンドは `python3 skills/last30days/scripts/last30days.py --preflight` です。設定の取得元、ブラウザのクッキーをどう扱う予定か、どのファイルを書き込む予定か、任意で使えるコマンド、無視されるプロジェクト設定を表示します。クッキーの読み取りもファイルの書き込みも調査の実行もしません。+Codex のデスクトップ版など、フォルダ単位で動くホストは、Git リポジトリでも普通のフォルダでも動作します。調査を始めずに読み書き予定を確認するには、読み込み済みのスキルディレクトリから同梱の `scripts/last30days.py --preflight` を実行してください。ソースをチェックアウトしている場合、同等のコマンドは `python3 skills/last30days/scripts/last30days.py --preflight` です。設定の取得元、ブラウザのクッキーをどう扱う予定か、どのファイルを書き込む予定か、任意で使えるコマンド、無視されるプロジェクト設定を表示します。クッキーの読み取りもファイルの書き込みも調査の実行もしません。初回セットアップでは必須ではありません。既定では、`npx skills` が検出したホスト向けにインストールされます。特定のホスト(または複数)を指定するには次のようにします。@@ -332,7 +332,7 @@ skills/last30days/scripts/setup-keychain.sh --delete XAI_API_KEY初日に知っておくとよいことが2つあります。-**調査ファイルの保存先。** `LAST30DAYS_MEMORY_DIR` の既定値は `~/Documents/Last30Days/` です(Windows では `C:\Users\<you>\Documents\Last30Days\`)。変更したい場合は、シェルでこの環境変数に任意のパスを設定するか、実行ごとに `--save-dir <path>` を指定します。レンダリング結果を特定のパスに出力したいときは `--output <file>` を使い、形式は `--emit` で選びます。同じトピックの複数のバリエーションを分けて残したいときは `--save-suffix=<name>` を使ってください(クライアントごとに分ける場合など)。`--save-dir` を付けた実行では `<slug>-raw[-suffix].md` が生成されます。調査を走らせる前に書き込み予定を確認するには `python3 skills/last30days/scripts/last30days.py --preflight` を実行してください。+**調査ファイルの保存先。** `LAST30DAYS_MEMORY_DIR` の既定値は `~/Documents/Last30Days/` です(Windows では `C:\Users\<you>\Documents\Last30Days\`)。変更したい場合は、シェルでこの環境変数に任意のパスを設定するか、実行ごとに `--save-dir <path>` を指定します。レンダリング結果を特定のパスに出力したいときは `--output <file>` を使い、形式は `--emit` で選びます。同じトピックの複数のバリエーションを分けて残したいときは `--save-suffix=<name>` を使ってください(クライアントごとに分ける場合など)。`--save-dir` を付けた実行では `<slug>-raw[-suffix].md` が生成されます。調査を走らせずに書き込み予定を確認するには、任意で `python3 skills/last30days/scripts/last30days.py --preflight` を実行してください。**エージェントやワークフロー向けの構造化出力。** `/last30days` に機械可読なJSONを求めると、安定したバージョン付きのエージェント向けプロファイルが返ります。スクリプトや開発でエンジンを直接使う場合は `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json` を実行してください。バージョン管理されていない内部の `Report` のダンプが必要なときだけ `--json-profile=raw` を追加します。[JSONエクスポートのフィールド一覧とバージョニング方針](docs/reference/json-export.md)も参照してください。diff --git a/README.md b/README.mdindex 9adf87c5..68b566b9 100644--- a/README.md+++ b/README.md@@ -215,7 +215,7 @@ 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.+Codex desktop and other folder-mode hosts can work in ordinary folders as well as Git repos. To inspect what a run would read and write without starting research, 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. First-run setup does not require it.By default this installs for whichever harness `npx skills` detects. To target a specific one (or multiple):@@ -332,7 +332,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`. Run `python3 skills/last30days/scripts/last30days.py --preflight` to review planned writes before a research run.+**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`. Optionally run `python3 skills/last30days/scripts/last30days.py --preflight` to review planned writes without starting research.**Structured output for agents and workflows.** Ask `/last30days` for machine-readable JSON to receive the stable, versioned agent profile. For direct engine use in scripts or development, run `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json`; add `--json-profile=raw` only when you need the unversioned internal `Report` dump. See the [JSON export field reference and versioning policy](docs/reference/json-export.md).diff --git a/README.pt-BR.md b/README.pt-BR.mdindex 08d6ca23..6387eeeb 100644--- a/README.pt-BR.md+++ b/README.pt-BR.md@@ -215,7 +215,7 @@ npx skills add mvanhorn/last30days-skill -gA flag `-g` (global) instala no seu diretório de usuário, então a skill fica disponível em todos os projetos. Sem `-g`, o `npx skills` instala só no projeto, dentro de `./.skills/` (e vai versionado junto com o repositório). Para uma ferramenta feita para pesquisar o mundo inteiro, o que você quer é a instalação global.-O Codex desktop e outros hosts que trabalham no nível de pasta funcionam tanto em pastas comuns quanto em repositórios Git. Antes da primeira pesquisa, peça ao agente host que rode o `scripts/last30days.py --preflight` que acompanha a skill, a partir do diretório da skill carregada; em um clone do código-fonte, o comando equivalente é `python3 skills/last30days/scripts/last30days.py --preflight`. Ele mostra de onde vem a configuração, quais cookies do navegador seriam lidos, quais arquivos seriam escritos, quais comandos opcionais existem e qual configuração de projeto está sendo ignorada — sem ler cookies, sem escrever arquivos e sem rodar pesquisa nenhuma.+O Codex desktop e outros hosts que trabalham no nível de pasta funcionam tanto em pastas comuns quanto em repositórios Git. Para inspecionar o que uma execução leria e escreveria sem iniciar pesquisa, rode o `scripts/last30days.py --preflight` que acompanha a skill, a partir do diretório da skill carregada; em um clone do código-fonte, o comando equivalente é `python3 skills/last30days/scripts/last30days.py --preflight`. Ele mostra de onde vem a configuração, quais cookies do navegador seriam lidos, quais arquivos seriam escritos, quais comandos opcionais existem e qual configuração de projeto está sendo ignorada — sem ler cookies, sem escrever arquivos e sem rodar pesquisa nenhuma. A configuração da primeira execução não exige isso.Por padrão, a instalação vale para o host que o `npx skills` detectar. Para mirar em um específico (ou em vários):@@ -333,7 +333,7 @@ Veja [CONFIGURATION.md](CONFIGURATION.md) para a matriz completa de chaves por fDuas coisas que você provavelmente vai querer saber no primeiro dia:-**Onde os arquivos de pesquisa são salvos.** O `LAST30DAYS_MEMORY_DIR` aponta por padrão para `~/Documents/Last30Days/` (no Windows: `C:\Users\<you>\Documents\Last30Days\`). Para mudar, defina essa variável de ambiente no seu shell com o caminho que quiser, ou use `--save-dir <path>` em uma execução específica. Use `--output <file>` quando precisar do resultado renderizado em um caminho exato, no formato escolhido por `--emit`. Use `--save-suffix=<name>` para manter separadas várias variações do mesmo assunto (por cliente, por exemplo). Cada execução com `--save-dir` gera `<slug>-raw[-suffix].md`. Rode `python3 skills/last30days/scripts/last30days.py --preflight` para conferir o que será escrito antes de disparar uma pesquisa.+**Onde os arquivos de pesquisa são salvos.** O `LAST30DAYS_MEMORY_DIR` aponta por padrão para `~/Documents/Last30Days/` (no Windows: `C:\Users\<you>\Documents\Last30Days\`). Para mudar, defina essa variável de ambiente no seu shell com o caminho que quiser, ou use `--save-dir <path>` em uma execução específica. Use `--output <file>` quando precisar do resultado renderizado em um caminho exato, no formato escolhido por `--emit`. Use `--save-suffix=<name>` para manter separadas várias variações do mesmo assunto (por cliente, por exemplo). Cada execução com `--save-dir` gera `<slug>-raw[-suffix].md`. Opcionalmente, rode `python3 skills/last30days/scripts/last30days.py --preflight` para conferir o que será escrito sem disparar uma pesquisa.**Saída estruturada para agentes e fluxos de trabalho.** Peça ao `/last30days` um JSON legível por máquina e você recebe o perfil de agente estável e versionado. Para usar o motor direto em scripts ou no desenvolvimento, rode `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json`; use `--json-profile=raw` só quando precisar do dump interno não versionado do `Report`. Veja a [referência de campos da exportação JSON e a política de versionamento](docs/reference/json-export.md).diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 165ac220..acf2c3e6 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -218,7 +218,7 @@ npx skills add mvanhorn/last30days-skill -g`-g`(全局)参数会把 Skill 安装到用户目录,因此所有项目均可使用。不加 `-g` 时,`npx skills` 会安装到当前项目的 `./.skills/` 中,并随仓库提交。对于一个用于研究整个世界的工具,全局安装通常更合适。-Codex 桌面版和其他以文件夹为工作区的宿主,不仅能在 Git 仓库中运行,也能在普通文件夹中工作。第一次研究前,请让宿主智能体从已加载的 Skill 目录运行随附的 `scripts/last30days.py --preflight`;若在源码仓库中,则运行等价命令 `python3 skills/last30days/scripts/last30days.py --preflight`。该命令会展示配置来源、浏览器 Cookie 方案、计划写入的文件、可选命令和被忽略的项目配置,但不会读取 Cookie、写入文件或执行研究。+Codex 桌面版和其他以文件夹为工作区的宿主,不仅能在 Git 仓库中运行,也能在普通文件夹中工作。若要在不启动研究的情况下检查一次运行会读取和写入什么,请从已加载的 Skill 目录运行随附的 `scripts/last30days.py --preflight`;若在源码仓库中,则运行等价命令 `python3 skills/last30days/scripts/last30days.py --preflight`。该命令会展示配置来源、浏览器 Cookie 方案、计划写入的文件、可选命令和被忽略的项目配置,但不会读取 Cookie、写入文件或执行研究。首次设置并不要求运行它。默认情况下,`npx skills` 会安装到它自动检测到的宿主。若要指定一个或多个宿主:@@ -331,7 +331,7 @@ skills/last30days/scripts/setup-keychain.sh --delete XAI_API_KEY第一天使用时,你大概最想知道以下两件事:-**研究文件保存在哪里。** `LAST30DAYS_MEMORY_DIR` 默认指向 `~/Documents/Last30Days/`(Windows:`C:\Users\<you>\Documents\Last30Days\`)。可以在 shell 中把该环境变量设为任意路径,也可以为单次运行传入 `--save-dir <path>`。若需要把渲染结果精确写入某个路径,请使用 `--output <file>`;文件格式由 `--emit` 决定。使用 `--save-suffix=<name>` 可分别保存同一主题的多个版本(例如按客户区分)。每次使用 `--save-dir` 都会生成 `<slug>-raw[-suffix].md`。研究前运行 `python3 skills/last30days/scripts/last30days.py --preflight`,可预览计划写入的内容。+**研究文件保存在哪里。** `LAST30DAYS_MEMORY_DIR` 默认指向 `~/Documents/Last30Days/`(Windows:`C:\Users\<you>\Documents\Last30Days\`)。可以在 shell 中把该环境变量设为任意路径,也可以为单次运行传入 `--save-dir <path>`。若需要把渲染结果精确写入某个路径,请使用 `--output <file>`;文件格式由 `--emit` 决定。使用 `--save-suffix=<name>` 可分别保存同一主题的多个版本(例如按客户区分)。每次使用 `--save-dir` 都会生成 `<slug>-raw[-suffix].md`。可选运行 `python3 skills/last30days/scripts/last30days.py --preflight`,在不启动研究的情况下预览计划写入的内容。**面向智能体和工作流的结构化输出。** 让 `/last30days` 输出机器可读的 JSON,即可获得稳定且带版本号的 agent profile。若在脚本或开发中直接调用引擎,可运行 `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json`;只有确实需要未版本化的内部 `Report` 转储时,才添加 `--json-profile=raw`。详见 [JSON 导出字段参考与版本策略](docs/reference/json-export.md)。diff --git a/changelog.d/+quiet-session-start-hook.added.md b/changelog.d/+quiet-session-start-hook.added.mddeleted file mode 100644index c95e5a8d..00000000--- a/changelog.d/+quiet-session-start-hook.added.md+++ /dev/null@@ -1 +0,0 @@-`LAST30DAYS_QUIET` quiets the SessionStart status hook. Setting it to a truthy value (`1`, `true`, `yes`, `on`) drops the first-run welcome and the ScrapeCreators tip while keeping the one-line status and the last-run summary. Previously there was no way to turn either off: an install that deliberately stays on the free sources was advised to run the setup wizard at every session start, in every project, indefinitely. The variable resolves through the existing precedence chain (process environment, then the global `.env`, then a trusted project file), and is a no-op when unset or falsy.diff --git a/changelog.d/+session-start-hook.removed.md b/changelog.d/+session-start-hook.removed.mdnew file mode 100644index 00000000..4dbcd8de--- /dev/null+++ b/changelog.d/+session-start-hook.removed.md@@ -0,0 +1 @@+The Claude Code and Grok plugin no longer installs a SessionStart hook. Welcome, source status, and the ScrapeCreators tip run only when `/last30days` is invoked (SKILL.md Step 0). `--preflight` remains as an opt-in permission inspector and MCP JSON contract; it is not a required first-run step. `LAST30DAYS_QUIET` is gone with the hook. The engine still creates `LAST30DAYS_MEMORY_DIR` on first save.diff --git a/docs/solutions/workflow-issues/session-start-hook-not-for-skill-nux.md b/docs/solutions/workflow-issues/session-start-hook-not-for-skill-nux.mdnew file mode 100644index 00000000..691d02ee--- /dev/null+++ b/docs/solutions/workflow-issues/session-start-hook-not-for-skill-nux.md@@ -0,0 +1,50 @@+---+title: Skill NUX belongs in SKILL.md Step 0, not a SessionStart hook+date: 2026-09-17+category: docs/solutions/workflow-issues+module: skills/last30days/SKILL.md+problem_type: workflow_issue+component: development_workflow+severity: medium+symptoms:+ - Claude Code or Grok sessions print last30days status even when /last30days is not invoked+ - ~/Documents/Last30Days is created on every session start+ - Unconfigured installs see a setup-wizard pitch in every project, indefinitely+root_cause: design_error+resolution_type: code_fix+related_components:+ - hooks/hooks.json+ - hooks/scripts/check-config.sh+ - last30days.py --preflight+tags:+ - session-start+ - nux+ - preflight+ - plugin-hooks+ - onboarding+---++# Skill NUX belongs in SKILL.md Step 0, not a SessionStart hook++## Problem++The plugin installed a `SessionStart` hook (`hooks/scripts/check-config.sh`) that ran in every Claude Code and Grok session, in every project, whether or not anyone invoked `/last30days`. It printed a welcome or source-count banner, optionally upsold ScrapeCreators, created `~/Documents/Last30Days`, scanned Keychain item names, and auto-chmod'd `.env` files.++That is the wrong layer for skill onboarding. A trusted plugin hook cannot be "just for last30days users."++## Root cause++[PR #58](https://github.com/mvanhorn/last30days-skill/pull/58) (2026-03-10) added a silent-when-configured missing-keys warning. [PR #126](https://github.com/mvanhorn/last30days-skill/pull/126) (v2.9.6) rewrote it into an always-print NUX. Later PRs piled on mkdir (#476), Keychain presence, and security patches (#914 cwd-adjacent `.env` RCE, #1074 decoy `check-config.sh` from session cwd). `--preflight` in the non-modal first-run flow was a second copy of the same permission summary.++SKILL.md Step 0 already owns consent (cookies, ScrapeCreators). The engine already creates the save dir on first save. `last30days.py --preflight` is a secret-free inspector for humans, scripts, and the MCP `preflight` tool — not a required first-run beat.++## Solution++- Do not ship `hooks/hooks.json` or a SessionStart command. Plugin auto-discovery would load it.+- First-run NUX stays in SKILL.md Step 0 (modal / non-modal / Grok Bot). Detect setup from key presence; do not dump `.env`.+- `--preflight` stays as an opt-in inspector and frozen JSON contract. Do not run it as a required first-run step.+- `lib/preflight.py` (Class 1 query refuse-gate) is unrelated and stays in the engine.++## Prevention++If a future change wants "status at session start," put it behind an explicit user-installed hook or a slash-command invocation. A marketplace plugin SessionStart hook is not an opt-in.diff --git a/hooks/hooks.json b/hooks/hooks.jsondeleted file mode 100644index 0c88bc40..00000000--- a/hooks/hooks.json+++ /dev/null@@ -1,15 +0,0 @@-{- "hooks": {- "SessionStart": [- {- "matcher": "",- "hooks": [- {- "type": "command",- "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/check-config.sh\""- }- ]- }- ]- }-}diff --git a/hooks/scripts/check-config.sh b/hooks/scripts/check-config.shdeleted file mode 100755index 36572cb8..00000000--- a/hooks/scripts/check-config.sh+++ /dev/null@@ -1,365 +0,0 @@-#!/bin/bash-set -euo pipefail--# Check last30days configuration status and show appropriate welcome message.-# Priority for this status hook (mirrors lib/env.py):-# process env > trusted .claude/last30days.env > ~/.config/last30days/.env > Keychain presence-# Project-scoped config is loaded only when LAST30DAYS_TRUST_PROJECT_CONFIG is-# truthy in the process environment or the global config file — never from the-# project file itself (it cannot self-grant trust).--GLOBAL_ENV="$HOME/.config/last30days/.env"-if [[ "${LAST30DAYS_CONFIG_DIR+x}" == "x" ]]; then- if [[ -n "$LAST30DAYS_CONFIG_DIR" ]]; then- GLOBAL_ENV="$LAST30DAYS_CONFIG_DIR/.env"- else- GLOBAL_ENV=""- fi-fi--# Ensure LAST30DAYS_MEMORY_DIR exists for HTML-brief / raw-markdown saves.-# SKILL.md and the engine default this via the same env-var fallback. Fresh-# installs otherwise fail silently on first --emit=html run. See #395.-mkdir -p "${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}" 2>/dev/null || true--# Helper: warn if file permissions are too open-check_perms() {- local file="$1"- if [[ ! -f "$file" ]]; then return; fi- # Git-for-Windows / MSYS / Cygwin run stat in noacl mode (always 644),- # so this POSIX check is a false positive. Windows perms use ACLs.- case "$(uname -s 2>/dev/null)" in- MINGW*|MSYS*|CYGWIN*) return ;;- esac- local perms- # Try GNU stat first (Linux), fall back to BSD stat (macOS).- # On Linux, `stat -f` prints filesystem info (not permissions) and exits 0,- # so the previous BSD-first ordering left $perms as multi-line garbage on- # every Linux session start and printed a false WARNING.- perms=$(stat -c '%a' "$file" 2>/dev/null || stat -f '%Lp' "$file" 2>/dev/null || echo "")- if [[ -n "$perms" && "$perms" != "600" && "$perms" != "400" ]]; then- chmod 600 "$file" && echo "/last30days: WARNING — $file had permissions $perms — auto-fixed with chmod 600" || echo "/last30days: WARNING — $file has permissions $perms (should be 600). Fix: chmod 600 $file"- fi-}--trim_ws() {- local s="$1"- s="${s#"${s%%[![:space:]]*}"}"- s="${s%"${s##*[![:space:]]}"}"- printf '%s' "$s"-}--strip_outer_quotes() {- local s="$1"- if [[ ${#s} -ge 2 ]]; then- if [[ "${s:0:1}" == '"' && "${s: -1}" == '"' ]]; then- s="${s:1:${#s}-2}"- elif [[ "${s:0:1}" == "'" && "${s: -1}" == "'" ]]; then- s="${s:1:${#s}-2}"- fi- fi- printf '%s' "$s"-}--# Load env file into variables for inspection (without exporting)-load_env_vars() {- local file="$1"- if [[ -f "$file" ]]; then- while IFS='=' read -r key value; do- # Skip comments, empty lines- [[ "$key" =~ ^[[:space:]]*# ]] && continue- [[ -z "$key" ]] && continue- key="$(trim_ws "$key")"- # Only plain identifiers may reach `printf -v`. printf -v uses assignment- # semantics, so a key carrying an array subscript — e.g. `x[$(id)]` — has- # that subscript arithmetic-evaluated, which runs the command inside it.- # A project-scoped .claude/last30days.env is attacker-controlled as soon- # as an untrusted repo is opened, so an unvalidated key here is arbitrary- # code execution at session start.- [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue- value="$(strip_outer_quotes "$(trim_ws "$value")")"- # Strip inline comments (# preceded by whitespace) to prevent- # command substitution in backtick-containing comments- value="${value%%[[:space:]]#*}"- if [[ -n "$key" && -n "$value" ]]; then- # printf -v writes via assignment semantics (global from inside a- # function), works on macOS's /bin/bash 3.2 — `declare -g` is 4.2+.- printf -v "ENV_${key}" '%s' "$value"- fi- done < "$file"- fi-}--# Match lib/env.py::_truthy — process/global trust signal only.-is_truthy() {- local v- v="$(trim_ws "$1")"- case "$v" in- 1|[Tt][Rr][Uu][Ee]|[Yy][Ee][Ss]|[Oo][Nn]) return 0 ;;- *) return 1 ;;- esac-}--# Quiet mode: suppress the onboarding welcome and the upsell tips, keeping the-# one-line status. Same precedence as every other setting: the process-# environment wins when set, otherwise the global config file is consulted.-# A project-scoped file reaches this only through the existing trust gate,-# because ENV_* vars are populated by load_env_vars after that check.-is_quiet() {- if [[ "${LAST30DAYS_QUIET+x}" == "x" ]]; then- is_truthy "$LAST30DAYS_QUIET"- return $?- fi- is_truthy "${ENV_LAST30DAYS_QUIET:-}"-}--# Project config cannot self-grant trust. Process env (including empty/0 deny)-# wins when set; otherwise the global config file's trust flag is consulted.-project_config_trusted() {- if [[ "${LAST30DAYS_TRUST_PROJECT_CONFIG+x}" == "x" ]]; then- is_truthy "$LAST30DAYS_TRUST_PROJECT_CONFIG"- return $?- fi- is_truthy "${ENV_LAST30DAYS_TRUST_PROJECT_CONFIG:-}"-}--# Mirror lib/env.py::_find_project_env: walk up from $PWD for-# .claude/last30days.env, stopping at the git root, $HOME, or filesystem root.-# Prints the absolute path on stdout when found; returns 1 when none.-find_project_env() {- local dir candidate parent- dir="$PWD"- while :; do- candidate="${dir}/.claude/last30days.env"- if [[ -f "$candidate" ]]; then- printf '%s' "$candidate"- return 0- fi- # Stop at git root even if no project env was found there (matches env.py).- if [[ -e "${dir}/.git" ]]; then- return 1- fi- if [[ "$dir" == "$HOME" ]]; then- return 1- fi- parent="$(dirname "$dir")"- if [[ "$parent" == "$dir" ]]; then- return 1- fi- dir="$parent"- done-}--# Determine which config file(s) are active. Always load global first (when-# present) so a trust signal there can unlock the project file — matching-# lib/env.py, where the project file is never parsed before the trust check.-CONFIG_FILE=""-if [[ -n "$GLOBAL_ENV" && -f "$GLOBAL_ENV" ]]; then- CONFIG_FILE="$GLOBAL_ENV"- check_perms "$GLOBAL_ENV"- load_env_vars "$GLOBAL_ENV"-fi--PROJECT_ENV=""-if project_config_trusted; then- # `|| true` keeps set -e from aborting when no project env is in the walk.- PROJECT_ENV="$(find_project_env)" || true-fi-if [[ -n "$PROJECT_ENV" && -f "$PROJECT_ENV" ]]; then- CONFIG_FILE="$PROJECT_ENV"- check_perms "$PROJECT_ENV"- load_env_vars "$PROJECT_ENV"-fi--# Load Keychain item presence for status checks without reading secret values.-# Runtime credential resolution still happens in lib/env.py; this hook only-# needs to avoid stale first-run/source-count messages.-load_keychain_presence() {- case "$(uname -s 2>/dev/null)" in- Darwin*) ;;- *) return 0 ;;- esac- command -v security >/dev/null 2>&1 || return 0-- local user key env_var current- user="${USER:-}"- if [[ -z "$user" ]]; then- user="$(id -un 2>/dev/null || true)"- fi- [[ -n "$user" ]] || return 0-- for key in SETUP_COMPLETE OPENAI_API_KEY SCRAPECREATORS_API_KEY AUTH_TOKEN CT0 XAI_API_KEY X_BEARER_TOKEN BSKY_HANDLE EXA_API_KEY; do- env_var="ENV_${key}"- current="${!env_var:-}"- if [[ -z "$current" ]]; then- current="${!key:-}"- fi- [[ -n "$current" ]] && continue- if security find-generic-password -a "$user" -s "last30days-${key}" >/dev/null 2>&1; then- printf -v "ENV_${key}" '%s' "keychain"- fi- done- return 0-}--load_keychain_presence--# Check SETUP_COMPLETE (from file, env, or Keychain presence)-SETUP_COMPLETE="${ENV_SETUP_COMPLETE:-${SETUP_COMPLETE:-}}"--# Compute last-run summary line (if last-run.json exists)-if [[ "${LAST30DAYS_CONFIG_DIR+x}" == "x" ]]; then- if [[ -n "$LAST30DAYS_CONFIG_DIR" ]]; then- LAST_RUN_FILE="$LAST30DAYS_CONFIG_DIR/last-run.json"- else- LAST_RUN_FILE=""- fi-else- LAST_RUN_FILE="$HOME/.config/last30days/last-run.json"-fi-LAST_RUN_LINE=""-# python3 -c, NOT a heredoc: bash 5.3 feeds heredocs to the child through a-# pipe and can deadlock in heredoc_write inside command substitution, hanging-# this hook forever at session start (observed on Homebrew bash 5.3.15).-if [[ -n "$LAST_RUN_FILE" && -f "$LAST_RUN_FILE" ]] && command -v python3 &>/dev/null; then- LAST_RUN_LINE=$(LAST_RUN_FILE="$LAST_RUN_FILE" python3 -c '-import datetime-import json-import os--path = os.environ["LAST_RUN_FILE"]-try:- with open(path) as fh:- d = json.load(fh)- topic = (d.get("topic") or "?")[:60]- ts = d.get("timestamp", "")- dt = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00"))- delta = (datetime.datetime.now(datetime.timezone.utc) - dt).total_seconds()- if delta < 60: ago = f"{int(delta)}s ago"- elif delta < 3600: ago = f"{int(delta//60)}m ago"- elif delta < 86400: ago = f"{int(delta//3600)}h ago"- else: ago = f"{int(delta//86400)}d ago"- total = d.get("total", 0)- print(f" Last run: \"{topic}\" · {ago} · {total} results")-except Exception:- pass-' 2>/dev/null || true)-fi--# Detect capability that doesn't need a config file: yt-dlp on PATH.-# Done before the new-user early-exit so first-run users with yt-dlp-# installed see YouTube is already available. See #394.-HAS_YTDLP=""-if command -v yt-dlp &>/dev/null; then- HAS_YTDLP="yes"-fi--# If setup has never been run, show welcome message for new users-if [[ -z "$SETUP_COMPLETE" && -z "$CONFIG_FILE" && -z "${ENV_OPENAI_API_KEY:-${OPENAI_API_KEY:-}}" && -z "${ENV_SCRAPECREATORS_API_KEY:-${SCRAPECREATORS_API_KEY:-}}" && -z "${ENV_AUTH_TOKEN:-${AUTH_TOKEN:-}}" && -z "${ENV_XAI_API_KEY:-${XAI_API_KEY:-}}" ]]; then- # Nothing is configured, so every line below is onboarding copy. In quiet- # mode emit only the last-run status, when there is one, and stop.- if is_quiet; then- if [[ -n "$LAST_RUN_LINE" ]]; then- echo "$LAST_RUN_LINE"- fi- exit 0- fi- # printf, NOT cat-with-heredoc: see the bash 5.3 heredoc deadlock note above.- if [[ -n "$HAS_YTDLP" ]]; then- # YouTube is already working via the on-system yt-dlp binary — don't list- # it as something the wizard needs to unlock. See #394.- printf '%s\n' \- '/last30days: Ready to use. Run /last30days to get started — setup takes 30 seconds.' \- ' Research any topic across Reddit, HN, X, YouTube, Polymarket (last 30 days).' \- '' \- 'Reddit, Hacker News, Polymarket, and YouTube (yt-dlp detected) work out of the box.' \- 'The setup wizard can unlock X/Twitter and more.' \- ' Detected: yt-dlp is installed (YouTube transcripts ready, no setup needed).'- else- printf '%s\n' \- '/last30days: Ready to use. Run /last30days to get started — setup takes 30 seconds.' \- ' Research any topic across Reddit, HN, X, YouTube, Polymarket (last 30 days).' \- '' \- 'Reddit, Hacker News, and Polymarket work out of the box.' \- 'The setup wizard can unlock X/Twitter, YouTube, and more.'- fi- if [[ -n "$LAST_RUN_LINE" ]]; then- echo "$LAST_RUN_LINE"- fi- exit 0-fi--# Setup done but check for ScrapeCreators-HAS_SCRAPECREATORS="${ENV_SCRAPECREATORS_API_KEY:-${SCRAPECREATORS_API_KEY:-}}"-HAS_X=""-if [[ -n "${ENV_AUTH_TOKEN:-${AUTH_TOKEN:-}}" && -n "${ENV_CT0:-${CT0:-}}" ]]; then- HAS_X="yes"-fi-# X API v2 bearer (official X API backend) is a third way to have X; read the-# same way XAI_API_KEY is (file first, then process env), presence only.-if [[ -n "${ENV_X_BEARER_TOKEN:-${X_BEARER_TOKEN:-}}" ]]; then- HAS_X="yes"-fi-HAS_XAI="${ENV_XAI_API_KEY:-${XAI_API_KEY:-}}"-HAS_BSKY="${ENV_BSKY_HANDLE:-${BSKY_HANDLE:-}}"-HAS_EXA="${ENV_EXA_API_KEY:-${EXA_API_KEY:-}}"--# Count active sources-SOURCE_COUNT=2 # HN + Polymarket are always free-if [[ -n "$HAS_X" || -n "$HAS_XAI" ]]; then- SOURCE_COUNT=$((SOURCE_COUNT + 1))-fi-# Reddit public JSON always works-SOURCE_COUNT=$((SOURCE_COUNT + 1))-if [[ -n "$HAS_YTDLP" ]]; then- SOURCE_COUNT=$((SOURCE_COUNT + 1))-fi-if [[ -n "$HAS_EXA" ]]; then- SOURCE_COUNT=$((SOURCE_COUNT + 1))-fi-if [[ -n "$HAS_BSKY" ]]; then- SOURCE_COUNT=$((SOURCE_COUNT + 1))-fi-if [[ -n "$HAS_SCRAPECREATORS" ]]; then- # Start with Reddit comments + TikTok + Instagram, subtract any in EXCLUDE_SOURCES.- # Normalise EXCLUDED by removing whitespace; case-insensitive matches below- # mirror pipeline.py's .strip().lower() parsing without requiring sed/tr.- SC_ADD=3- EXCLUDED="${ENV_EXCLUDE_SOURCES:-${EXCLUDE_SOURCES:-}}"- EXCLUDED_NORM="${EXCLUDED//[[:space:]]/}"- if [[ ",$EXCLUDED_NORM," == *",[Tt][Ii][Kk][Tt][Oo][Kk],"* ]]; then- SC_ADD=$((SC_ADD - 1))- fi- if [[ ",$EXCLUDED_NORM," == *",[Ii][Nn][Ss][Tt][Aa][Gg][Rr][Aa][Mm],"* ]]; then- SC_ADD=$((SC_ADD - 1))- fi- SOURCE_COUNT=$((SOURCE_COUNT + SC_ADD))-fi--if [[ -n "$HAS_SCRAPECREATORS" ]]; then- # Fully configured — compact ready message- echo "/last30days: Ready — ${SOURCE_COUNT} sources active."- echo " Research any topic across social + market + web sources (last 30 days)."- if [[ -n "$LAST_RUN_LINE" ]]; then- echo "$LAST_RUN_LINE"- fi-else- # Setup done but missing ScrapeCreators — recommend it- echo "/last30days: Ready — ${SOURCE_COUNT} sources active."- echo " Research any topic across social + market + web sources (last 30 days)."- if [[ -n "$LAST_RUN_LINE" ]]; then- echo "$LAST_RUN_LINE"- fi- # Status already printed above; the rest of this branch is an upsell.- if is_quiet; then- exit 0- fi- echo " Tip: Add ScrapeCreators for Reddit comments + TikTok + Instagram."- echo " 100 free credits, no credit card — scrapecreators.com"- echo " last30days has no affiliation with any API provider."-fi--# The branches above end with `[[ -n "$LAST_RUN_LINE" ]] && echo ...`. When-# LAST_RUN_LINE is empty, that test returns 1 and is the script's last command,-# leaking exit=1 to callers (e.g. SessionStart hook drivers) despite no error.-exit 0diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex f4db7b34..36209f6c 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -303,10 +303,10 @@ After resolving host web search, run the first-run gate below before anything elgrep -q "SETUP_COMPLETE=true" ~/.config/last30days/.env 2>/dev/null && echo "1" || echo "FIRST_RUN_DETECTED"```-This emits exactly one token: `1` or `FIRST_RUN_DETECTED`, never both.+This emits exactly one token: `1` or `FIRST_RUN_DETECTED`, never both. The grep only sees `SETUP_COMPLETE` in the global `.env`; it does not see process env, project config, Keychain, pass, or host-provided auth.- Output is `1` → setup is complete. Continue to the branching rule below.-- Output is `FIRST_RUN_DETECTED` → this is a first run. Jump immediately to `## Step 0: First-Run Setup Wizard` and complete it **before doing any topic research**. Do NOT proceed to Step 0.5, do NOT load WebSearch supplements, do NOT synthesize anything. The wizard installs yt-dlp (YouTube), the Digg CLI (via `npx`), and extracts browser cookies for X/Twitter and other sources. Skipping it produces a degraded WebSearch-only result that misrepresents the skill's capability to the user.+- Output is `FIRST_RUN_DETECTED` → global `SETUP_COMPLETE` is unset. Jump immediately to `## Step 0: First-Run Setup Wizard`. That section decides first-run from every credential source without dumping files. A missing `.env` alone is not a first run. If Step 0 skips, continue to the branching rule. If Step 0 runs, complete it **before doing any topic research**. Do NOT proceed to Step 0.5, do NOT load WebSearch supplements, do NOT synthesize anything. The wizard installs yt-dlp (YouTube), the Digg CLI (via `npx`), and extracts browser cookies for X/Twitter and other sources. Skipping a true first run produces a degraded WebSearch-only result that misrepresents the skill's capability to the user.**Named failure mode (2026-06-22, first-run setup skip - Fredy Montero run):** Model read "proceed to Step 0.5" in the branching rule and jumped there directly, bypassing `## Step 0: First-Run Setup Wizard` at line ~339. Result: no browser cookie extraction, no yt-dlp, no Digg CLI install, WebSearch-only synthesis with no X/YouTube/TikTok data. Root cause: the branching rule named Step 0.5 as the next step without mentioning the wizard. Fix: this gate and the updated branching rule below.@@ -527,7 +527,7 @@ Your host search is better than the engine's keyless web fallback, so this tells## Configuration-Set `LAST30DAYS_MEMORY_DIR` before invoking the skill to choose where raw research files are saved. If it is not set, the skill defaults to `~/Documents/Last30Days`. The SessionStart hook (`hooks/scripts/check-config.sh`) creates this directory automatically on every session start if it doesn't already exist - but the hook ships only with the Claude Code plugin install; on `npx skills` and other hookless installs there is no hook, and the engine creates the directory itself on first save.+Set `LAST30DAYS_MEMORY_DIR` before invoking the skill to choose where raw research files are saved. If it is not set, the skill defaults to `~/Documents/Last30Days`. The engine creates this directory on first save.The engine reads `LAST30DAYS_MEMORY_DIR` from either the process env or `~/.config/last30days/.env`, so direct CLI invocations (`python3 scripts/last30days.py ...`) without `--save-dir` will still save when the env var is set. Mirrors the `LAST30DAYS_STORE` env-or-flag convention. Explicit `--save-dir` always wins.@@ -546,6 +546,8 @@ When both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine run**First-run detection (silent, no commands, no output to user):**- If `SETUP_COMPLETE=true` is available from process env, project config (`.claude/last30days.env`), global config (`~/.config/last30days/.env`), or the setup check reports configured credentials, skip Step 0 entirely and go to Step 1 (CRITICAL: Parse User Intent below). Do NOT announce that setup is complete. The user does not need a status message on every run.- Do NOT treat the absence of `~/.config/last30days/.env` alone as a first run. Credentials may live in process env, project config, macOS Keychain (`last30days-<KEY>`), pass(1), or host-provided auth.+- Detect first-run from key presence and setup status, not by dumping files. Do not print `.env` contents or credential values.+- `--preflight` is an opt-in inspector (what this run would read or write, ignored project config). Do not run it as a required first-run step.- If no setup marker or credential source is present, this is a first run.**Named onboarding contracts:**@@ -656,16 +658,14 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI**1. Welcome.** Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py --welcome` and show its stdout to the user VERBATIM (do not summarize or reformat). The welcome is engine-owned so it renders the same everywhere.-**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 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.**+**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 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), 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), plus the free keyless arXiv and Techmeme CLIs.- **Extras hosts (Linux / Mac mini / Darwin agentcookie sink) — a MacBook SKIPS this, and so does a `LAST30DAYS_HOST=grok-bot` host.** On these hosts the Chrome cookie store can't be decrypted, so the extract above finds nothing and X stays empty unless you capture a LIVE login over CDP. Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/box_chrome_login.py` (prints the host-correct command; `--exec` launches it; a MacBook prints "no launch needed" and spawns nothing). When `box-chrome` is on PATH it launches a throwaway profile on the last30days extras port **18800** (`SAND_CHROME_REMOTE_DEBUG_PORT=18800`, not box-chrome's default): `CHROME_USER_DATA_DIR=/tmp/last30days-x-chrome SAND_CHROME_REMOTE_DEBUG_PORT=18800 box-chrome --new-window https://x.com/login`. Wait for the x.com login page, then HAND THE DESKTOP to the human to type — do NOT drive the form. After they sign in, append `BROWSER_CDP_URL=http://127.0.0.1:18800` to `.env` (never `AUTH_TOKEN`/`CT0`; keep `AGENTCOOKIE=off` during the harvest) and re-run `setup --allow-browser-cookies`. Full steps and the block/rate-limit stop rule: **X on Linux / Mac mini** below. This extras-host login only runs on the consented **yes** path; a waiting topic never skips it when the user said yes to X.- - On **no** → run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme, still writes `SETUP_COMPLETE`. If the invocation already includes a topic, immediately research it with `--no-browser-cookies`, then resume the deferred onboarding in the same run after the findings: the ScrapeCreators offer (step 5) and source tier (step 5b) if a key is saved. Do not re-ask cookie consent as part of the resume.+ - On **no** → run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme, still writes `SETUP_COMPLETE`. If the invocation already includes a topic, immediately research it with `--no-browser-cookies`, then resume the deferred onboarding in the same run after the findings: the ScrapeCreators offer (step 4) and source tier (step 4b) if a key is saved. Do not re-ask cookie consent as part of the resume.-**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 only when no research topic is waiting. If a topic is already waiting or the user skips, continue immediately with available sources.+**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 only when no research topic is waiting. If a topic is already waiting or the user skips, continue immediately with available sources.-**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 optional backups: Reddit search backfill when the free path returns no items (empty-only by default; thin-run / SC-primary are opt-in env knobs — see Reddit backend pin below), and a YouTube transcript fallback when yt-dlp is rate-limited or bot-gated. GitHub signup grants the full 10,000 free calls (more than the web form), and 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.**+**4. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that add TikTok and Instagram, plus optional backups: Reddit search backfill when the free path returns no items (empty-only by default; thin-run / SC-primary are opt-in env knobs — see Reddit backend pin below), and a YouTube transcript fallback when yt-dlp is rate-limited or bot-gated. GitHub signup grants the full 10,000 free calls (more than the web form), and 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** → two commands. FIRST run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-start` in the FOREGROUND - it returns in ~1-2s with a `Your GitHub code: XXXX-XXXX` line plus a JSON blob, copies the code to the clipboard, and opens the browser. Read the `user_code` from that output and immediately tell the user: the code, that it's on their clipboard so they can just paste it (Cmd+V) on the GitHub page - do not make them hunt for it. (If `status == "already_registered"`, stop here - their existing key is active. If the output said the clipboard copy failed, tell them to type the code.) THEN run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-poll` (background with a 5-min timeout, or foreground) and parse the **LAST** JSON line of its 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 **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 **`status == "error"` with `message == "Authorized but failed to fetch API key"`** (exact match; often `"reason": "no_api_key"`) → GitHub authorized fine, so do NOT say auth failed. This usually means the GitHub account is already linked to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it, or Skip." Accept a pasted key or offer web/skip.@@ -673,11 +673,11 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI- On **timeout, or any other error** → 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).** Comments are the default, never opt-in. Your key runs TikTok + Instagram posts AND top comments, plus YouTube comments. Reddit stays on the free keyless path (empty-only ScrapeCreators search backup; comments via shreddit). Ask whether they want the widest net, e.g.: `Recommended is TikTok + Instagram + all comments (posts and top comments for TikTok/Instagram plus YouTube comments). Or Everything - also Threads + Pinterest (more credits). (recommended / everything)` **Wait for the answer.**+**4b. Source tier (only if a key was saved).** Comments are the default, never opt-in. Your key runs TikTok + Instagram posts AND top comments, plus YouTube comments. Reddit stays on the free keyless path (empty-only ScrapeCreators search backup; comments via shreddit). Ask whether they want the widest net, e.g.: `Recommended is TikTok + Instagram + all comments (posts and top comments for TikTok/Instagram plus YouTube comments). Or Everything - also Threads + Pinterest (more credits). (recommended / everything)` **Wait for the answer.**- On **recommended** → append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments` to `~/.config/last30days/.env` (include `tiktok,instagram` so they are not treated as excluded). Confirm posts + top comments for TikTok/Instagram/YouTube are on.- On **everything** → append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments,threads,pinterest`. Confirm Threads and Pinterest are 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; only report a project file as active when diagnose reports it as the config source.+**5. Complete.** Once `SETUP_COMPLETE=true` is written, proceed to research. Setup stdout is what this run installed, not the runtime source list; the engine diagnostic at research confirmation is authoritative. 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; only report a project file as active when the engine reports it as the config source.---@@ -687,13 +687,11 @@ For a Grok Bot host. The Grok Bot host rule in HOW TO INVOKE applies throughout:**1. Host key + welcome.** Persist the host signal so later runs and `doctor` see it: if `~/.config/last30days/.env` is missing, `mkdir -p ~/.config/last30days && touch ~/.config/last30days/.env`; then append one line `LAST30DAYS_HOST=grok-bot` (append-only with `>>`; never `>`). Then run `"${LAST30DAYS_PYTHON:-python3}" "${SKILL_DIR}/scripts/last30days.py" --welcome` and show its stdout VERBATIM.-**2. Permission preflight.** Run `"${LAST30DAYS_PYTHON:-python3}" "${SKILL_DIR}/scripts/last30days.py" --preflight` and summarize the human-readable result (config source, planned writes, optional commands). It reads nothing from a browser and runs no research.--**3. X connector (primary - check this BEFORE offering any key).** Look for an X post-search tool from the X connector in this session: the "X for Grok Bot" plugin (search posts, read timelines, check mentions), for example `search_posts_all`. Any of its search tools counts; use the one that searches posts by query.- - **Present** → tell the user: `X search runs through your X connector on the credits included with Grok Bot, with full 30-day coverage - nothing to configure.` Export `LAST30DAYS_X_HOST_LANE=1` next to `LAST30DAYS_HOST=grok-bot` in every engine shell for this session, and on every research run follow the X connector recipe in Research Execution: one `topic` call sized 10 / 30 / 60 by depth (`--quick` / default / `--deep`) with `-is:retweet` and the window; per `--x-handle`, a `from` call of 8 and a `mention` call of 5; per `--x-related` handle, a `related` call of 3; written to a `last30days-x-posts/1` envelope (`generated_at`, `topic`, `window`, `status`, `calls` tagged `topic` / `from` / `mention` / `related`, each post exactly `id`, `author_handle`, `created_at`, `text`, `likes`, `reposts`, `replies`, `quotes` and nothing else); if the tool rejects the window or count parameters, omit them and write `status: partial` with `error: window-unsupported`; pass the file as `--x-posts <file>`. Skip step 4.- - **Absent** → continue to step 4.+**2. X connector (primary - check this BEFORE offering any key).** Look for an X post-search tool from the X connector in this session: the "X for Grok Bot" plugin (search posts, read timelines, check mentions), for example `search_posts_all`. Any of its search tools counts; use the one that searches posts by query.+ - **Present** → tell the user: `X search runs through your X connector on the credits included with Grok Bot, with full 30-day coverage - nothing to configure.` Export `LAST30DAYS_X_HOST_LANE=1` next to `LAST30DAYS_HOST=grok-bot` in every engine shell for this session, and on every research run follow the X connector recipe in Research Execution: one `topic` call sized 10 / 30 / 60 by depth (`--quick` / default / `--deep`) with `-is:retweet` and the window; per `--x-handle`, a `from` call of 8 and a `mention` call of 5; per `--x-related` handle, a `related` call of 3; written to a `last30days-x-posts/1` envelope (`generated_at`, `topic`, `window`, `status`, `calls` tagged `topic` / `from` / `mention` / `related`, each post exactly `id`, `author_handle`, `created_at`, `text`, `likes`, `reposts`, `replies`, `quotes` and nothing else); if the tool rejects the window or count parameters, omit them and write `status: partial` with `error: window-unsupported`; pass the file as `--x-posts <file>`. Skip step 3.+ - **Absent** → continue to step 3.-**4. Backup key (only when the connector is absent).** Say, then WAIT: `This session has no X connector, so X needs a key. Best fix: add the "X for Grok Bot" plugin and connect X inside Grok Bot (it provisions an X developer account for you, with credits included). Otherwise paste an X_BEARER_TOKEN from the X developer console - recent posts, about the last week, unless your X developer project has full-archive access - or an XAI_API_KEY from console.x.ai. Or skip X for now. (bearer / xai / skip)`+**3. Backup key (only when the connector is absent).** Say, then WAIT: `This session has no X connector, so X needs a key. Best fix: add the "X for Grok Bot" plugin and connect X inside Grok Bot (it provisions an X developer account for you, with credits included). Otherwise paste an X_BEARER_TOKEN from the X developer console - recent posts, about the last week, unless your X developer project has full-archive access - or an XAI_API_KEY from console.x.ai. Or skip X for now. (bearer / xai / skip)`- On a pasted key → persist it ONLY through the engine's key-write path, feeding stdin from a single-quoted heredoc. Never an ad-hoc shell write of the value, never interpolate it into a command line:```bash@@ -703,13 +701,13 @@ For a Grok Bot host. The Grok Bot host rule in HOW TO INVOKE applies throughout:```Use `setup --store-key XAI_API_KEY` for an xAI key. The engine prints `X_BEARER_TOKEN=****` (or `XAI_API_KEY=****`) plus a JSON `persisted` line; never echo the value back, and confirm only in the masked `NAME=****` form. Running it again with a new value replaces the stored one (that is how a rejected key is rotated). A `"persisted": false` means the write failed: say so and do not claim X is active.- - On **skip** → append `X_DECLINED=grok-bot` to `~/.config/last30days/.env` (append-only) so later runs stay quiet about X: no unlock pitch, no second key question. If the invocation already includes a topic, research it right after step 5 and resume steps 6-7 after the findings.+ - On **skip** → append `X_DECLINED=grok-bot` to `~/.config/last30days/.env` (append-only) so later runs stay quiet about X: no unlock pitch, no second key question. If the invocation already includes a topic, research it right after step 4 and resume steps 5-6 after the findings.-**5. Setup (free CLIs, no browser reads).** Run `"${LAST30DAYS_PYTHON:-python3}" "${SKILL_DIR}/scripts/last30days.py" setup` (the plain form; on this host it reads nothing from a browser). It best-effort installs yt-dlp (YouTube), the Digg CLI, arXiv, and Techmeme and writes `SETUP_COMPLETE=true`. Show what was installed, including whether Digg landed on PATH.+**4. Setup (free CLIs, no browser reads).** Run `"${LAST30DAYS_PYTHON:-python3}" "${SKILL_DIR}/scripts/last30days.py" setup` (the plain form; on this host it reads nothing from a browser). It best-effort installs yt-dlp (YouTube), the Digg CLI, arXiv, and Techmeme and writes `SETUP_COMPLETE=true`. Show what was installed, including whether Digg landed on PATH.-**6. ScrapeCreators offer and source tier.** Run steps 5 and 5b of the Non-Modal Prose Flow exactly as written there (GitHub device-code signup with `setup --github-start` then `setup --github-poll`; the engine persists the key and masks it).+**5. ScrapeCreators offer and source tier.** Run steps 4 and 4b of the Non-Modal Prose Flow exactly as written there (GitHub device-code signup with `setup --github-start` then `setup --github-poll`; the engine persists the key and masks it).-**7. Complete.** Confirm `SETUP_COMPLETE=true` is in `~/.config/last30days/.env` (append it if `setup` did not run), briefly confirm which sources are active (re-run `--preflight`, or safe `--diagnose`, with the host signal and, when the connector is present, `LAST30DAYS_X_HOST_LANE=1` exported; `--diagnose` then lists `x` as served by the connector), and proceed to research.+**6. Complete.** Confirm `SETUP_COMPLETE=true` is in `~/.config/last30days/.env` (append it if `setup` did not run) and proceed to research (with the host signal and, when the connector is present, `LAST30DAYS_X_HOST_LANE=1` exported). Setup stdout is what this run installed, not the runtime source list; the engine diagnostic at research confirmation is authoritative.---@@ -2408,7 +2406,7 @@ Want another prompt? Just tell me what you're creating next.- Saves research briefings as .md files to `LAST30DAYS_MEMORY_DIR` (defaults to `~/Documents/Last30Days`)- Generates a local `index.html`, Atom `feed.xml`, and rendered brief pages from saved research when the user asks for the library feed- Publishes the library, feed, and referenced briefs to `ht-ml.app` only after explicit opt-in; hosted pages are public by default unless the user chooses password protection-- Provides `--preflight` for a safe human-readable permission summary before research; it does not read browser-cookie values, write files, or run live research+- Provides `--preflight` as an opt-in permission inspector (config source, planned writes, available sources); it does not read browser-cookie values, write files, or run live research. Do not run it as a required first-run step.**What this skill does NOT do:**- Does not post, like, or modify content on any platformdiff --git a/tests/test_check_config_env_safety.py b/tests/test_check_config_env_safety.pydeleted file mode 100644index 79853818..00000000--- a/tests/test_check_config_env_safety.py+++ /dev/null@@ -1,406 +0,0 @@-"""Security tests for hooks/scripts/check-config.sh env parsing.--Covers the SessionStart hook's .env loader:-- - printf -v key injection (array-subscript command substitution)- - LAST30DAYS_TRUST_PROJECT_CONFIG gate matching lib/env.py- - Legitimate identifier keys still parse--The PoC key ``x[$(touch RCE-PROOF.txt)]=1`` executes under bash 4+/5 via-printf -v assignment semantics; bash 3.2 rejects it as an invalid identifier-and (with ``set -e``) aborts the hook. Either way, after the fix the hook must-exit 0 and must never create the proof file.-"""--from __future__ import annotations--import os-import re-import shutil-import subprocess-from pathlib import Path--import pytest--HOOK = Path(__file__).resolve().parents[1] / "hooks" / "scripts" / "check-config.sh"-POC_LINE = "x[$(touch RCE-PROOF.txt)]=1\n"---def _bash_binaries() -> list[str]:- """Prefer modern bash (4+) when present so the RCE path is actually exercised."""- seen: list[str] = []- for candidate in (- "/opt/homebrew/bin/bash",- "/usr/local/bin/bash",- shutil.which("bash"),- ):- if not candidate:- continue- path = str(Path(candidate).resolve())- if path not in seen and Path(path).is_file():- seen.append(path)- return seen---def _bash_major(bash_path: str) -> int:- result = subprocess.run(- [bash_path, "-c", 'echo "${BASH_VERSINFO[0]}"'],- capture_output=True,- text=True,- timeout=10,- check=False,- )- try:- return int((result.stdout or "").strip() or "0")- except ValueError:- return 0---def _mode_bits_assertable() -> bool:- """Match check_perms: Windows/MSYS synthesized modes are not meaningful."""- if os.name == "nt":- return False- uname = ""- try:- uname = os.uname().sysname # type: ignore[attr-defined]- except AttributeError:- return True- return not uname.startswith(("MINGW", "MSYS", "CYGWIN"))---def _assert_mode(path: Path, expected: str) -> None:- if _mode_bits_assertable():- assert oct(path.stat().st_mode)[-3:] == expected---def _isolated_path(tmp_path: Path) -> str:- """PATH with a stub ``security`` so macOS Keychain presence cannot leak into assertions."""- bin_dir = tmp_path / "hook-bin"- bin_dir.mkdir(exist_ok=True)- security = bin_dir / "security"- if not security.exists():- security.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")- security.chmod(0o755)- return f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"---def _run_hook(- bash_path: str,- cwd: Path,- tmp_path: Path,- env_overrides: dict[str, str] | None = None,-) -> subprocess.CompletedProcess[str]:- env = os.environ.copy()- for k in (- "LAST30DAYS_MEMORY_DIR",- "SETUP_COMPLETE",- "LAST30DAYS_CONFIG_DIR",- "LAST30DAYS_TRUST_PROJECT_CONFIG",- "OPENAI_API_KEY",- "SCRAPECREATORS_API_KEY",- "AUTH_TOKEN",- "CT0",- "XAI_API_KEY",- "BSKY_HANDLE",- "EXA_API_KEY",- ):- env.pop(k, None)- env["PATH"] = _isolated_path(tmp_path)- if env_overrides:- env.update(env_overrides)- return subprocess.run(- [bash_path, str(HOOK)],- capture_output=True,- text=True,- env=env,- cwd=str(cwd),- timeout=30,- check=False,- )--[email protected](params=_bash_binaries())-def bash_path(request: pytest.FixtureRequest) -> str:- return request.param--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_malicious_project_env_key_does_not_execute(bash_path: str, tmp_path: Path):- """Reporter PoC: crafted key must not run, even under bash 4+/5."""- project = tmp_path / "repo"- env_file = project / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text(f"SETUP_COMPLETE=1\n{POC_LINE}", encoding="utf-8")- proof = project / "RCE-PROOF.txt"-- result = _run_hook(- bash_path,- project,- tmp_path,- {- "LAST30DAYS_CONFIG_DIR": str(tmp_path / "empty-config"),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert not proof.exists(), f"RCE proof file was created under {bash_path}"- assert result.returncode == 0, (- f"hook aborted under {bash_path}: stderr={result.stderr!r} stdout={result.stdout!r}"- )--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_malicious_key_blocked_even_when_project_trusted(bash_path: str, tmp_path: Path):- """Identifier gate must hold even after an explicit trust opt-in."""- project = tmp_path / "repo"- env_file = project / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text(f"SETUP_COMPLETE=1\n{POC_LINE}", encoding="utf-8")- proof = project / "RCE-PROOF.txt"-- result = _run_hook(- bash_path,- project,- tmp_path,- {- "LAST30DAYS_TRUST_PROJECT_CONFIG": "1",- "LAST30DAYS_CONFIG_DIR": str(tmp_path / "empty-config"),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert not proof.exists(), f"RCE proof file was created under {bash_path} (trusted path)"- assert result.returncode == 0, (- f"hook aborted under {bash_path}: stderr={result.stderr!r} stdout={result.stdout!r}"- )- assert "Ready" in result.stdout--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_untrusted_project_env_is_ignored(bash_path: str, tmp_path: Path):- """Without LAST30DAYS_TRUST_PROJECT_CONFIG, project file is not read or chmod'd."""- project = tmp_path / "repo"- env_file = project / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text(- "SETUP_COMPLETE=true\nSCRAPECREATORS_API_KEY=scrape-test-key-untrusted\n",- encoding="utf-8",- )- env_file.chmod(0o644)-- result = _run_hook(- bash_path,- project,- tmp_path,- {- "LAST30DAYS_CONFIG_DIR": str(tmp_path / "empty-config"),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert result.returncode == 0, result.stderr- # check_perms only runs on the chosen config file; untrusted project stays 644.- _assert_mode(env_file, "644")- # Project ScrapeCreators key must not suppress the tip when the configured- # banner path runs (isolated PATH stubs Keychain).- if "sources active" in result.stdout:- assert "Tip: Add ScrapeCreators" in result.stdout- else:- assert "Ready to use" in result.stdout--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_trusted_project_env_loads_normal_keys(bash_path: str, tmp_path: Path):- project = tmp_path / "repo"- env_file = project / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text(- "SETUP_COMPLETE=true\n"- "SCRAPECREATORS_API_KEY=scrape-test-key\n",- encoding="utf-8",- )- env_file.chmod(0o644)-- result = _run_hook(- bash_path,- project,- tmp_path,- {- "LAST30DAYS_TRUST_PROJECT_CONFIG": "1",- "LAST30DAYS_CONFIG_DIR": str(tmp_path / "empty-config"),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert result.returncode == 0, result.stderr- assert re.search(r"Ready — \d+ sources active", result.stdout)- assert "Tip: Add ScrapeCreators" not in result.stdout- _assert_mode(env_file, "600")--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_global_trust_signal_unlocks_project_env(bash_path: str, tmp_path: Path):- """Trust from ~/.config (via LAST30DAYS_CONFIG_DIR) unlocks project overlay."""- config_dir = tmp_path / "config"- config_dir.mkdir()- (config_dir / ".env").write_text(- "LAST30DAYS_TRUST_PROJECT_CONFIG=1\nSETUP_COMPLETE=true\n",- encoding="utf-8",- )-- project = tmp_path / "repo"- env_file = project / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text("SCRAPECREATORS_API_KEY=from-project\n", encoding="utf-8")- env_file.chmod(0o644)-- result = _run_hook(- bash_path,- project,- tmp_path,- {- "LAST30DAYS_CONFIG_DIR": str(config_dir),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert result.returncode == 0, result.stderr- assert re.search(r"Ready — \d+ sources active", result.stdout)- assert "Tip: Add ScrapeCreators" not in result.stdout- _assert_mode(env_file, "600")--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_process_deny_overrides_global_trust(bash_path: str, tmp_path: Path):- config_dir = tmp_path / "config"- config_dir.mkdir()- (config_dir / ".env").write_text(- "LAST30DAYS_TRUST_PROJECT_CONFIG=1\nSETUP_COMPLETE=true\n",- encoding="utf-8",- )-- project = tmp_path / "repo"- env_file = project / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text("SCRAPECREATORS_API_KEY=from-project\n", encoding="utf-8")- env_file.chmod(0o644)-- result = _run_hook(- bash_path,- project,- tmp_path,- {- "LAST30DAYS_TRUST_PROJECT_CONFIG": "0",- "LAST30DAYS_CONFIG_DIR": str(config_dir),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert result.returncode == 0, result.stderr- assert re.search(r"Ready — \d+ sources active", result.stdout)- assert "Tip: Add ScrapeCreators" in result.stdout- _assert_mode(env_file, "644")--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_trusted_project_env_discovered_from_nested_cwd(bash_path: str, tmp_path: Path):- """Mirror lib/env.py: walk up from a subdirectory to the repo-root project env."""- repo = tmp_path / "repo"- nested = repo / "apps" / "web"- nested.mkdir(parents=True)- (repo / ".git").mkdir()- env_file = repo / ".claude" / "last30days.env"- env_file.parent.mkdir(parents=True)- env_file.write_text(- "SETUP_COMPLETE=true\nSCRAPECREATORS_API_KEY=from-repo-root\n",- encoding="utf-8",- )- env_file.chmod(0o644)-- result = _run_hook(- bash_path,- nested,- tmp_path,- {- "LAST30DAYS_TRUST_PROJECT_CONFIG": "1",- "LAST30DAYS_CONFIG_DIR": str(tmp_path / "empty-config"),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert result.returncode == 0, result.stderr- assert re.search(r"Ready — \d+ sources active", result.stdout)- assert "Tip: Add ScrapeCreators" not in result.stdout- _assert_mode(env_file, "600")--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_project_env_walk_stops_at_git_root(bash_path: str, tmp_path: Path):- """An env above the git root must not be discovered (matches lib/env.py)."""- outside = tmp_path / ".claude" / "last30days.env"- outside.parent.mkdir(parents=True)- outside.write_text(- "SETUP_COMPLETE=true\nSCRAPECREATORS_API_KEY=outside-repo\n",- encoding="utf-8",- )- outside.chmod(0o644)-- repo = tmp_path / "repo"- nested = repo / "nested"- nested.mkdir(parents=True)- (repo / ".git").mkdir()-- result = _run_hook(- bash_path,- nested,- tmp_path,- {- "LAST30DAYS_TRUST_PROJECT_CONFIG": "1",- "LAST30DAYS_CONFIG_DIR": str(tmp_path / "empty-config"),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert result.returncode == 0, result.stderr- _assert_mode(outside, "644")- # Outside key must not suppress the ScrapeCreators tip / must not count as configured.- if "sources active" in result.stdout:- assert "Tip: Add ScrapeCreators" in result.stdout- else:- assert "Ready to use" in result.stdout--[email protected](not _bash_binaries(), reason="bash not on PATH")-def test_malicious_key_in_global_env_also_blocked(bash_path: str, tmp_path: Path):- """Identifier gate applies to the global file too (defense in depth)."""- config_dir = tmp_path / "config"- config_dir.mkdir()- (config_dir / ".env").write_text(f"SETUP_COMPLETE=1\n{POC_LINE}", encoding="utf-8")- work = tmp_path / "workdir"- work.mkdir()- proof = work / "RCE-PROOF.txt"-- result = _run_hook(- bash_path,- work,- tmp_path,- {- "LAST30DAYS_CONFIG_DIR": str(config_dir),- "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"),- },- )-- assert not proof.exists(), f"RCE proof created from global env under {bash_path}"- assert result.returncode == 0, result.stderr- assert "Ready" in result.stdout--- not any(_bash_major(b) >= 4 for b in _bash_binaries()),- reason="needs bash 4+ to exercise printf -v RCE",-)-def test_rce_path_exercised_on_modern_bash(tmp_path: Path):- """Sanity: at least one bash>=4 is under test so the PoC path is real, not vacuous."""- modern = [b for b in _bash_binaries() if _bash_major(b) >= 4]- assert modern, "expected a bash 4+ binary from _bash_binaries()"- test_malicious_key_blocked_even_when_project_trusted(modern[0], tmp_path)diff --git a/tests/test_check_config_memory_dir.py b/tests/test_check_config_memory_dir.pydeleted file mode 100644index 8d02b131..00000000--- a/tests/test_check_config_memory_dir.py+++ /dev/null@@ -1,101 +0,0 @@-"""Tests for hooks/scripts/check-config.sh auto-creating LAST30DAYS_MEMORY_DIR.--Covers issue #395 — fresh installs failed silently on first --emit=html run-because nothing created the default memory dir. The SessionStart hook should-mkdir -p the configured memory dir on every run.--The default path is the same one used throughout the engine:- LAST30DAYS_MEMORY_DIR="${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}"--Cases:- - LAST30DAYS_MEMORY_DIR points to a non-existent path -> dir is created- - LAST30DAYS_MEMORY_DIR points to an existing path -> no error, exit 0- - LAST30DAYS_MEMORY_DIR unset -> default dir is created- - LAST30DAYS_MEMORY_DIR points to an unwritable path -> script still exits 0-"""--from __future__ import annotations--import os-import shutil-import subprocess-import sys-from pathlib import Path--import pytest--HOOK = Path(__file__).resolve().parents[1] / "hooks" / "scripts" / "check-config.sh"---def _run_hook(env_overrides: dict[str, str], cwd: Path | None = None) -> subprocess.CompletedProcess:- env = os.environ.copy()- # Clear any pre-existing keys so the test is deterministic.- for k in ("LAST30DAYS_MEMORY_DIR", "SETUP_COMPLETE", "LAST30DAYS_CONFIG_DIR"):- env.pop(k, None)- env.update(env_overrides)- return subprocess.run(- ["bash", str(HOOK)],- capture_output=True,- text=True,- env=env,- cwd=str(cwd) if cwd else None,- timeout=30,- )--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_creates_dir_when_memory_dir_missing(tmp_path: Path):- target = tmp_path / "Last30Days"- assert not target.exists()-- result = _run_hook({"LAST30DAYS_MEMORY_DIR": str(target)})-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- assert target.is_dir(), "LAST30DAYS_MEMORY_DIR was not created"--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_no_error_when_memory_dir_already_exists(tmp_path: Path):- target = tmp_path / "Last30Days"- target.mkdir()- sentinel = target / "sentinel.txt"- sentinel.write_text("preserve me")-- result = _run_hook({"LAST30DAYS_MEMORY_DIR": str(target)})-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- assert sentinel.read_text() == "preserve me", "existing dir contents were disturbed"--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_default_memory_dir_created_when_unset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- # Override $HOME so the default fallback path lands inside tmp_path.- fake_home = tmp_path / "home"- fake_home.mkdir()- monkeypatch.setenv("HOME", str(fake_home))- expected = fake_home / "Documents" / "Last30Days"- assert not expected.exists()-- # Use a clean env without LAST30DAYS_MEMORY_DIR (also drop SETUP_COMPLETE so- # the welcome path runs, but it doesn't matter — mkdir runs first).- result = _run_hook({})-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- assert expected.is_dir(), f"default dir {expected} was not created"--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_tolerates_unwritable_memory_dir(tmp_path: Path):- """Hook should swallow mkdir errors and still exit 0 — never crash Claude Code startup."""- # /proc/1 is owned by root; under sandboxed runners this will fail with EACCES.- bad_path = "/proc/should/not/be/writable/last30days-test-395"- if os.path.exists(bad_path):- pytest.skip("unwritable test path already exists; skipping")-- result = _run_hook({"LAST30DAYS_MEMORY_DIR": bad_path})-- # Either mkdir silently failed (2>/dev/null) or it succeeded under a permissive- # test runner. Both are acceptable. The contract is: exit 0, no crash.- assert result.returncode == 0, (- f"hook should not crash on mkdir failure: rc={result.returncode} stderr={result.stderr!r}"- )diff --git a/tests/test_check_config_quiet.py b/tests/test_check_config_quiet.pydeleted file mode 100644index 17c721af..00000000--- a/tests/test_check_config_quiet.py+++ /dev/null@@ -1,164 +0,0 @@-"""Tests for LAST30DAYS_QUIET in hooks/scripts/check-config.sh.--The SessionStart status hook prints an onboarding welcome when nothing is-configured, and a ScrapeCreators tip when setup is done without that key.-Neither can be turned off, so a user who has deliberately settled on the-free sources sees setup advice at every session start forever.--LAST30DAYS_QUIET suppresses the onboarding and upsell lines while keeping-the one-line status. Every case below is asserted in both directions: the-quiet run drops the copy, and the otherwise-identical non-quiet run still-emits it, so a test cannot pass because the hook printed nothing at all.--Cases:- - unconfigured + quiet -> silent; without quiet -> welcome- - setup done, no ScrapeCreators -> status kept, tip dropped- - quiet read from the config file, not only the process environment- - falsy values do not enable quiet- - last-run status survives quiet on the unconfigured path-"""--from __future__ import annotations--import json-import os-import shutil-import subprocess-from pathlib import Path--import pytest--HOOK = Path(__file__).resolve().parents[1] / "hooks" / "scripts" / "check-config.sh"--_CLEARED = (- "LAST30DAYS_MEMORY_DIR",- "LAST30DAYS_QUIET",- "SETUP_COMPLETE",- "LAST30DAYS_CONFIG_DIR",- "OPENAI_API_KEY",- "SCRAPECREATORS_API_KEY",- "AUTH_TOKEN",- "XAI_API_KEY",- "CT0",- "BSKY_HANDLE",- "BSKY_APP_PASSWORD",- "EXA_API_KEY",-)--WELCOME = "Ready to use. Run /last30days"-TIP = "Tip: Add ScrapeCreators"-STATUS = "sources active"---def _run_hook(env_overrides: dict[str, str]) -> subprocess.CompletedProcess:- env = os.environ.copy()- for key in _CLEARED:- env.pop(key, None)- env.update(env_overrides)- bash_path = shutil.which("bash")- if bash_path is None:- pytest.skip("bash not on PATH")- return subprocess.run(- [bash_path, str(HOOK)],- capture_output=True,- text=True,- env=env,- timeout=30,- )---def _cfg_dir(tmp_path: Path, name: str = "cfg", env_body: str | None = None) -> str:- """Config dir holding a well-formed last-run.json, optionally an .env.-- The hook reads last-run.json through a python3 subshell; supplying a valid- one keeps these tests independent of the empty-last-run exit bug (#440).- """- cfg = tmp_path / name- cfg.mkdir()- (cfg / "last-run.json").write_text(- json.dumps({"topic": "quiet mode", "timestamp": "2026-06-01T00:00:00Z", "total": 0})- )- if env_body is not None:- env_file = cfg / ".env"- env_file.write_text(env_body)- env_file.chmod(0o600)- return str(cfg)--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_quiet_suppresses_new_user_welcome(tmp_path: Path):- """Unconfigured + quiet is silent; the same run without quiet is not."""- quiet = _run_hook({"LAST30DAYS_CONFIG_DIR": _cfg_dir(tmp_path, "a"), "LAST30DAYS_QUIET": "1"})- loud = _run_hook({"LAST30DAYS_CONFIG_DIR": _cfg_dir(tmp_path, "b")})-- assert quiet.returncode == 0, f"hook failed: stderr={quiet.stderr!r}"- assert loud.returncode == 0, f"hook failed: stderr={loud.stderr!r}"-- # Positive control: without quiet the welcome is present, so the assertion- # below is testing suppression rather than an unrelated early exit.- assert WELCOME in loud.stdout, f"control run lost the welcome: {loud.stdout!r}"- assert WELCOME not in quiet.stdout, f"quiet run kept the welcome: {quiet.stdout!r}"--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_quiet_keeps_status_and_drops_scrapecreators_tip(tmp_path: Path):- """Setup done without ScrapeCreators: status survives, the upsell does not."""- base = {"SETUP_COMPLETE": "true"}- quiet = _run_hook({**base, "LAST30DAYS_CONFIG_DIR": _cfg_dir(tmp_path, "a"), "LAST30DAYS_QUIET": "1"})- loud = _run_hook({**base, "LAST30DAYS_CONFIG_DIR": _cfg_dir(tmp_path, "b")})-- assert quiet.returncode == 0, f"hook failed: stderr={quiet.stderr!r}"- assert loud.returncode == 0, f"hook failed: stderr={loud.stderr!r}"-- assert TIP in loud.stdout, f"control run lost the tip: {loud.stdout!r}"- assert TIP not in quiet.stdout, f"quiet run kept the tip: {quiet.stdout!r}"- # Quiet trims the copy, it does not silence a configured install.- assert STATUS in quiet.stdout, f"quiet run lost the status line: {quiet.stdout!r}"--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_quiet_honored_from_config_file(tmp_path: Path):- """The global .env can set quiet, matching how every other setting resolves."""- cfg = _cfg_dir(tmp_path, "a", env_body="SETUP_COMPLETE=true\nLAST30DAYS_QUIET=true\n")- control = _cfg_dir(tmp_path, "b", env_body="SETUP_COMPLETE=true\n")-- quiet = _run_hook({"LAST30DAYS_CONFIG_DIR": cfg})- loud = _run_hook({"LAST30DAYS_CONFIG_DIR": control})-- assert quiet.returncode == 0, f"hook failed: stderr={quiet.stderr!r}"- assert loud.returncode == 0, f"hook failed: stderr={loud.stderr!r}"-- assert TIP in loud.stdout, f"control run lost the tip: {loud.stdout!r}"- assert TIP not in quiet.stdout, f"config-file quiet was ignored: {quiet.stdout!r}"--[email protected](shutil.which("bash") is None, reason="bash not on PATH")[email protected]("value", ["0", "false", "no", "off", ""])-def test_falsy_values_do_not_enable_quiet(tmp_path: Path, value: str):- """Only the documented truthy set turns quiet on; everything else is a no-op."""- result = _run_hook(- {- "SETUP_COMPLETE": "true",- "LAST30DAYS_CONFIG_DIR": _cfg_dir(tmp_path),- "LAST30DAYS_QUIET": value,- }- )-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- assert TIP in result.stdout, (- f"LAST30DAYS_QUIET={value!r} should not enable quiet mode: {result.stdout!r}"- )--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_quiet_preserves_last_run_line_when_unconfigured(tmp_path: Path):- """Quiet drops onboarding copy, not the last-run status a returning user wants."""- result = _run_hook(- {"LAST30DAYS_CONFIG_DIR": _cfg_dir(tmp_path), "LAST30DAYS_QUIET": "1"}- )-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- assert WELCOME not in result.stdout- assert "quiet mode" in result.stdout, (- f"expected the last-run topic to survive quiet mode: {result.stdout!r}"- )diff --git a/tests/test_check_config_x_bearer.py b/tests/test_check_config_x_bearer.pydeleted file mode 100644index 255057ac..00000000--- a/tests/test_check_config_x_bearer.py+++ /dev/null@@ -1,115 +0,0 @@-"""hooks/scripts/check-config.sh: X_BEARER_TOKEN counts toward HAS_X (U6/R17).--The SessionStart hook counts X as an active source when a cookie pair-(AUTH_TOKEN + CT0) or XAI_API_KEY is present. The X API bearer is a third-way to have X, so a bearer set alone must raise the numeric source count by-exactly one, the same way XAI_API_KEY alone does.-"""--from __future__ import annotations--import os-import re-import shutil-import subprocess-from pathlib import Path--import pytest--HOOK = Path(__file__).resolve().parents[1] / "hooks" / "scripts" / "check-config.sh"--_CREDENTIAL_VARS = (- "LAST30DAYS_MEMORY_DIR",- "SETUP_COMPLETE",- "LAST30DAYS_CONFIG_DIR",- "LAST30DAYS_TRUST_PROJECT_CONFIG",- "OPENAI_API_KEY",- "SCRAPECREATORS_API_KEY",- "AUTH_TOKEN",- "CT0",- "XAI_API_KEY",- "X_BEARER_TOKEN",- "BSKY_HANDLE",- "EXA_API_KEY",- "EXCLUDE_SOURCES",-)---def _isolated_path(tmp_path: Path) -> str:- """PATH with a stub ``security`` so a real Keychain item cannot leak in."""- bin_dir = tmp_path / "hook-bin"- bin_dir.mkdir(exist_ok=True)- security = bin_dir / "security"- if not security.exists():- security.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")- security.chmod(0o755)- return f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"---def _run_hook(tmp_path: Path, overrides: dict[str, str]) -> subprocess.CompletedProcess[str]:- bash_path = shutil.which("bash")- if bash_path is None:- pytest.skip("bash not on PATH")- env = os.environ.copy()- for key in _CREDENTIAL_VARS:- env.pop(key, None)- cfg_dir = tmp_path / "cfg"- cfg_dir.mkdir(exist_ok=True)- env["LAST30DAYS_CONFIG_DIR"] = str(cfg_dir) # no .env file inside: env-only- env["LAST30DAYS_MEMORY_DIR"] = str(tmp_path / "mem")- env["PATH"] = _isolated_path(tmp_path)- env["SETUP_COMPLETE"] = "true"- env.update(overrides)- return subprocess.run(- [bash_path, str(HOOK)],- capture_output=True,- text=True,- env=env,- cwd=str(tmp_path),- timeout=30,- check=False,- )---def _source_count(stdout: str) -> int:- match = re.search(r"Ready\s+[—–-]\s+(\d+)\s+sources?\s+active", stdout)- assert match, f"could not find source count in hook stdout: {stdout!r}"- return int(match.group(1))---def test_x_bearer_token_alone_counts_x_as_active(tmp_path: Path):- base = _run_hook(tmp_path, {})- assert base.returncode == 0, base.stderr- bearer = _run_hook(tmp_path, {"X_BEARER_TOKEN": "dummy-x-bearer-not-real"})- assert bearer.returncode == 0, bearer.stderr- xai = _run_hook(tmp_path, {"XAI_API_KEY": "dummy-xai-not-real"})- assert xai.returncode == 0, xai.stderr-- assert _source_count(bearer.stdout) == _source_count(base.stdout) + 1- # Same weight as the xAI key: X is one source however it is reached.- assert _source_count(bearer.stdout) == _source_count(xai.stdout)- # The hook never echoes credential values.- assert "dummy-x-bearer-not-real" not in bearer.stdout + bearer.stderr---def test_x_bearer_token_from_env_file_counts_x_as_active(tmp_path: Path):- cfg_dir = tmp_path / "cfg"- cfg_dir.mkdir(exist_ok=True)- env_file = cfg_dir / ".env"- env_file.write_text("SETUP_COMPLETE=true\nX_BEARER_TOKEN=dummy-x-bearer-not-real\n", encoding="utf-8")- env_file.chmod(0o600)- with_file = _run_hook(tmp_path, {})- assert with_file.returncode == 0, with_file.stderr-- env_file.write_text("SETUP_COMPLETE=true\n", encoding="utf-8")- without = _run_hook(tmp_path, {})- assert without.returncode == 0, without.stderr-- assert _source_count(with_file.stdout) == _source_count(without.stdout) + 1- assert "dummy-x-bearer-not-real" not in with_file.stdout + with_file.stderr---def test_bearer_and_xai_key_together_count_x_once(tmp_path: Path):- both = _run_hook(tmp_path, {"X_BEARER_TOKEN": "dummy-a", "XAI_API_KEY": "dummy-b"})- xai = _run_hook(tmp_path, {"XAI_API_KEY": "dummy-b"})- assert _source_count(both.stdout) == _source_count(xai.stdout)diff --git a/tests/test_check_config_ytdlp_detection.py b/tests/test_check_config_ytdlp_detection.pydeleted file mode 100644index b07c548f..00000000--- a/tests/test_check_config_ytdlp_detection.py+++ /dev/null@@ -1,255 +0,0 @@-"""Tests for hooks/scripts/check-config.sh yt-dlp detection on the new-user path.--Covers issue #394 — new users with yt-dlp installed were never told YouTube was-available, because the capability-detection block ran AFTER the new-user early-exit. The SessionStart hook should detect yt-dlp on PATH and mention it in the-welcome message even when no config exists.--Cases:- - new user + yt-dlp on PATH -> welcome says YouTube works out of the box- - new user + no yt-dlp on PATH -> welcome unchanged (wizard can unlock YouTube)- - existing user + yt-dlp -> numeric source count is higher than without-"""--from __future__ import annotations--import json-import os-import re-import shutil-import subprocess-from pathlib import Path--import pytest--HOOK = Path(__file__).resolve().parents[1] / "hooks" / "scripts" / "check-config.sh"---def _run_hook(env_overrides: dict[str, str], path_override: str | None = None) -> subprocess.CompletedProcess:- env = os.environ.copy()- for k in (- "LAST30DAYS_MEMORY_DIR",- "SETUP_COMPLETE",- "LAST30DAYS_CONFIG_DIR",- "OPENAI_API_KEY",- "SCRAPECREATORS_API_KEY",- "AUTH_TOKEN",- "XAI_API_KEY",- "CT0",- "BSKY_HANDLE",- "BSKY_APP_PASSWORD",- "EXA_API_KEY",- ):- env.pop(k, None)- env.update(env_overrides)- if path_override is not None:- env["PATH"] = path_override- bash_path = shutil.which("bash")- if bash_path is None:- pytest.skip("bash not on PATH")- return subprocess.run(- [bash_path, str(HOOK)],- capture_output=True,- text=True,- env=env,- timeout=30,- )---def _tool_path_without_ytdlp(tmp_path: Path) -> str:- """Build a tiny PATH with hook dependencies but no yt-dlp."""- tool_bin = tmp_path / "tool_bin"- tool_bin.mkdir(exist_ok=True)- for name in ("cat", "id", "mkdir", "python3", "sed", "stat", "tr", "uname"):- target = shutil.which(name)- if target is None:- if name == "python3":- continue- pytest.skip(f"{name} not on PATH")- link = tool_bin / name- if not link.exists():- link.symlink_to(target)- assert shutil.which("yt-dlp", path=str(tool_bin)) is None- return str(tool_bin)---def _write_fake_last_run(tmp_path: Path) -> str:- """Write a minimal last-run.json and return the LAST30DAYS_CONFIG_DIR the hook- should be pointed at.-- The hook reads ``$LAST30DAYS_CONFIG_DIR/last-run.json`` and runs a python3- subshell on it. Without this file, the hook's last-run line stays empty- and a pre-existing bug (#440) makes the script exit 1 even on success.- We don't want our regression test to depend on that bug, so we always- provide a well-formed last-run.json.- """- cfg_dir = tmp_path / "last30days_cfg"- cfg_dir.mkdir()- (cfg_dir / "last-run.json").write_text(- json.dumps(- {- "topic": "test topic",- "timestamp": "2026-06-01T00:00:00Z",- "total": 0,- }- )- )- return str(cfg_dir)---def _parse_source_count(stdout: str) -> int:- """Extract the source count from the 'Ready — N sources active.' line.-- The script emits the count in both the fully-configured and the- 'setup-done but missing ScrapeCreators' branches.- """- match = re.search(r"Ready\s+[—–-]\s+(\d+)\s+sources?\s+active", stdout)- assert match, f"could not find source count in hook stdout: {stdout!r}"- return int(match.group(1))--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_new_user_with_ytdlp_says_youtube_works(tmp_path: Path):- """A new user with yt-dlp on PATH should see YouTube flagged as already-working."""- fake_bin = tmp_path / "fake_bin"- fake_bin.mkdir()- (fake_bin / "yt-dlp").touch()- (fake_bin / "yt-dlp").chmod(0o755)-- # PATH must contain bash (so the hook can run) AND the fake yt-dlp dir.- # Putting fake_bin FIRST means any real yt-dlp elsewhere is shadowed.- path = f"{fake_bin}:{_tool_path_without_ytdlp(tmp_path)}"- assert shutil.which("yt-dlp", path=path) is not None, (- "test pre-condition: fake yt-dlp should resolve on the override PATH"- )-- cfg_dir = _write_fake_last_run(tmp_path)- result = _run_hook({"LAST30DAYS_CONFIG_DIR": cfg_dir}, path_override=path)-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- # The welcome message is now consistent: it explicitly says YouTube is- # working via yt-dlp, AND drops "YouTube" from the wizard-unlock line so- # the two don't contradict each other (see #394 follow-up).- assert "Detected: yt-dlp" in result.stdout, (- f"expected yt-dlp detection line, got: {result.stdout!r}"- )- assert "YouTube (yt-dlp detected) work out of the box" in result.stdout, (- f"expected yt-dlp-aware YouTube line, got: {result.stdout!r}"- )- # The wizard line should NOT advertise YouTube as something the wizard unlocks,- # because yt-dlp is already providing it.- assert "wizard can unlock X/Twitter, YouTube, and more" not in result.stdout, (- f"welcome should not claim wizard unlocks YouTube when yt-dlp is present: {result.stdout!r}"- )--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_new_user_without_ytdlp_unchanged_welcome(tmp_path: Path):- """A new user without yt-dlp should see the original wizard-unlock copy."""- path = _tool_path_without_ytdlp(tmp_path)- assert shutil.which("yt-dlp", path=path) is None, (- "test pre-condition: yt-dlp should not resolve on the minimal PATH"- )-- cfg_dir = _write_fake_last_run(tmp_path)- result = _run_hook({"LAST30DAYS_CONFIG_DIR": cfg_dir}, path_override=path)-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- # No detection line, no yt-dlp-aware copy, original wizard line preserved.- assert "Detected: yt-dlp" not in result.stdout- assert "yt-dlp detected" not in result.stdout- assert "wizard can unlock X/Twitter, YouTube, and more" in result.stdout, (- f"expected unchanged wizard line, got: {result.stdout!r}"- )--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_setup_done_user_source_count_includes_ytdlp(tmp_path: Path):- """Regression: the setup-done path must count YouTube when yt-dlp is on PATH.-- Runs the hook twice — once with yt-dlp and once without — and asserts the- numeric source count is exactly 1 higher with yt-dlp present. This catches- a real regression where HAS_YTDLP gets zeroed out before the counting block.- """- cfg_dir = _write_fake_last_run(tmp_path)- base_env = {- "SETUP_COMPLETE": "true",- "SCRAPECREATORS_API_KEY": "sc_test",- "LAST30DAYS_CONFIG_DIR": cfg_dir,- }-- # 1) Run WITH yt-dlp- fake_bin = tmp_path / "fake_bin_with"- fake_bin.mkdir()- (fake_bin / "yt-dlp").touch()- (fake_bin / "yt-dlp").chmod(0o755)- path_with = f"{fake_bin}:{_tool_path_without_ytdlp(tmp_path)}"- assert shutil.which("yt-dlp", path=path_with) is not None-- with_yt = _run_hook(base_env, path_override=path_with)- assert with_yt.returncode == 0, f"hook failed: stderr={with_yt.stderr!r}"- count_with = _parse_source_count(with_yt.stdout)-- # 2) Run WITHOUT yt-dlp (minimal PATH)- path_without = _tool_path_without_ytdlp(tmp_path)- assert shutil.which("yt-dlp", path=path_without) is None-- without_yt = _run_hook(base_env, path_override=path_without)- assert without_yt.returncode == 0, f"hook failed: stderr={without_yt.stderr!r}"- count_without = _parse_source_count(without_yt.stdout)-- # YouTube adds exactly one source to the count.- assert count_with == count_without + 1, (- f"expected YouTube to add exactly 1 source; got "- f"{count_with} (with yt-dlp) vs {count_without} (without). "- f"Stdout with: {with_yt.stdout!r}\n"- f"Stdout without: {without_yt.stdout!r}"- )--[email protected](shutil.which("bash") is None, reason="bash not on PATH")-def test_keychain_credentials_avoid_new_user_welcome(tmp_path: Path):- """macOS Keychain credentials should count as configured for the status hook."""- fake_bin = tmp_path / "fake_bin_keychain"- fake_bin.mkdir()-- uname = fake_bin / "uname"- uname.write_text("#!/bin/sh\necho Darwin\n", encoding="utf-8")- uname.chmod(0o755)-- security = fake_bin / "security"- security.write_text(- """#!/bin/sh-service=""-while [ "$#" -gt 0 ]; do- if [ "$1" = "-s" ]; then- service="$2"- shift 2- else- shift- fi-done-case "$service" in- last30days-XAI_API_KEY|last30days-SCRAPECREATORS_API_KEY) exit 0 ;;- *) exit 44 ;;-esac-""",- encoding="utf-8",- )- security.chmod(0o755)-- cfg_dir = _write_fake_last_run(tmp_path)- path = f"{fake_bin}:{_tool_path_without_ytdlp(tmp_path)}"- result = _run_hook(- {- "HOME": str(tmp_path),- "LAST30DAYS_CONFIG_DIR": cfg_dir,- },- path_override=path,- )-- assert result.returncode == 0, f"hook failed: stderr={result.stderr!r}"- assert "Ready to use. Run /last30days" not in result.stdout- assert "Ready" in result.stdout- assert "sources active" in result.stdout- assert "Tip: Add ScrapeCreators" not in result.stdoutdiff --git a/tests/test_codex_host_contract.py b/tests/test_codex_host_contract.pyindex 2d05c62c..c30360b6 100644--- a/tests/test_codex_host_contract.py+++ b/tests/test_codex_host_contract.py@@ -37,19 +37,15 @@ def test_non_modal_cookie_consent_uses_engine_allow_flag():assert consent < decline-def test_non_modal_preflight_runs_before_cookie_consent():+def test_non_modal_does_not_require_preflight_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+ assert "--preflight" not in prose+ assert consent > prose.index("Welcome")-def test_non_modal_completion_mentions_safe_diagnose_and_project_trust():+def test_non_modal_completion_mentions_project_trust():prose = _prose_flow()- assert "safe `--diagnose`" in proseassert "LAST30DAYS_TRUST_PROJECT_CONFIG=1" in proseassert "Codex desktop" in prosediff --git a/tests/test_diagnose_compat.py b/tests/test_diagnose_compat.pyindex ce9221ab..67f1aef1 100644--- a/tests/test_diagnose_compat.py+++ b/tests/test_diagnose_compat.py@@ -20,8 +20,7 @@ The two real consumers, each with an explicit test:authoritative source list). Asserted: the key exists, is a list ofsource-name strings.-hooks/scripts/check-config.sh is NOT a JSON consumer (it reads env files and-last-run.json, never engine JSON) — deliberately no compat test for it.+There is no SessionStart hook; last-run.json is not consumed at session start.NOTE: snapshots re-recorded against the committed v3.10.0 baseline(origin/main a5b3ca1, post-v3.9.x source wave: arxiv/techmeme/stocktwits/diff --git a/tests/test_grok_bot_host_contract.py b/tests/test_grok_bot_host_contract.pyindex 7ad94d06..bc2e6091 100644--- a/tests/test_grok_bot_host_contract.py+++ b/tests/test_grok_bot_host_contract.py@@ -135,7 +135,6 @@ class TestGrokBotProseFlow(unittest.TestCase):"about the last week","SETUP_COMPLETE=true","X_DECLINED=grok-bot",- "--preflight",):self.assertIn(token, self.flow, token)diff --git a/tests/test_last_run_state.py b/tests/test_last_run_state.pyindex 2491539f..af445cda 100644--- a/tests/test_last_run_state.py+++ b/tests/test_last_run_state.py@@ -1,9 +1,6 @@import ioimport jsonimport os-import re-import shutil-import statimport subprocessimport sysimport tempfile@@ -327,183 +324,6 @@ class LastRunStateTests(unittest.TestCase):self.assertIn("No matching cached report data", stderr.getvalue())self.assertIn("Cached synthesis body.", stdout.getvalue())- @unittest.skipIf(shutil.which("bash") is None, "bash not available")- def test_hook_reads_last_run_from_custom_config_dir(self):- with tempfile.TemporaryDirectory() as tmp:- config_dir = Path(tmp) / "custom-config"- config_dir.mkdir()- (config_dir / "last-run.json").write_text(- json.dumps(- {- "topic": "custom hook query",- "timestamp": "2026-04-30T00:00:00+00:00",- "sources": {"reddit": 2},- "total": 2,- }- )- )- env = os.environ.copy()- env["HOME"] = str(Path(tmp) / "home")- env["LAST30DAYS_CONFIG_DIR"] = str(config_dir)-- result = subprocess.run(- ["bash", "hooks/scripts/check-config.sh"],- cwd=REPO_ROOT,- env=env,- capture_output=True,- text=True,- check=False,- )-- self.assertEqual(result.returncode, 0, result.stderr)- self.assertIn('Last run: "custom hook query"', result.stdout)-- def test_hook_exits_0_when_no_last_run(self):- """Script exits 0 when ScrapeCreators configured but no prior run (last-run.json absent)."""- with tempfile.TemporaryDirectory() as tmp:- env = os.environ.copy()- env["HOME"] = str(Path(tmp) / "home")- env["SETUP_COMPLETE"] = "true"- env["ENV_SCRAPECREATORS_API_KEY"] = "sk-test"-- result = subprocess.run(- ["bash", "hooks/scripts/check-config.sh"],- cwd=REPO_ROOT,- env=env,- capture_output=True,- text=True,- check=False,- )-- self.assertEqual(result.returncode, 0, result.stderr)- self.assertIn("Ready —", result.stdout)- self.assertNotIn("Last run:", result.stdout)-- def test_hook_parses_dotenv_with_unbalanced_quote(self):- """Script exits 0 when .env contains an unbalanced quote in a value."""- with tempfile.TemporaryDirectory() as tmp:- home = Path(tmp) / "home"- config_dir = home / ".config" / "last30days"- config_dir.mkdir(parents=True)- env_file = config_dir / ".env"- env_file.write_text(- "SETUP_COMPLETE=true\n"- "XAI_API_KEY=xai-key-with-apostrophe's-ok\n"- "AUTH_TOKEN=test-auth\n"- "CT0=test-ct0\n"- )- env = os.environ.copy()- env["HOME"] = str(home)-- result = subprocess.run(- ["bash", "hooks/scripts/check-config.sh"],- cwd=REPO_ROOT,- env=env,- capture_output=True,- text=True,- check=False,- )-- self.assertEqual(result.returncode, 0, result.stderr)- self.assertIn("Ready —", result.stdout)-- @staticmethod- def _extract_source_count(output: str) -> int:- match = re.search(r"Ready — (\d+) sources active", output)- if not match:- raise AssertionError(f"Could not find source count in: {repr(output[:200])}")- return int(match.group(1))-- def _run_hook(self, tmp: str, env_overrides: dict[str, str]) -> subprocess.CompletedProcess[str]:- env = os.environ.copy()- env["HOME"] = str(Path(tmp) / "home")- env["SETUP_COMPLETE"] = "true"- # Strip credentials that could bleed in from the test-runner environment- # and corrupt source-count baseline comparisons.- for key in ("AUTH_TOKEN", "CT0", "XAI_API_KEY", "BSKY_HANDLE", "EXA_API_KEY", "SCRAPECREATORS_API_KEY"):- env.pop(key, None)- env.update(env_overrides)- return subprocess.run(- ["bash", "hooks/scripts/check-config.sh"],- cwd=REPO_ROOT,- env=env,- capture_output=True,- text=True,- check=False,- )-- def test_x_not_counted_with_only_auth_token(self):- with tempfile.TemporaryDirectory() as tmp:- neither = self._extract_source_count(- self._run_hook(tmp, {}).stdout- )- only_auth = self._extract_source_count(- self._run_hook(tmp, {"AUTH_TOKEN": "test_auth"}).stdout- )- self.assertEqual(- only_auth, neither,- "X should not be counted when only AUTH_TOKEN is set (CT0 missing)",- )-- def test_x_not_counted_with_only_ct0(self):- with tempfile.TemporaryDirectory() as tmp:- neither = self._extract_source_count(- self._run_hook(tmp, {}).stdout- )- only_ct0 = self._extract_source_count(- self._run_hook(tmp, {"CT0": "test_ct0"}).stdout- )- self.assertEqual(- only_ct0, neither,- "X should not be counted when only CT0 is set (AUTH_TOKEN missing)",- )-- def test_x_counted_when_both_auth_token_and_ct0(self):- with tempfile.TemporaryDirectory() as tmp:- neither = self._extract_source_count(- self._run_hook(tmp, {}).stdout- )- both = self._extract_source_count(- self._run_hook(tmp, {"AUTH_TOKEN": "test_auth", "CT0": "test_ct0"}).stdout- )- self.assertEqual(- both, neither + 1,- "X should add 1 source when both AUTH_TOKEN and CT0 are set",- )-- def test_hook_shows_last_run_when_json_exists(self):- """Script exits 0 and shows last-run summary when last-run.json exists."""- with tempfile.TemporaryDirectory() as tmp:- config_dir = Path(tmp) / "custom-config"- config_dir.mkdir()- (config_dir / "last-run.json").write_text(- json.dumps(- {- "topic": "prior research",- "timestamp": "2026-06-01T12:00:00+00:00",- "sources": {"reddit": 5},- "total": 5,- }- )- )- env = os.environ.copy()- env["HOME"] = str(Path(tmp) / "home")- env["SETUP_COMPLETE"] = "true"- env["ENV_SCRAPECREATORS_API_KEY"] = "sk-test"- env["LAST30DAYS_CONFIG_DIR"] = str(config_dir)-- result = subprocess.run(- ["bash", "hooks/scripts/check-config.sh"],- cwd=REPO_ROOT,- env=env,- capture_output=True,- text=True,- check=False,- )-- self.assertEqual(result.returncode, 0, result.stderr)- self.assertIn('Last run: "prior research"', result.stdout)-class TestSkillMdFirstRunReference(unittest.TestCase):"""Verifies SKILL.md references that exist in the CLI."""@@ -537,34 +357,6 @@ class TestSkillMdFirstRunReference(unittest.TestCase):mock_write.assert_called_once()-class TestCheckPermsAutoFix(unittest.TestCase):- """check_perms should auto-fix loose .env permissions instead of warning only."""-- def test_loose_env_is_tightened_by_check_perms(self):- with tempfile.TemporaryDirectory() as tmp:- config_dir = Path(tmp) / ".config" / "last30days"- config_dir.mkdir(parents=True)- env_file = config_dir / ".env"- env_file.write_text("SETUP_COMPLETE=true\n")- os.chmod(env_file, 0o644)-- env = os.environ.copy()- env["HOME"] = str(Path(tmp))- env["LAST30DAYS_CONFIG_DIR"] = str(config_dir)-- result = subprocess.run(- ["bash", "hooks/scripts/check-config.sh"],- cwd=REPO_ROOT,- env=env,- capture_output=True,- text=True,- check=False,- )-- self.assertEqual(result.returncode, 0, result.stderr)- self.assertIn("auto-fixed", result.stdout.lower())- self.assertEqual(stat.S_IMODE(os.stat(env_file).st_mode), 0o600)-if __name__ == "__main__":unittest.main()diff --git a/tests/test_onboarding_contract.py b/tests/test_onboarding_contract.pyindex a1e54909..1f57fa95 100644--- a/tests/test_onboarding_contract.py+++ b/tests/test_onboarding_contract.py@@ -72,6 +72,34 @@ class TestOnboardingContract(unittest.TestCase):self.assertLess(self.grok.index("search_posts_all"), self.grok.index("X_BEARER_TOKEN"))self.assertIn("setup --store-key", self.grok)+ def test_first_run_flows_do_not_invoke_preflight(self):+ """Status and permission inspection are not a required first-run beat.+ `--preflight` stays an opt-in inspector; Step 0 must not dump `.env`."""+ self.assertNotIn("--preflight", self.modal)+ self.assertNotIn("--preflight", self.prose)+ self.assertNotIn("--preflight", self.grok)+ self.assertIn("Do not run it as a required first-run step", self.step0)+ self.assertIn("Do not print `.env` contents or credential values", self.step0)++ def test_first_run_gate_defers_to_step0_credential_sources(self):+ """The cheap SETUP_COMPLETE grep is not itself a first-run verdict."""+ start = self.text.index("**FIRST-RUN GATE")+ end = self.text.index("\n## Step 0: First-Run Setup Wizard")+ gate = self.text[start:end]+ self.assertIn("FIRST_RUN_DETECTED", gate)+ self.assertIn("A missing `.env` alone is not a first run", gate)+ self.assertIn("That section decides first-run from every credential source", gate)++ def test_complete_does_not_treat_setup_stdout_as_source_list(self):+ self.assertIn(+ "Setup stdout is what this run installed, not the runtime source list",+ self.prose,+ )+ self.assertIn(+ "Setup stdout is what this run installed, not the runtime source list",+ self.grok,+ )+def test_hard_gate_step0_before_step1(self):"""The erosion-resistant gate that orphaned the wizard in #659 is restored."""self.assertIn("ALWAYS execute Step 0 BEFORE Step 1", self.step0)diff --git a/tests/test_plugin_contract.py b/tests/test_plugin_contract.pyindex 237661e7..fd294872 100644--- a/tests/test_plugin_contract.py+++ b/tests/test_plugin_contract.py@@ -143,16 +143,11 @@ class TestPluginContract(unittest.TestCase):self.assertEqual([], offenders)- def test_session_start_hook_uses_bare_claude_plugin_root(self) -> None:- # Claude Code's missing-plugin-root guard matches the exact literal- # ${CLAUDE_PLUGIN_ROOT}. Defaults like ${CLAUDE_PLUGIN_ROOT:-.} slip past- # that check and resolve relative to the session cwd (issue #1074).- hooks = _json(ROOT / "hooks" / "hooks.json")- command = hooks["hooks"]["SessionStart"][0]["hooks"][0]["command"]- self.assertIn("${CLAUDE_PLUGIN_ROOT}", command)- self.assertNotIn(":-", command)- self.assertNotIn("extensionPath", command)- self.assertNotIn(":-.}", command)+ def test_plugin_ships_no_session_start_hook(self) -> None:+ # SessionStart ran in every Claude Code / Grok session whether or not+ # /last30days was invoked. First-run NUX lives in SKILL.md Step 0.+ self.assertFalse((ROOT / "hooks" / "hooks.json").exists())+ self.assertFalse((ROOT / "hooks" / "scripts" / "check-config.sh").exists())def test_mcp_manifest_credential_entries_are_sensitive(self) -> None:# Every user_config entry that names a credential (title ends in _KEYdiff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.pyindex 87f8ff8b..849e5ddc 100644--- a/tests/test_source_outcomes.py+++ b/tests/test_source_outcomes.py@@ -1,6 +1,5 @@import socketimport urllib.error-from datetime import datetime, timedelta, timezonefrom unittest.mock import MagicMock, patchimport pytest@@ -363,9 +362,10 @@ def test_pipeline_records_both_mode_semantic_leg_failure_as_partial():"title": "Search result","url": "https://example.com/result","snippet": "Raw search evidence",- # Relative so the item stays inside the run window; a fixed date fell out- # of the 30-day window and turned PARTIAL into ERROR once the calendar moved.- "date": (datetime.now(timezone.utc) - timedelta(days=5)).date().isoformat(),+ # Inside the pinned as_of window below. A wall-clock relative date+ # (today-5) falls outside 2026-07-21..2026-08-20 once the calendar+ # moves past late August, and the failure then records as ERROR.+ "date": "2026-08-15","relevance": 0.8,"why_relevant": "Perplexity Search result","engagement": {},@@ -387,9 +387,6 @@ def test_pipeline_records_both_mode_semantic_leg_failure_as_partial():"PERPLEXITY_API_KEY": "pplx-test",},depth="quick",- # Pin both ends of the window. The fixture item is dated 2026-08-10,- # so an unpinned window drops it once the wall clock moves 30 days- # past that date and the failure then records as ERROR, not PARTIAL.lookback_days=30,as_of_date="2026-08-20",requested_sources=["perplexity"],