AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(x): give Grok Bot users X with zero setup via its built-in X tools (#1235)
Matt Van Horn98f8558bb6aa
diff --git a/AGENTS.md b/AGENTS.mdindex 07d7be00..002206ec 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -60,7 +60,7 @@ Agents open most PRs. Follow this so `CHANGELOG.md` stops conflicting and versio- Do not reduce `fail_under` in `pyproject.toml` (`[tool.coverage.report]`) without documenting why in the PR. The coverage gate is a floor meant to rise over time, not to be relaxed when new code is under-tested.- Every `lib/*.py` call to `log.source_log(...)` must pass `tty_only=False`. The default is `True`, which silently drops every line when stderr isn't a TTY (Claude Code, Codex, CI, captured output) — turning source observability into invisible failure. Enforced by `tests/test_source_log_visibility.py`.- **CLI-gated optional sources** (Digg via `digg-pp-cli`, YouTube via `yt-dlp`) activate only when `shutil.which` resolves the binary on the **agent subprocess PATH** — not merely when the file exists on disk. First-run setup installs Digg through `@mvanhorn/printing-press-library` (default `$HOME/.local/bin`); Hermes/OpenClaw gateways often need that directory on PATH. Setup must distinguish PATH-visible installs from off-PATH binaries and must not claim "now active" unless the engine gate would pass. See `docs/solutions/integration-issues/digg-cli-agent-path-setup-wizard.md`.-- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth, and emitting the engine-owned welcome via `--welcome`) — it cannot prompt, so consent lives in the root `SKILL.md` gate and Step 0 of `references/setup-wizard.md`. Two flows avoid model-authored prose that Claude Code folds or the model skips: in the **Modal Flow** the welcome pitch is embedded in the setup modal's question (the AskUserQuestion modal is the only always-fully-visible surface — a separate welcome message or `--welcome` Bash run gets buried behind "ctrl+o to expand"); the **Non-Modal Prose Flow** still uses `last30days.py --welcome` (relayed verbatim) since it has no modal. The GitHub device code is surfaced by a two-command split — `setup --github-start` returns the code fast (foreground, copies to clipboard) and `setup --github-poll` waits for authorization (`setup --github` still chains both for back-compat). Step 0 has THREE branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI, Grok CLI), and a **Grok Bot Prose Flow** for the Grok Bot host (`LAST30DAYS_HOST=grok-bot`), which leads with the bot's X connector lane (`LAST30DAYS_X_HOST_LANE=1` plus a `--x-posts` envelope the model fetches itself), persists any backup key (`X_BEARER_TOKEN` / `XAI_API_KEY`) only through the engine's `setup --store-key` path, and never reads a browser session. The first two ask before reading cookies and surface the macOS Full Disk Access fix on permission-denied; all three offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers, both comment-enabled: **Recommended** (TikTok + Instagram posts AND top comments, plus YouTube comments — `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments`) and **Everything** (also Threads + Pinterest). Comments are on by default (posts on → comments on for all three platforms); **Threads and Pinterest are the only opt-in extras**, appearing only in the Step 5 Everything option, never in the welcome or the Step 4 offer. Instagram comments are fetched via ScrapeCreators (`/v2/instagram/post/comments`, ranked by `comment_like_count`) with full vote-weighting parity to YouTube/TikTok (a dedicated `_instagram_engagement` carve-out, the `_VOTE_LOG_REFERENCE`/label/threshold entries). The cross-platform "Top Community Comments" list (`render._render_top_comments`) selects **round-robin by within-platform rank** (every platform's #1, then #2, then #3) so a viral platform can't crowd out a smaller one, and drops the per-platform absolute floor so a less-watched video's killer low-vote comment still surfaces.+- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth, and emitting the engine-owned welcome via `--welcome`) — it cannot prompt, so consent lives in the root `SKILL.md` gate and Step 0 of `references/setup-wizard.md`. Two flows avoid model-authored prose that Claude Code folds or the model skips: in the **Modal Flow** the welcome pitch is embedded in the setup modal's question (the AskUserQuestion modal is the only always-fully-visible surface — a separate welcome message or `--welcome` Bash run gets buried behind "ctrl+o to expand"); the **Non-Modal Prose Flow** still uses `last30days.py --welcome` (relayed verbatim) since it has no modal. The GitHub device code is surfaced by a two-command split — `setup --github-start` returns the code fast (foreground, copies to clipboard) and `setup --github-poll` waits for authorization (`setup --github` still chains both for back-compat). Step 0 has THREE branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI, Grok CLI), and a **Grok Bot Prose Flow** for the Grok Bot host (`LAST30DAYS_HOST=grok-bot`), which leads with the bot's own X lanes (its built-in X tools first, then the X for Grok Bot connector; `LAST30DAYS_X_HOST_LANE=1` plus a `--x-posts` envelope the model fetches itself, exported only when the fetch returned posts), persists any backup key (`X_BEARER_TOKEN` / `XAI_API_KEY`) only through the engine's `setup --store-key` path, and never reads a browser session. The first two ask before reading cookies and surface the macOS Full Disk Access fix on permission-denied; all three offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers, both comment-enabled: **Recommended** (TikTok + Instagram posts AND top comments, plus YouTube comments — `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments`) and **Everything** (also Threads + Pinterest). Comments are on by default (posts on → comments on for all three platforms); **Threads and Pinterest are the only opt-in extras**, appearing only in the Step 5 Everything option, never in the welcome or the Step 4 offer. Instagram comments are fetched via ScrapeCreators (`/v2/instagram/post/comments`, ranked by `comment_like_count`) with full vote-weighting parity to YouTube/TikTok (a dedicated `_instagram_engagement` carve-out, the `_VOTE_LOG_REFERENCE`/label/threshold entries). The cross-platform "Top Community Comments" list (`render._render_top_comments`) selects **round-robin by within-platform rank** (every platform's #1, then #2, then #3) so a viral platform can't crowd out a smaller one, and drops the per-platform absolute floor so a less-watched video's killer low-vote comment still surfaces.## Security hygiene- Never commit real API keys, browser cookies, auth tokens, app passwords, access tokens, or `.env` contents.diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 24158f82..efe6b712 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -85,7 +85,7 @@ When no credential source shows completed setup, the skill runs consent-driven o- **Claude Code Modal Flow** - the restored v3.0.0 guided NUX, used on hosts with `AskUserQuestion` (Claude Code). A welcome message, then modals for Auto/Manual/Skip setup, cookie consent, the ScrapeCreators signup offer, a TikTok/Instagram `INCLUDE_SOURCES` opt-in, and a first-topic picker.- **Non-Modal Prose Flow** - the same work done conversationally on hosts without modals (OpenClaw, Codex, Cursor, Gemini CLI, Grok, raw CLI).-- **Grok Bot Prose Flow** - the prose flow on a Grok Bot host (`LAST30DAYS_HOST=grok-bot`, persisted to `.env` by this setup). It has no browser-session step: X is set up through the bot's X connector, with `X_BEARER_TOKEN` or `XAI_API_KEY` as backups (see [Grok Bot](#grok-bot) under Per-client patterns).+- **Grok Bot Prose Flow** - the prose flow on a Grok Bot host (`LAST30DAYS_HOST=grok-bot`, persisted to `.env` by this setup). It has no browser-session step: X runs through the bot's built-in X tools with nothing to set up, then the X for Grok Bot connector, with `X_BEARER_TOKEN` or `XAI_API_KEY` as backups (see [Grok Bot](#grok-bot) under Per-client patterns).The Modal and Non-Modal flows share the same consent points:@@ -167,7 +167,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \| Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; searches Techmeme's live archive and keeps only headlines dated within the research window (undated headlines flow through as low-confidence) | yes (free, keyless) || Trustpilot | `trustpilot-pp-cli` on PATH (NOT auto-installed; install on demand via `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`) + (`INCLUDE_SOURCES` contains `trustpilot` **or** an explicit `--trustpilot-domain` / plan-level `trustpilot_domain`) | **opt-in, off by default**; `--trustpilot-domain=<domain>` (and per-entity `trustpilot_domain` in `--competitors-plan`) auto-activates the source for that run and bypasses the brand-shape gate. Persist with `INCLUDE_SOURCES=trustpilot` to skip per-run auto-enable. `EXCLUDE_SOURCES=trustpilot` still wins. Bare company names auto-resolve to the review-page domain via the CLI's search only when the source is already active. The session warms once before the search fan-out; a stale session does a ~10s headless-Chrome WAF-cookie harvest (set `LAST30DAYS_TRUSTPILOT_NO_BROWSER=1` to disable in cron/CI) | yes (no API key; cookie-replay after the one-time harvest) || Amazon | `brightdata` CLI on PATH **and logged in** (NOT auto-installed: `npm i -g @brightdata/cli` then `brightdata login`) + (`INCLUDE_SOURCES` contains `amazon` **or** `--search` includes `amazon`) | product records with live rating, rating count, and price, plus a capped sample of recent written reviews woven as buyer voice; the emoji footer shows each product's all-time-vs-last-30-days drift | **opt-in, off by default**. Free tier is 5,000 requests/month (~$7.50 equivalent); a typical run spends 4 (1 product search + up to 3 review pulls) regardless of how many reviews come back, since billing is per request. Past the free tier it bills the account balance at $1.50 per 1,000 records (~$0.32 for a default run). `--amazon-query=<keyword>` sets the product keyword when it differs from the topic; `LAST30DAYS_AMAZON_DOMAIN` selects a non-US marketplace. `EXCLUDE_SOURCES=amazon` wins. Never auto-fires: the model requests it per run or the user enables it durably |-| X / Twitter | one of: `X_BEARER_TOKEN` (official X API v2; opt-in outside Grok Bot: `LAST30DAYS_X_BACKEND=xapi`; covers recent posts, about the last week, unless your X developer project has full-archive access), a signed-in `grok` CLI (opt-in: `LAST30DAYS_X_BACKEND=grok`), `AUTH_TOKEN` + `CT0` (browser cookies, Bird CLI), `XAI_API_KEY`, `XQUIK_API_KEY`, or `FROM_BROWSER` (cookie-jar auth). On a Grok Bot host the bot's X connector serves X first; see [Grok Bot](#grok-bot) | X items in results | X API bearer = your X developer project's credits; grok = Grok plan, opt-in only; cookie-jar / Bird = free; Xquik / xAI = key-based |+| X / Twitter | one of: `X_BEARER_TOKEN` (official X API v2; opt-in outside Grok Bot: `LAST30DAYS_X_BACKEND=xapi`; covers recent posts, about the last week, unless your X developer project has full-archive access), a signed-in `grok` CLI (opt-in: `LAST30DAYS_X_BACKEND=grok`), `AUTH_TOKEN` + `CT0` (browser cookies, Bird CLI), `XAI_API_KEY`, `XQUIK_API_KEY`, or `FROM_BROWSER` (cookie-jar auth). On a Grok Bot host the bot's built-in X tools (then the X connector) serve X first; see [Grok Bot](#grok-bot) | X items in results | X API bearer = your X developer project's credits; grok = Grok plan, opt-in only; cookie-jar / Bird = free; Xquik / xAI = key-based || TikTok | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `tiktok` | TikTok items | 10K free calls || Instagram | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `instagram` | Instagram Reels | 10K free calls; raise `LAST30DAYS_TRANSCRIPT_TIMEOUT` (default 30s) if SC is slow on your network || Threads | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `threads` | Threads items | 10K free calls |@@ -188,7 +188,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. `LAST30DAYS_YT_PLAYER_CLIENT` defaults to `android` so yt-dlp can pass YouTube's web bot-gate without cookies (search, transcripts, and comments); set it empty to disable. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.-**X backend priority (bird first).** The default X backend chain is bird (browser cookies) → xai (API key) → xurl (OAuth2 CLI) → xquik (API key). Cookies beat `XAI_API_KEY` when both are present. A leftover grok login never steals the X lane; see below. `xapi` (the official X API v2 with `X_BEARER_TOKEN`) is opt-in on these hosts (`LAST30DAYS_X_BACKEND=xapi`), so an ambient bearer never spends X API credits when the free path comes back empty. **Grok Bot exception.** On a Grok Bot host (`LAST30DAYS_HOST=grok-bot`) the unpinned chain is the official chain instead: xapi (`X_BEARER_TOKEN`) → xai (`XAI_API_KEY`) → xurl (the X API through X's CLI). When the bot's X connector is in the session, its results come first and the chain is not called at all; see [Grok Bot](#grok-bot) under Per-client patterns.+**X backend priority (bird first).** The default X backend chain is bird (browser cookies) → xai (API key) → xurl (OAuth2 CLI) → xquik (API key). Cookies beat `XAI_API_KEY` when both are present. A leftover grok login never steals the X lane; see below. `xapi` (the official X API v2 with `X_BEARER_TOKEN`) is opt-in on these hosts (`LAST30DAYS_X_BACKEND=xapi`), so an ambient bearer never spends X API credits when the free path comes back empty. **Grok Bot exception.** On a Grok Bot host (`LAST30DAYS_HOST=grok-bot`) the unpinned chain is the official chain instead: xapi (`X_BEARER_TOKEN`) → xai (`XAI_API_KEY`) → xurl (the X API through X's CLI). When the bot fetched X itself (its built-in X tools, or the X connector), those results come first and the chain is not called at all; see [Grok Bot](#grok-bot) under Per-client patterns.**Grok CLI (opt-in backup).** Install the Grok CLI (`curl -fsSL https://x.ai/cli/install.sh | bash`) and run `grok login`, and X can work with no X account, no browser cookies, and no `XAI_API_KEY`. However, grok is **opt-in only**: a leftover `~/.grok/auth.json` must never steal the X lane. Pin `LAST30DAYS_X_BACKEND=grok` to enable it. It is not "free" in the way the cookie path is: calls draw on your Grok plan, and depth costs several calls per run because the underlying tool caps each search at 10 posts. Results are validated before use — every returned post's ID is decoded to confirm it falls inside the requested date range, because the retrieval is performed by a language model and can otherwise return confident, well-formed posts that were never searched for.@@ -479,15 +479,15 @@ The engine treats public jobs/careers postings as evidence of focus or priority### `--x-posts` flag-`--x-posts <path>` hands the engine an X result the hosting model fetched through its own X connector; it replaces the engine's X fetch for that run and works on any host. The value is a file path only (inline JSON exits `2`): a regular `.json` file in the `last30days-x-posts/1` shape, never read from inside the config dir or a credential store.+`--x-posts <path>` hands the engine an X result the hosting model fetched itself (on Grok Bot, through the X for Grok Bot connector or the bot's built-in X tools); it replaces the engine's X fetch for that run and works on any host. The value is a file path only (inline JSON exits `2`): a regular `.json` file in the `last30days-x-posts/1` shape, never read from inside the config dir or a credential store.| Field | Meaning || --- | --- |-| `schema`, `generated_at`, `topic`, `window {from, to}`, `provider`, `status` | Envelope header. `status` is `ok`, `partial`, or `error`; `error` is a short category (`credits`, `not-connected`, `unavailable`, `window-unsupported`), never raw tool output. `topic` must match the run topic and `generated_at` must be under 6 hours old, or the run fails closed with exit `2`. |-| `calls[]` | One entry per connector call: `lane` (`topic`, `from`, `mention`, `related`), `handles` (a subset of the run's `--x-handle` / `--x-related` handles), and `posts`. |+| `schema`, `generated_at`, `topic`, `window {from, to}`, `provider`, `status` | Envelope header. `status` is `ok`, `partial`, or `error`; `error` is a short category (`credits`, `not-connected`, `unavailable`, `window-unsupported`), never raw tool output. `topic` must match the run topic and `generated_at` must be under 6 hours old, or the run fails closed with exit `2`. `provider` `x-native` (Grok Bot's built-in X tools) makes the footer read "via Grok Bot X"; any other value reads "via X connector". |+| `calls[]` | One entry per query (merge a query's pages into one entry): `lane` (`topic`, `from`, `mention`, `related`), `handles` (a subset of the run's `--x-handle` / `--x-related` handles), and `posts`. || `posts[]` | Flat rows with exactly eight fields: `id`, `author_handle`, `created_at`, `text`, `likes`, `reposts`, `replies`, `quotes`. Any other key is ignored and counted. |-Limits: 8 MiB, strict UTF-8, at most 20 calls, 500 rows per call, 1,000 rows in total, 10,000 characters of text per row. Rows are rebuilt from validated parts: the citation is always `https://x.com/<handle>/status/<id>` (a row-supplied URL is never used), rows without an id or text, outside the window, or whose date disagrees with the id are dropped and counted, and an id sequence that looks generated rejects the whole file. The envelope is single-serve for the run. The hosted backend (`LAST30DAYS_API_BASE`) rejects the flag with exit `2`. Comparison runs take the per-entity `x_posts` field of `--competitors-plan` instead; a bare `--x-posts` on a comparison run exits `2`.+Limits: 8 MiB, strict UTF-8, at most 20 calls, 500 rows per call, 1,000 rows in total, 10,000 characters of text per row. Rows are rebuilt from validated parts: the citation is always `https://x.com/<handle>/status/<id>` (a row-supplied URL is never used), rows without an id or text, outside the window, or whose date disagrees with the id are dropped and counted, and an id sequence that looks generated rejects the whole file. The envelope is single-serve for the run, and its topic rows count against twice the per-stream limit (12 / 24 / 40 at quick / default / deep), the same budget as the engine's two X fetches. The hosted backend (`LAST30DAYS_API_BASE`) rejects the flag with exit `2`. Comparison runs take the per-entity `x_posts` field of `--competitors-plan` instead; a bare `--x-posts` on a comparison run exits `2`.```bashpython3 skills/last30days/scripts/last30days.py "<topic>" --x-posts /tmp/x-posts.json@@ -529,7 +529,7 @@ Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json| `LAST30DAYS_DOCTOR_PROBE_TIMEOUT` | Per-source deadline (**seconds**) for `doctor --probe` live checks. Defaults to `10`. Caps each concurrent probe so a slow source cannot hang the command. || `LAST30DAYS_HOST` | Host self-identification. `grok-bot` switches X to the official chain (xapi → xai → xurl) and turns off browser-session discovery; any other value, or unset, leaves every host exactly as today. Persisted to `.env` by first-run setup on Grok Bot and exported per invocation by the skill; doctor prints the resolved value. The engine never infers the host any other way. || `X_BEARER_TOKEN` | App-only bearer for the official X API v2 (`xapi`). First rung of the chain on Grok Bot; opt-in elsewhere via `LAST30DAYS_X_BACKEND=xapi`. Full-archive search is tried first, then recent search, so coverage is recent posts, about the last week, unless your X developer project has full-archive access (the outcome detail says `window truncated to 7 days` when the fallback ran, and `search stopped at the lane deadline; results may be incomplete` when the shared 150s lane budget cut a search short). Exhausted credits (HTTP 402) report as `payment-required`. Doctor checks presence only, never the network. Loaded from `.env`, Keychain, or `pass` like the other keys. |-| `LAST30DAYS_X_HOST_LANE` | `1` declares that the hosting model's X connector is in this session, so `--diagnose` and planning list `x` as available and the run expects `--x-posts`. Read from the process environment only: a `.env` line is ignored (doctor says so), so a removed connector never leaves a stale declaration. A run with the signal but no `--x-posts` records X as `error` ("connector result not passed"). |+| `LAST30DAYS_X_HOST_LANE` | `1` declares that the hosting model fetched X itself (on Grok Bot, through its built-in X tools or the X connector) and is passing the posts, so `--diagnose` and planning list `x` as available and the run expects `--x-posts`. Read from the process environment only: a `.env` line is ignored (doctor says so), so a stale declaration never outlives the session. Export it only when the host fetch returned posts. A run with the signal but no `--x-posts` records X as `error` ("connector result not passed"). || `LAST30DAYS_X_BACKEND` | Pins the X backend (`bird` / `xai` / `xurl` / `xquik` / `grok` / `xapi`); doctor renders the pin and predicts "will use" accordingly. The unpinned auto chain is bird → xai → xurl → xquik (grok and xapi are opt-in only). Pin `grok` to enable it; a leftover `~/.grok/auth.json` is never auto-selected. Pin `xapi` to use `X_BEARER_TOKEN` on an ordinary host. On a Grok Bot host the unpinned chain is the official chain (xapi → xai → xurl) and this pin is the only way to select a backend outside it; the pin keeps its exclusive, no-failover meaning there, and doctor names the pinned backend. || `AGENTCOOKIE` | `on` opts any host (incl. a MacBook) into the extra bird cookie lookups (agentcookie sidecar + live Chrome CDP); `off` disables the agentcookie sidecar reader. Unset uses host detection (Linux / Mac mini / Darwin sink get the extras). See "Extra bird cookie lookups" above. || `BROWSER_CONSENT` | Browser-cookie decision saved by setup: `true` permits consented browser discovery; `false` blocks native browser and CDP reads across later runs. Native extraction still requires `FROM_BROWSER`; CDP permits a prior explicit Chromium / `auto` selection when this marker is absent. `FROM_BROWSER=off` always blocks both readers. |@@ -721,9 +721,10 @@ Pass as `--competitors-plan @client/competitors-plan.json` (or as a string). SeeOn a Grok Bot host the bot exports `LAST30DAYS_HOST=grok-bot` on every engine call (first-run setup also persists it to `.env`), and X search runs through official channels only, in this order:-1. **X connector (primary).** Add the "X for Grok Bot" plugin and connect your X account in Grok Bot settings (it provisions an X developer account for you; paid Grok Bot plans include X API credits). When one of the plugin's post-search tools is in the session, the bot exports `LAST30DAYS_X_HOST_LANE=1`, fetches the posts itself, writes them to a `last30days-x-posts/1` file, and passes it with `--x-posts <path>` (see [`--x-posts` flag](#--x-posts-flag)). Connector calls draw on the credits included with Grok Bot and cover the full research window. `--diagnose` lists `x` as available whenever the lane signal is set; a run with the signal but no `--x-posts` file records X as `error` ("connector result not passed").-2. **`X_BEARER_TOKEN` (backup).** An app-only bearer from the X developer console, funded by your own X developer project. The engine tries full-archive search first and falls back to recent search, so coverage is recent posts, about the last week, unless your X developer project has full-archive access; the outcome detail says `window truncated to 7 days` when the fallback ran. Exhausted credits (HTTP 402) report as `payment-required`, which `LAST30DAYS_STRICT_EXIT` treats as degraded.-3. **`XAI_API_KEY` (backup).** xAI's licensed X search from console.x.ai: full window, topic search only (no from/mention handle lanes).+1. **Built-in X tools (primary).** Grok Bot's own X search (the `x` tools), available to every Grok Bot user with nothing to set up and no X API credits used. The bot fetches the posts itself (recency-sorted pages to the depth count, plus one relevance-sorted page for each of 10 equal slices of the window (5 on `--quick`) on the first query so busy topics still surface the month's most-engaged posts), writes them to a `last30days-x-posts/1` file with `"provider": "x-native"`, exports `LAST30DAYS_X_HOST_LANE=1`, and passes the file with `--x-posts <path>` (see [`--x-posts` flag](#--x-posts-flag)). The footer reads "via Grok Bot X".+2. **X connector.** When the built-in tools are missing or return nothing, the "X for Grok Bot" plugin (connect your X account in Grok Bot settings; it provisions an X developer account for you) serves the same file with `"provider": "x-connector"`, and the footer reads "via X connector". `--diagnose` lists `x` as available whenever the lane signal is set; a run with the signal but no `--x-posts` file records X as `error` ("connector result not passed"), so the bot exports the signal only when a fetch returned posts.+3. **`X_BEARER_TOKEN` (backup).** An app-only bearer from the X developer console, funded by your own X developer project. The engine tries full-archive search first and falls back to recent search, so coverage is recent posts, about the last week, unless your X developer project has full-archive access; the outcome detail says `window truncated to 7 days` when the fallback ran. Exhausted credits (HTTP 402) report as `payment-required`, which `LAST30DAYS_STRICT_EXIT` treats as degraded.+4. **`XAI_API_KEY` (backup).** xAI's licensed X search from console.x.ai: full window, topic search only (no from/mention handle lanes).Persist either key without echoing it:diff --git a/README.de.md b/README.de.mdindex 8fe3e063..000ba5d0 100644--- a/README.de.md+++ b/README.de.md@@ -203,7 +203,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-Mit `--trust` überspringst du die Installationsbestätigung. Aktualisieren kannst du mit `grok plugin update last30days`. Grok liest aus Kompatibilitätsgründen auch die Claude-Code-Manifeste; das native `.grok-plugin/`-Paar ist der bevorzugte Weg – und genau darauf verweist ein offizieller Eintrag im [xAI-Marketplace](https://github.com/xai-org/plugin-marketplace). `npx skills add` bleibt ein gültiger Fallback über alle Hosts hinweg. Auf Grok Bot läuft die X-Suche über den X-Connector des Bots, mit der offiziellen X-API (`X_BEARER_TOKEN`) als Fallback.+Mit `--trust` überspringst du die Installationsbestätigung. Aktualisieren kannst du mit `grok plugin update last30days`. Grok liest aus Kompatibilitätsgründen auch die Claude-Code-Manifeste; das native `.grok-plugin/`-Paar ist der bevorzugte Weg – und genau darauf verweist ein offizieller Eintrag im [xAI-Marketplace](https://github.com/xai-org/plugin-marketplace). `npx skills add` bleibt ein gültiger Fallback über alle Hosts hinweg. Auf Grok Bot funktioniert X sofort über die eingebauten X-Tools des Bots, danach über den X-Connector des Bots, mit der offiziellen X-API (`X_BEARER_TOKEN`) als Fallback.### Codex, Cursor, Copilot, Gemini CLI und weitere Agent-Skills-Hosts@@ -298,7 +298,7 @@ Diese Plattformen haben nichts miteinander zu tun. X weiß nicht, was Reddit den|---------|---------------|------|| Reddit (mit Kommentaren) + HN + Polymarket + GitHub + StockTwits | Nichts | Kostenlos || arXiv + Techmeme | Kostenlose CLIs, die das Erst-Setup automatisch installiert | Kostenlos |-| X / Twitter | `X_BEARER_TOKEN` für die offizielle X-API setzen (aktuelle Posts, etwa die letzte Woche, sofern dein X-Entwicklerprojekt keinen Vollarchiv-Zugang hat; Standard auf Grok Bot, anderswo per Opt-in mit `LAST30DAYS_X_BACKEND=xapi`), oder in einem beliebigen Browser bei x.com anmelden, oder `XQUIK_API_KEY` / `XAI_API_KEY` setzen | X-API-Guthaben stammt aus deinem X-Entwicklerprojekt; Browser-Cookies sind kostenlos; andere Schlüssel hängen vom Anbieter ab |+| X / Twitter | `X_BEARER_TOKEN` für die offizielle X-API setzen (aktuelle Posts, etwa die letzte Woche, sofern dein X-Entwicklerprojekt keinen Vollarchiv-Zugang hat; auf Grok Bot ein Fallback nach den eingebauten X-Tools des Bots, anderswo per Opt-in mit `LAST30DAYS_X_BACKEND=xapi`), oder in einem beliebigen Browser bei x.com anmelden, oder `XQUIK_API_KEY` / `XAI_API_KEY` setzen | X-API-Guthaben stammt aus deinem X-Entwicklerprojekt; Browser-Cookies sind kostenlos; andere Schlüssel hängen vom Anbieter ab || YouTube | `brew install yt-dlp` | Kostenlos || Bluesky | App-Passwort von bsky.app | Kostenlos || TikTok + Instagram + Threads + Pinterest + LinkedIn + YouTube-Kommentare | Ein ScrapeCreators-Schlüssel | 10.000 kostenlose Aufrufe, danach nutzungsabhängig |diff --git a/README.es.md b/README.es.mdindex a19abc70..06a8d5d9 100644--- a/README.es.md+++ b/README.es.md@@ -203,7 +203,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-Añade `--trust` para saltarte la confirmación de instalación. Actualiza con `grok plugin update last30days`. Grok también lee los manifiestos de Claude Code por compatibilidad; el par nativo `.grok-plugin/` es la vía principal, y es a lo que apunta una entrada oficial en el [marketplace de xAI](https://github.com/xai-org/plugin-marketplace). `npx skills add` sigue siendo una alternativa válida para cualquier host. En Grok Bot, la búsqueda en X pasa por el conector de X del bot, con la API oficial de X (`X_BEARER_TOKEN`) como respaldo.+Añade `--trust` para saltarte la confirmación de instalación. Actualiza con `grok plugin update last30days`. Grok también lee los manifiestos de Claude Code por compatibilidad; el par nativo `.grok-plugin/` es la vía principal, y es a lo que apunta una entrada oficial en el [marketplace de xAI](https://github.com/xai-org/plugin-marketplace). `npx skills add` sigue siendo una alternativa válida para cualquier host. En Grok Bot, X funciona sin configurar nada a través de las herramientas de X integradas del bot, luego el conector de X del bot, con la API oficial de X (`X_BEARER_TOKEN`) como respaldo.### Codex, Cursor, Copilot, Gemini CLI y otros hosts de Agent Skills@@ -298,7 +298,7 @@ Estas plataformas no tienen ninguna relación entre sí. X no sabe lo que piensa|---------|---------------|------|| Reddit (con comentarios) + HN + Polymarket + GitHub + StockTwits | Nada | Gratis || arXiv + Techmeme | CLI gratuitas, instaladas automáticamente por la configuración inicial | Gratis |-| X / Twitter | Define `X_BEARER_TOKEN` para la API oficial de X (posts recientes, aproximadamente la última semana, salvo que tu proyecto de desarrollador de X tenga acceso al archivo completo; es el valor por defecto en Grok Bot y opcional en otros hosts con `LAST30DAYS_X_BACKEND=xapi`), o inicia sesión en x.com en cualquier navegador, o define `XQUIK_API_KEY` / `XAI_API_KEY` | Los créditos de la API de X salen de tu proyecto de desarrollador de X; las cookies del navegador son gratis; las demás claves dependen del proveedor |+| X / Twitter | Define `X_BEARER_TOKEN` para la API oficial de X (posts recientes, aproximadamente la última semana, salvo que tu proyecto de desarrollador de X tenga acceso al archivo completo; es un respaldo en Grok Bot tras las herramientas de X integradas del bot y opcional en otros hosts con `LAST30DAYS_X_BACKEND=xapi`), o inicia sesión en x.com en cualquier navegador, o define `XQUIK_API_KEY` / `XAI_API_KEY` | Los créditos de la API de X salen de tu proyecto de desarrollador de X; las cookies del navegador son gratis; las demás claves dependen del proveedor || YouTube | `brew install yt-dlp` | Gratis || Bluesky | Una contraseña de aplicación de bsky.app | Gratis || TikTok + Instagram + Threads + Pinterest + LinkedIn + comentarios de YouTube | Una clave de ScrapeCreators | 10.000 llamadas gratis y luego pago por uso |diff --git a/README.fr.md b/README.fr.mdindex 8e9f4059..3c160293 100644--- a/README.fr.md+++ b/README.fr.md@@ -203,7 +203,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-Ajoutez `--trust` pour sauter la confirmation d'installation. Mettez à jour avec `grok plugin update last30days`. Grok lit aussi les manifestes Claude Code par compatibilité ; la paire native `.grok-plugin/` reste la voie principale, et c'est elle que pointe une entrée officielle dans la [marketplace xAI](https://github.com/xai-org/plugin-marketplace). `npx skills add` reste une solution de repli valable, tous hôtes confondus. Sur Grok Bot, la recherche X passe par le connecteur X du bot, avec l'API X officielle (`X_BEARER_TOKEN`) en secours.+Ajoutez `--trust` pour sauter la confirmation d'installation. Mettez à jour avec `grok plugin update last30days`. Grok lit aussi les manifestes Claude Code par compatibilité ; la paire native `.grok-plugin/` reste la voie principale, et c'est elle que pointe une entrée officielle dans la [marketplace xAI](https://github.com/xai-org/plugin-marketplace). `npx skills add` reste une solution de repli valable, tous hôtes confondus. Sur Grok Bot, X fonctionne sans configuration grâce aux outils X intégrés du bot, puis au connecteur X du bot, avec l'API X officielle (`X_BEARER_TOKEN`) en secours.### Codex, Cursor, Copilot, Gemini CLI et autres hôtes Agent Skills@@ -298,7 +298,7 @@ Ces plateformes n'ont aucune relation entre elles. X ignore ce que pense Reddit.|---------|---------------|------|| Reddit (avec les commentaires) + HN + Polymarket + GitHub + StockTwits | Rien | Gratuit || arXiv + Techmeme | Des CLI gratuites, installées automatiquement à la configuration initiale | Gratuit |-| X / Twitter | Définissez `X_BEARER_TOKEN` pour l'API X officielle (posts récents, environ la dernière semaine, sauf si votre projet développeur X dispose de l'accès aux archives complètes ; par défaut sur Grok Bot, en opt-in ailleurs avec `LAST30DAYS_X_BACKEND=xapi`), ou connectez-vous à x.com dans n'importe quel navigateur, ou définissez `XQUIK_API_KEY` / `XAI_API_KEY` | Les crédits de l'API X proviennent de votre projet développeur X ; les cookies de navigateur sont gratuits ; les autres clés dépendent du fournisseur |+| X / Twitter | Définissez `X_BEARER_TOKEN` pour l'API X officielle (posts récents, environ la dernière semaine, sauf si votre projet développeur X dispose de l'accès aux archives complètes ; en secours sur Grok Bot après les outils X intégrés du bot, en opt-in ailleurs avec `LAST30DAYS_X_BACKEND=xapi`), ou connectez-vous à x.com dans n'importe quel navigateur, ou définissez `XQUIK_API_KEY` / `XAI_API_KEY` | Les crédits de l'API X proviennent de votre projet développeur X ; les cookies de navigateur sont gratuits ; les autres clés dépendent du fournisseur || YouTube | `brew install yt-dlp` | Gratuit || Bluesky | Un mot de passe d'application depuis bsky.app | Gratuit || TikTok + Instagram + Threads + Pinterest + LinkedIn + commentaires YouTube | Une clé ScrapeCreators | 10 000 appels gratuits, puis paiement à l'usage |diff --git a/README.ja.md b/README.ja.mdindex ffdb73d5..9a2edb62 100644--- a/README.ja.md+++ b/README.ja.md@@ -203,7 +203,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-インストール時の確認を省きたい場合は `--trust` を付けてください。更新は `grok plugin update last30days` です。Grok は互換性のために Claude Code のマニフェストも読みますが、第一の経路はネイティブの `.grok-plugin/` のペアで、[xAI のマーケットプレイス](https://github.com/xai-org/plugin-marketplace)への公式掲載もこちらを指しています。`npx skills add` は、どのホストでも使える代替手段として引き続き有効です。Grok Bot では、X 検索はボットの X コネクタを通じて実行され、公式 X API(`X_BEARER_TOKEN`)がバックアップになります。+インストール時の確認を省きたい場合は `--trust` を付けてください。更新は `grok plugin update last30days` です。Grok は互換性のために Claude Code のマニフェストも読みますが、第一の経路はネイティブの `.grok-plugin/` のペアで、[xAI のマーケットプレイス](https://github.com/xai-org/plugin-marketplace)への公式掲載もこちらを指しています。`npx skills add` は、どのホストでも使える代替手段として引き続き有効です。Grok Bot では、X は設定不要でボットの組み込み X ツールを通じて動作し、次にボットの X コネクタ、公式 X API(`X_BEARER_TOKEN`)がバックアップになります。### Codex、Cursor、Copilot、Gemini CLI、その他の Agent Skills ホスト@@ -297,7 +297,7 @@ Reddit(コメント込み)、Hacker News、Polymarket、GitHub はすぐに使|---------|---------------|------|| Reddit(コメント込み)+ HN + Polymarket + GitHub + StockTwits | 不要 | 無料 || arXiv + Techmeme | 無料のCLI。初回セットアップが自動でインストールします | 無料 |-| X / Twitter | 公式 X API 用に `X_BEARER_TOKEN` を設定(最近の投稿、およそ直近 1 週間分。X 開発者プロジェクトにフルアーカイブ検索のアクセスがある場合を除く。Grok Bot では既定、それ以外のホストでは `LAST30DAYS_X_BACKEND=xapi` でオプトイン)するか、任意のブラウザで x.com にログインするか、`XQUIK_API_KEY` / `XAI_API_KEY` を設定 | X API のクレジットはご自身の X 開発者プロジェクトから消費。ブラウザのクッキーは無料。その他のキーの料金は提供元によります |+| X / Twitter | 公式 X API 用に `X_BEARER_TOKEN` を設定(最近の投稿、およそ直近 1 週間分。X 開発者プロジェクトにフルアーカイブ検索のアクセスがある場合を除く。Grok Bot ではボットの組み込み X ツールの次のバックアップ、それ以外のホストでは `LAST30DAYS_X_BACKEND=xapi` でオプトイン)するか、任意のブラウザで x.com にログインするか、`XQUIK_API_KEY` / `XAI_API_KEY` を設定 | X API のクレジットはご自身の X 開発者プロジェクトから消費。ブラウザのクッキーは無料。その他のキーの料金は提供元によります || YouTube | `brew install yt-dlp` | 無料 || Bluesky | bsky.app のアプリパスワード | 無料 || TikTok + Instagram + Threads + Pinterest + LinkedIn + YouTube のコメント | ScrapeCreators のキー | 1万リクエストまで無料、以降は従量課金 |diff --git a/README.md b/README.mdindex 68b566b9..07ffbea2 100644--- a/README.md+++ b/README.md@@ -203,7 +203,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-Add `--trust` to skip the install confirmation. Update with `grok plugin update last30days`. Grok also reads the Claude Code manifests for compatibility; the native `.grok-plugin/` pair is the first-class lane (and what an official [xAI marketplace](https://github.com/xai-org/plugin-marketplace) listing points at). `npx skills add` remains a valid cross-host fallback. On Grok Bot, X search runs through the bot's X connector, with the official X API (`X_BEARER_TOKEN`) as backup.+Add `--trust` to skip the install confirmation. Update with `grok plugin update last30days`. Grok also reads the Claude Code manifests for compatibility; the native `.grok-plugin/` pair is the first-class lane (and what an official [xAI marketplace](https://github.com/xai-org/plugin-marketplace) listing points at). `npx skills add` remains a valid cross-host fallback. On Grok Bot, X works out of the box through the bot's built-in X tools, then the bot's X connector, with the official X API (`X_BEARER_TOKEN`) as backup.### Codex, Cursor, Copilot, Gemini CLI, and other Agent Skills hosts@@ -297,7 +297,7 @@ These platforms don't have relationships with each other. X doesn't know what Re|---------|---------------|------|| Reddit (with comments) + HN + Polymarket + GitHub + StockTwits | Nothing | Free || arXiv + Techmeme | Free CLIs, auto-installed by first-run setup | Free |-| X / Twitter | Set `X_BEARER_TOKEN` for the official X API (recent posts, about the last week, unless your X developer project has full-archive access; the default on Grok Bot, opt-in elsewhere with `LAST30DAYS_X_BACKEND=xapi`), or log into x.com in any browser, or set `XQUIK_API_KEY` / `XAI_API_KEY` | X API credits come from your X developer project; browser cookies are free; other keys are provider-specific |+| X / Twitter | Set `X_BEARER_TOKEN` for the official X API (recent posts, about the last week, unless your X developer project has full-archive access; a backup on Grok Bot after the bot's built-in X tools, opt-in elsewhere with `LAST30DAYS_X_BACKEND=xapi`), or log into x.com in any browser, or set `XQUIK_API_KEY` / `XAI_API_KEY` | X API credits come from your X developer project; browser cookies are free; other keys are provider-specific || YouTube | `brew install yt-dlp` | Free || Bluesky | App password from bsky.app | Free || TikTok + Instagram + Threads + Pinterest + LinkedIn + YouTube comments | ScrapeCreators key | 10,000 free calls, then PAYG |diff --git a/README.pt-BR.md b/README.pt-BR.mdindex 6387eeeb..9c67c01d 100644--- a/README.pt-BR.md+++ b/README.pt-BR.md@@ -203,7 +203,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-Acrescente `--trust` para pular a confirmação de instalação. Atualize com `grok plugin update last30days`. O Grok também lê os manifestos do Claude Code por compatibilidade; o par nativo `.grok-plugin/` é o caminho principal — e é para ele que aponta um registro oficial no [marketplace da xAI](https://github.com/xai-org/plugin-marketplace). O `npx skills add` continua sendo uma alternativa válida em qualquer host. No Grok Bot, a busca no X passa pelo conector de X do bot, com a API oficial do X (`X_BEARER_TOKEN`) como reserva.+Acrescente `--trust` para pular a confirmação de instalação. Atualize com `grok plugin update last30days`. O Grok também lê os manifestos do Claude Code por compatibilidade; o par nativo `.grok-plugin/` é o caminho principal — e é para ele que aponta um registro oficial no [marketplace da xAI](https://github.com/xai-org/plugin-marketplace). O `npx skills add` continua sendo uma alternativa válida em qualquer host. No Grok Bot, o X funciona sem configuração pelas ferramentas de X integradas do bot, depois pelo conector de X do bot, com a API oficial do X (`X_BEARER_TOKEN`) como reserva.### Codex, Cursor, Copilot, Gemini CLI e outros hosts do Agent Skills@@ -298,7 +298,7 @@ Essas plataformas não têm relação nenhuma entre si. O X não sabe o que o Re|---------|---------------|------|| Reddit (com comentários) + HN + Polymarket + GitHub + StockTwits | Nada | De graça || arXiv + Techmeme | CLIs gratuitas, instaladas automaticamente pela configuração inicial | De graça |-| X / Twitter | Defina `X_BEARER_TOKEN` para a API oficial do X (posts recentes, cerca da última semana, a menos que seu projeto de desenvolvedor do X tenha acesso ao arquivo completo; é o padrão no Grok Bot e opcional em outros hosts com `LAST30DAYS_X_BACKEND=xapi`), ou faça login em x.com em qualquer navegador, ou defina `XQUIK_API_KEY` / `XAI_API_KEY` | Os créditos da API do X vêm do seu projeto de desenvolvedor do X; os cookies do navegador são gratuitos; as demais chaves dependem do provedor |+| X / Twitter | Defina `X_BEARER_TOKEN` para a API oficial do X (posts recentes, cerca da última semana, a menos que seu projeto de desenvolvedor do X tenha acesso ao arquivo completo; é uma reserva no Grok Bot depois das ferramentas de X integradas do bot e opcional em outros hosts com `LAST30DAYS_X_BACKEND=xapi`), ou faça login em x.com em qualquer navegador, ou defina `XQUIK_API_KEY` / `XAI_API_KEY` | Os créditos da API do X vêm do seu projeto de desenvolvedor do X; os cookies do navegador são gratuitos; as demais chaves dependem do provedor || YouTube | `brew install yt-dlp` | De graça || Bluesky | Uma senha de aplicativo do bsky.app | De graça || TikTok + Instagram + Threads + Pinterest + LinkedIn + comentários do YouTube | Uma chave do ScrapeCreators | 10.000 chamadas gratuitas e depois pagamento por uso |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex acf2c3e6..199e34a1 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -206,7 +206,7 @@ grok plugin marketplace add mvanhorn/last30days-skillgrok plugin install last30days```-加入 `--trust` 可跳过安装确认;使用 `grok plugin update last30days` 更新。为兼容旧机制,Grok 也会读取 Claude Code 的清单文件;原生 `.grok-plugin/` 文件是首选通路,也是 [xAI marketplace](https://github.com/xai-org/plugin-marketplace) 官方目录条目指向的对象。`npx skills add` 仍是有效的跨宿主备用方案。在 Grok Bot 上,X 搜索通过机器人的 X 连接器执行,并以官方 X API(`X_BEARER_TOKEN`)作为备用。+加入 `--trust` 可跳过安装确认;使用 `grok plugin update last30days` 更新。为兼容旧机制,Grok 也会读取 Claude Code 的清单文件;原生 `.grok-plugin/` 文件是首选通路,也是 [xAI marketplace](https://github.com/xai-org/plugin-marketplace) 官方目录条目指向的对象。`npx skills add` 仍是有效的跨宿主备用方案。在 Grok Bot 上,X 无需任何设置即可通过机器人内置的 X 工具使用,其次是机器人的 X 连接器,并以官方 X API(`X_BEARER_TOKEN`)作为备用。### Codex、Cursor、Copilot、Gemini CLI 与其他 Agent Skills 宿主@@ -296,7 +296,7 @@ Reddit(含评论)、Hacker News、Polymarket 和 GitHub 无需任何配置|------|----------------|------|| Reddit(含评论)+ HN + Polymarket + GitHub + StockTwits | 无 | 免费 || arXiv + Techmeme | 免费 CLI,由首次配置自动安装 | 免费 |-| X / Twitter | 设置 `X_BEARER_TOKEN` 使用官方 X API(近期帖子,大约最近一周;除非你的 X 开发者项目拥有完整归档访问权限。Grok Bot 上为默认方式,其他宿主需通过 `LAST30DAYS_X_BACKEND=xapi` 选择启用),或在任意浏览器中登录 x.com,或设置 `XQUIK_API_KEY` / `XAI_API_KEY` | X API 额度来自你自己的 X 开发者项目;浏览器 Cookie 免费;其他密钥费用取决于服务商 |+| X / Twitter | 设置 `X_BEARER_TOKEN` 使用官方 X API(近期帖子,大约最近一周;除非你的 X 开发者项目拥有完整归档访问权限。Grok Bot 上作为机器人内置 X 工具之后的备用方式,其他宿主需通过 `LAST30DAYS_X_BACKEND=xapi` 选择启用),或在任意浏览器中登录 x.com,或设置 `XQUIK_API_KEY` / `XAI_API_KEY` | X API 额度来自你自己的 X 开发者项目;浏览器 Cookie 免费;其他密钥费用取决于服务商 || YouTube | `brew install yt-dlp` | 免费 || Bluesky | 来自 bsky.app 的应用密码 | 免费 || TikTok + Instagram + Threads + Pinterest + LinkedIn + YouTube 评论 | ScrapeCreators 密钥 | 前 10,000 次调用免费,之后按量付费 |diff --git a/changelog.d/+grok-bot-native-x.changed.md b/changelog.d/+grok-bot-native-x.changed.mdnew file mode 100644index 00000000..cd82c2e3--- /dev/null+++ b/changelog.d/+grok-bot-native-x.changed.md@@ -0,0 +1 @@+On Grok Bot, X now works out of the box: the bot fetches X through its built-in X tools first, with no plugin, key, or X API credits needed, then falls back to the X for Grok Bot connector and the official X API keys. Busy topics also get a popular pass, one relevance-sorted page for each of 10 equal slices of the window (5 on `--quick`), so the month's most-engaged posts surface, and the footer reads "via Grok Bot X". Host-fetched X results (`--x-posts`) can now fill the same topic budget as the engine's own two X fetches (24 posts at default depth, up from 12).diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 21bbbf4f..45b2aed1 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -106,7 +106,7 @@ Paths resolve relative to `SKILL_DIR`. A mode selected while reading a reference| `--agent` mode or explicit machine-readable JSON | Read [references/agent-mode.md](references/agent-mode.md) in full. | Apply structured output without treating absent consent as permission. || Recommendation intent | Read [references/recommendations.md](references/recommendations.md) in full. | Rank and render the recommended items before the footer/invitation. || Identifiable product requires category peers | Read [references/category-peers.md](references/category-peers.md) in full. | Expand peers during Step 0.55 before planning. |-| Grok Bot official X connector lane | Read [references/grok-bot-x.md](references/grok-bot-x.md) in full. | Fetch and validate the X envelope before the research engine command. |+| Grok Bot X lane | Read [references/grok-bot-x.md](references/grok-bot-x.md) in full. | Fetch and validate the X envelope before the research engine command. || Follow-up on existing research | Read [references/followups.md](references/followups.md) in full. | Answer or re-render existing research; use the explicit cached drill/freshness/queue routes when requested. || HTML/export intent | Read [references/save-html-brief.md](references/save-html-brief.md) in full. | Create the local artifact, then follow its access and explicit publishing choices. |@@ -122,7 +122,7 @@ For fresh research or discovery, resolve whether the agent session has a usable- When host web search is available, use it for applicable pre-research and supplements. Export `LAST30DAYS_NATIVE_SEARCH=1` in the same shell as the engine.- When no host web search is available, leave that signal unset. Skip Steps 0.55 and 0.75, and add `--auto-resolve`; the engine uses configured backends or its keyless floor.-**GROK BOT HOST RULE (every invocation, including `SETUP_COMPLETE=true`).** On an actual Grok Bot host, export `LAST30DAYS_HOST=grok-bot` in every engine shell. Do not infer this host from `CURSOR_AGENT` alone; Cursor also sets it. When the session exposes the official X connector's post-search tools (the "X for Grok Bot" plugin), export `LAST30DAYS_X_HOST_LANE=1` and load the connector reference through the gate above. Use its `--x-posts` envelope. Never read a browser session on a Grok Bot. Never place post text unquoted in a shell command; write envelopes only with a single-quoted heredoc delimiter or tool file output. First-run Grok Bot uses the Grok Bot Prose Flow; Cursor uses the Non-Modal Prose Flow.+**GROK BOT HOST RULE (every invocation, including `SETUP_COMPLETE=true`).** On an actual Grok Bot host, export `LAST30DAYS_HOST=grok-bot` in every engine shell. Do not infer this host from `CURSOR_AGENT` alone; Cursor also sets it. Load the Grok Bot X lane reference through the gate above and fetch X yourself first: the built-in X tools (namespace `x`), else the "X for Grok Bot" plugin. Export `LAST30DAYS_X_HOST_LANE=1` with its `--x-posts` envelope only when posts came back. Never read a browser session on a Grok Bot. Never place post text unquoted in a shell command; write envelopes only with a single-quoted heredoc delimiter or tool file output. First-run Grok Bot uses the Grok Bot Prose Flow; Cursor uses the Non-Modal Prose Flow.**FIRST-RUN GATE — after resolving host web search, before topic research:**diff --git a/skills/last30days/references/grok-bot-x.md b/skills/last30days/references/grok-bot-x.mdindex 1fff4cdf..cdcddaaf 100644--- a/skills/last30days/references/grok-bot-x.md+++ b/skills/last30days/references/grok-bot-x.md@@ -1,16 +1,23 @@-# Grok Bot official X connector+# Grok Bot X lanes-Read only for an actual Grok Bot host with the official X connector lane active. Browser sessions are never read on this host.+Read only on an actual Grok Bot host. Browser sessions are never read on this host.-**Grok Bot X connector recipe (only when `LAST30DAYS_X_HOST_LANE=1` is exported - see the GROK BOT HOST RULE in the root SKILL.md).** On a Grok Bot with the X connector, YOU fetch X through the connector before the engine command and hand the engine the file; the engine then calls no X backend, plans `x` in, and the footer's X provenance reads "X via X connector". Do this before the research runbook's Step 1 command.+**Grok Bot X recipe (see the GROK BOT HOST RULE in the root SKILL.md).** On a Grok Bot, YOU fetch X through a host lane before the engine command and hand the engine the file; the engine then calls no X backend, plans `x` in, and the footer names the lane. Do this before the research runbook's Step 1 command.-1. **Calls (the connector's post-search tool, e.g. `search_posts_all`).** Window = the engine's date range (`--days`, default 30: `from` is today minus the day count, `to` is today). Depth count = 10 (`--quick`) / 30 (default) / 60 (`--deep`).- - One `topic` call: the topic query plus `-is:retweet`, the window, and the depth count.- - Per `--x-handle` handle: one `from` call (`from:<handle> -is:retweet`, 8 posts) and one `mention` call (`@<handle> -is:retweet`, 5 posts).- - Per `--x-related` handle: one `related` call (`from:<handle> -is:retweet`, 3 posts).- - If the tool rejects the window or count parameters, omit them, keep at most the depth count per call, and write `"status": "partial"` with `"error": "window-unsupported"`.- - If the connector itself fails, write `"status": "error"` with `"calls": []` and a short category in `error`: `credits`, `not-connected`, or `unavailable` - never raw tool output, never an account or app id.-2. **Envelope.** Exactly these top-level fields; every post carries the eight flat fields and nothing else (no URLs, media, or author objects); at most the depth count per call. A fresh `generated_at` (the engine rejects an envelope older than 6 hours) and a `topic` identical to the engine's topic string:+0. **Lanes, in order.** Two host lanes write the same envelope. Both expose a post-search tool named `search_posts_all`, so tell them apart by where the tool comes from, never by its name:+ 1. Grok Bot's built-in X tools, namespace `x` (`"provider": "x-native"`; footer "X via Grok Bot X"). Free, nothing to set up.+ 2. The "X for Grok Bot" connector plugin's tools (`"provider": "x-connector"`; footer "X via X connector").++ Use the first lane present in the session that returns posts. If a lane errors or returns nothing, try the next one. Export `LAST30DAYS_X_HOST_LANE=1` and pass `--x-posts` only when a lane returned posts. When no lane did, run `unset LAST30DAYS_X_HOST_LANE` and the Step 1 command without `--x-posts`, so the engine's own X chain (`X_BEARER_TOKEN`, then `XAI_API_KEY`) can still run.+1. **Calls.** Window = the engine's date range (`--days`, default 30: `from` is today minus the day count, `to` is today). Depth count per query = 10 (`--quick`) / 30 (default) / 60 (`--deep`).+ - **Topic.** One `topic` call per planned X query, at most 2: the topic itself, plus the second X subquery's search text when the plan has one. Build each query from the raw topic: multi-word topics go unquoted (every word must match), phrase-quote only proper names, and add `-is:retweet`. If fewer than half the posts on the first page mention the topic's main word, retry that query once with its two or three core words.+ - **Built-in `x` tools.** Pass `sort_order` `recency` (relevancy order skips high-engagement posts; the engine ranks by engagement itself), `start_time` / `end_time` for the window (`end_time` a minute before now), and `max_results` 25 (the tool's minimum is 10; ask for at least 10 and keep only the count you need). Follow `next_token` until the depth count is reached or no token comes back. Then run the **popular pass** for the first topic query only: split the window into 10 equal slices (5 on `--quick`; about 3 days each for the default 30) and fetch one page per slice with `sort_order` `relevancy` and that slice's `start_time` / `end_time`, so a busy topic still surfaces the month's most-engaged posts instead of only its last few minutes. Merge every page of one query, recency and popular, into ONE envelope call; pages can overlap, so keep the first copy of each id. The popular pages do not count toward the depth count. Request `post.fields=created_at,public_metrics,author_id,note_tweet`, `expansions=author_id`, and `user.fields=username`. Map `public_metrics` `like_count` / `retweet_count` / `reply_count` / `quote_count` to `likes` / `reposts` / `replies` / `quotes`, the expanded user's `username` to `author_handle`, and use `note_tweet.text` as `text` when present.+ - **Connector tools.** Pass the window and the depth count on each call.+ - **Named handles.** Per `--x-handle` handle: one `from` call (`from:<handle> -is:retweet`, 8 posts) and one `mention` call (`@<handle> -is:retweet`, 5 posts). Per `--x-related` handle the user gave: one `related` call (`from:<handle> -is:retweet`, 3 posts).+ - **Discovered authors.** From every topic post fetched (all pages, before trimming to the depth count), take up to 3 authors (not already an `--x-handle`) with at least 2 posts that are about the topic, most posts first. For each, one `from` call (`from:<handle>` plus the topic's core words, `-is:retweet`, 8 posts) and one `mention` call (`@<handle>` plus the topic's core words, `-is:retweet`, 5 posts), and add the handle to `--x-related`.+ - If the tool rejects the window or count parameters, omit them, keep at most the depth count per query, and write `"status": "partial"` with `"error": "window-unsupported"`.+ - If a lane fails before returning any posts, move to the next lane (step 0). If posts came back and a later call failed, write `"status": "partial"` with a short category in `error`: `credits`, `not-connected`, or `unavailable` - never raw tool output, never an account or app id.+2. **Envelope.** Exactly these top-level fields; every post carries the eight flat fields and nothing else (no URLs, media, or author objects); at most the depth count per query plus its popular pages. Keep the envelope inside the engine's limits or it is rejected: at most 500 posts per call, 1,000 posts and 20 calls in total. When a budget would be exceeded, drop discovered-author calls first, then popular pages; keep the recency pages and the user's own `--x-handle` / `--x-related` calls. A fresh `generated_at` (the engine rejects an envelope older than 6 hours), a `topic` identical to the engine's topic string, and the `provider` of the lane that served it:```json{@@ -18,7 +25,7 @@ Read only for an actual Grok Bot host with the official X connector lane active."generated_at": "{ISO_8601_UTC_NOW}","topic": "{TOPIC}","window": {"from": "{YYYY-MM-DD}", "to": "{YYYY-MM-DD}"},- "provider": "x-connector",+ "provider": "x-native","status": "ok","calls": [{"lane": "topic", "handles": [], "posts": [@@ -31,7 +38,7 @@ Read only for an actual Grok Bot host with the official X connector lane active.}```- Omit the `from` / `mention` / `related` calls when the run has no `--x-handle` / `--x-related`; `handles` must be the run's own handles. `id` is the post's numeric id as a string; `author_handle` is the username without `@`.+ Omit the `from` / `mention` / `related` calls when the run has no handles for them; `handles` must be the run's own `--x-handle` / `--x-related` handles, including discovered authors. `id` is the post's numeric id as a string; `author_handle` is the username without `@`.3. **Write the file - post text is attacker-controlled and never goes unquoted into a shell command.** Use the tool's own file output when it has one; otherwise a single-quoted heredoc (never unquoted) into a `.json` path outside `~/.config`, in the SAME Bash call as the engine command (the trap removes it on exit). Two rules keep a post from closing the heredoc early: emit the envelope as ONE line of compact JSON (newlines inside post text stay escaped as `\n`; never pretty-print), and replace `{X_POSTS_NONCE}` in BOTH sentinel lines with 12 random letters and digits you generate fresh for this run, so no post text can equal the closing line:```bash@@ -44,5 +51,5 @@ X_POSTS_EOF_{X_POSTS_NONCE}```For a comparison, create `X_POSTS_DIR` and its cleanup trap once. Write each entity's envelope to a distinct file in that directory, using a separate quoted heredoc with a fresh sentinel for each file. Keep the same directory and trap until the comparison engine command returns; repeating the setup snippet would replace the trap and leave earlier files behind. Run it directly in your shell tool, never wrapped in `bash -lc '...'` (same rule as the plan tmpfile).-4. **Engine.** Add `--x-posts "$X_POSTS_FILE"` to the Step 1 command (the file path only, never inline JSON); every other flag stays as usual. Comparison runs: write one envelope per entity (its `topic` is that entity's name) and put the path in that entity's `--competitors-plan` entry as `"x_posts": "/abs/path/x-posts.json"`; a bare `--x-posts` on a comparison run exits 2. If an envelope includes handle lanes, also put its `x_handle` and `x_related` in that entry; for the main entity, pass the same targeting as outer flags as shown in `comparison.md`. If the engine exits 2 naming an envelope, fix that file or remove that entity's `x_posts` plan entry before retrying; X is then absent for that entity. For an ordinary run, remove `--x-posts` before retrying without the envelope.-5. **After the run.** The stats line reads "X via X connector". The engine's one receipt line (accepted / dropped counts, on stderr) is diagnostics only: never narrate it in the deliverable (LAW 9).+4. **Engine.** Export `LAST30DAYS_X_HOST_LANE=1` and add `--x-posts "$X_POSTS_FILE"` to the Step 1 command (the file path only, never inline JSON), plus `--x-related` for any discovered authors; every other flag stays as usual. Comparison runs: fetch entities one after another and pace the whole comparison so no minute holds more than 30 tool calls (wait before a call that would exceed it); run the popular pass for the main entity only. The lane signal covers every entity, so use envelopes only when every entity's fetch returned posts; otherwise unset the lane and run the comparison without envelopes, so each entity's engine X chain still runs. With posts for all of them, write one envelope per entity (its `topic` is that entity's name) and put the path in that entity's `--competitors-plan` entry as `"x_posts": "/abs/path/x-posts.json"`; a bare `--x-posts` on a comparison run exits 2. If an envelope includes handle lanes, also put its `x_handle` and `x_related` in that entry; for the main entity, pass the same targeting as outer flags as shown in `comparison.md`. If the engine exits 2 naming an envelope, fix that file or remove that entity's `x_posts` plan entry before retrying; X is then absent for that entity. For an ordinary run, remove `--x-posts` and unset the lane before retrying without the envelope.+5. **After the run.** The stats line reads "X via X connector" or "X via Grok Bot X". The engine's one receipt line (accepted / dropped counts, on stderr) is diagnostics only: never narrate it in the deliverable (LAW 9).diff --git a/skills/last30days/references/research-runbook.md b/skills/last30days/references/research-runbook.mdindex edeb9965..069c5ea7 100644--- a/skills/last30days/references/research-runbook.md+++ b/skills/last30days/references/research-runbook.md@@ -582,7 +582,7 @@ Store your plan as `QUERY_PLAN_JSON` - you'll pass it to the script in the next----**Grok Bot connector:** when the official X connector lane is active, follow the root routing gate for `grok-bot-x.md` before the engine command.+**Grok Bot X:** on a Grok Bot host, follow the root routing gate for `grok-bot-x.md` before the engine command.**Step 1: Run the research script WITH your query plan (FOREGROUND)**diff --git a/skills/last30days/references/setup-wizard.md b/skills/last30days/references/setup-wizard.mdindex 647c3f82..7a265d3e 100644--- a/skills/last30days/references/setup-wizard.md+++ b/skills/last30days/references/setup-wizard.md@@ -26,7 +26,7 @@ Carry out only the authorized repair. Reading this guide or a doctor prescriptio**Platform split - run exactly ONE branch:**- **If you HAVE WebSearch and AskUserQuestion (Claude Code):** run the **Claude Code Modal Flow** immediately below.- **If you do NOT (OpenClaw, Codex, Cursor, Gemini CLI, raw CLI):** run the **Non-Modal Prose Flow** further down. It does the same work conversationally, without modals.-- **If you are running as a Grok Bot** (the GROK BOT HOST RULE in the root SKILL.md): run the **Grok Bot Prose Flow**, the third branch, below the Non-Modal flow. The X connector comes first, any backup key is written only through the engine, and no browser session is read. Cursor stays in the Non-Modal Prose Flow.+- **If you are running as a Grok Bot** (the GROK BOT HOST RULE in the root SKILL.md): run the **Grok Bot Prose Flow**, the third branch, below the Non-Modal flow. The bot's own X tools come first, any backup key is written only through the engine, and no browser session is read. Cursor stays in the Non-Modal Prose Flow.---@@ -154,15 +154,15 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI### Grok Bot Prose Flow-For a Grok Bot host. The GROK BOT HOST RULE in the root SKILL.md applies throughout: `LAST30DAYS_HOST=grok-bot` is exported in every shell that runs the engine, including every command below. Same conversational shape as the Non-Modal Prose Flow, no modals, and the X connector comes first: on this host the engine never reads a browser session and X runs only through official access. Run in order; wait where it says to wait.+For a Grok Bot host. The GROK BOT HOST RULE in the root SKILL.md applies throughout: `LAST30DAYS_HOST=grok-bot` is exported in every shell that runs the engine, including every command below. Same conversational shape as the Non-Modal Prose Flow, no modals, and the bot's own X tools come first: on this host the engine never reads a browser session and X runs only through official access. Run in order; wait where it says to wait.**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. 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.+**2. X tools (primary - check this BEFORE offering any key).** Look for an X post-search tool in this session, for example `search_posts_all`: first Grok Bot's built-in X tools (namespace `x`), then the "X for Grok Bot" plugin's tools. Any tool that searches posts by query counts; tell the two apart by where the tool comes from, never by its name.+ - **Present** → tell the user: `X is ready - it runs through Grok Bot's own X access with full 30-day coverage, nothing to configure.` On every research run follow the Grok Bot X recipe in Research Execution, and export `LAST30DAYS_X_HOST_LANE=1` next to `LAST30DAYS_HOST=grok-bot` only in an engine shell whose fetch returned posts: 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.-**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)`+**3. Backup key (only when neither is present).** Say, then WAIT: `This session has no X search tools, 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@@ -178,7 +178,7 @@ For a Grok Bot host. The GROK BOT HOST RULE in the root SKILL.md applies through**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).-**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.+**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 `LAST30DAYS_X_HOST_LANE=1` exported when the X fetch returned posts). Setup stdout is what this run installed, not the runtime source list; the engine diagnostic at research confirmation is authoritative.---@@ -196,7 +196,7 @@ The magic of /last30days is Reddit comments + X posts together - and both are fr- `XQUIK_API_KEY=xxx` - keyless-style X via Xquik.- `AUTH_TOKEN=xxx` + `CT0=xxx` - paste your X cookies manually (x.com → F12 → Application → Cookies).-**X on a Grok Bot (repair).** On a `LAST30DAYS_HOST=grok-bot` host X runs only through official access, so if X returns nothing there: add the "X for Grok Bot" plugin and connect X inside Grok Bot (the X connector lane; full 30-day coverage on the included credits), or add `X_BEARER_TOKEN` (recent posts, about the last week, unless your X developer project has full-archive access) or `XAI_API_KEY` from console.x.ai through `setup --store-key <NAME>`, or, when the footer reports X API credits exhausted (`payment-required`), top up credits in the X developer console. Nothing in the Linux / Mac mini repair section below applies on a Grok Bot.+**X on a Grok Bot (repair).** On a `LAST30DAYS_HOST=grok-bot` host X runs only through official access, so if X returns nothing there: confirm Grok Bot's built-in X tools (namespace `x`) are in the session and the fetch ran before the engine command; otherwise add the "X for Grok Bot" plugin and connect X inside Grok Bot (the X connector lane), or add `X_BEARER_TOKEN` (recent posts, about the last week, unless your X developer project has full-archive access) or `XAI_API_KEY` from console.x.ai through `setup --store-key <NAME>`, or, when the footer reports X API credits exhausted (`payment-required`), top up credits in the X developer console. Nothing in the Linux / Mac mini repair section below applies on a Grok Bot.**X on Linux / Mac mini (repair).** These hosts (never a `LAST30DAYS_HOST=grok-bot` host) can't decrypt a local Chrome cookie store, so if X returns nothing there, feed bird a cookie pair one of these ways (a MacBook does NOT do any of this — it uses its Keychain / Firefox / Safari extract; do not launch box-chrome on a MacBook):- **agentcookie sidecar:** install the `agentcookie` CLI so the engine can read your `auth_token`/`ct0` from it automatically. Nothing to configure; `AGENTCOOKIE=off` disables it.diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pyindex 1a0a3d69..928ce0a6 100644--- a/skills/last30days/scripts/lib/doctor.py+++ b/skills/last30days/scripts/lib/doctor.py@@ -429,8 +429,8 @@ def _reddit_record(config):# Official-path wording. The bearer path is never described as# parity with the connector lane.X_BEARER_CAVEAT = x_api.BEARER_COVERAGE_NOTE-X_CONNECTOR_NOTE = "will use: X connector (host-fetched at run time)"-X_CONNECTOR_ARMED = "X connector lane armed"+X_CONNECTOR_NOTE = "will use: built-in X tools or X connector (host-fetched at run time)"+X_CONNECTOR_ARMED = "host X lane armed (built-in X tools or X connector)"def _x_will_use_note(record: Dict[str, Any], policy: env.XPolicy) -> str:@@ -1109,7 +1109,7 @@ def _x_auth_path(config: Dict[str, Any]) -> Dict[str, Any]:note = "explicit backend pin"else:note = (- "no official X path armed (add the X for Grok Bot plugin and connect X in Grok Bot settings, or set "+ "no official X path armed (use Grok Bot's built-in X tools or add the X for Grok Bot plugin, or set ""X_BEARER_TOKEN or XAI_API_KEY)")return {"name": "X auth path", "armed": bool(source), "note": note}diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex f341c349..8d6505b8 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -2431,8 +2431,8 @@ def run(bundle = schema.RetrievalBundle(artifacts={"grounding": []})if envelope is not None:- # The footer's X provenance reads "via X connector" (render._render_stats).- bundle.artifacts["x_provenance"] = "connector"+ # The footer names the X provenance (render._render_stats).+ bundle.artifacts["x_provenance"] = envelope.provenance# Handles the user named explicitly. Available before any retrieval, unlike# the entity-extracted set, so Phase 1 and quick-depth runs get first-party# protection too. Without this the exemption reached only the Phase 2@@ -2806,9 +2806,15 @@ def run(# Jobs is exempt from per_stream_limit: a careers board is a complete# snapshot of open roles, and truncating it to the default 12 drops# strategic postings (the whole point of hiring-signals coverage).+ # A host-fetched envelope serves every topic row to the first X+ # stream, so that one stream carries what the backend's X streams+ # together would have (per_stream_limit x the X fetch cap).if source != "jobs":+ stream_limit = settings["per_stream_limit"]+ if source == "x" and config.get("_x_envelope") is not None:+ stream_limit *= _source_fetch_cap("x", config) or 1normalized = _apply_reddit_stream_keepers(- source, normalized, settings["per_stream_limit"], topic+ source, normalized, stream_limit, topic)bundle.add_items(subquery.label, source, normalized)if artifact:diff --git a/skills/last30days/scripts/lib/prescriptions.py b/skills/last30days/scripts/lib/prescriptions.pyindex fc647995..2a57066f 100644--- a/skills/last30days/scripts/lib/prescriptions.py+++ b/skills/last30days/scripts/lib/prescriptions.py@@ -109,18 +109,20 @@ REGISTRY: Dict[Tuple[str, str], Prescription] = dict((anchor="api-keys-env",),# Official X path (an official-only host per env.x_policy, or an explicit- # xapi pin). Copy is limited to the connector lane, X_BEARER_TOKEN,- # XAI_API_KEY, and X API credits; the bearer path is described as- # about a week, never as parity with the connector. Anchors point at+ # xapi pin). Copy is limited to the host X lanes (Grok Bot's built-in X+ # tools, then the X for Grok Bot connector), X_BEARER_TOKEN, XAI_API_KEY,+ # and X API credits; the bearer path is described as about a week, never+ # as parity with the host lanes. Anchors point at# the CONFIGURATION.md Grok Bot subsection (slug grok-bot)._entry("x", "bearer_missing",cause=(- "no official X path is configured (X connector, X_BEARER_TOKEN, "- "or XAI_API_KEY)"+ "no official X path is configured (Grok Bot X tools, X connector, "+ "X_BEARER_TOKEN, or XAI_API_KEY)"),fix_nl=(- "add the X for Grok Bot plugin and connect X in Grok Bot settings (full 30-day coverage), or set "+ "fetch X with Grok Bot's built-in X tools and pass the posts with --x-posts, or add the X for Grok Bot "+ "plugin and connect X in Grok Bot settings (full 30-day coverage), or set "f"X_BEARER_TOKEN from the X developer console ({BEARER_COVERAGE_NOTE}), ""or set XAI_API_KEY from console.x.ai"),@@ -151,12 +153,12 @@ REGISTRY: Dict[Tuple[str, str], Prescription] = dict((_entry("x", "connector_missing",cause=(- "the X connector lane was declared but no connector result was "+ "the host X lane was declared but no host-fetched result was ""passed to the engine"),fix_nl=(- "add the X for Grok Bot plugin and connect X in Grok Bot settings (full 30-day coverage) and pass the "- "connector's posts with --x-posts, or set X_BEARER_TOKEN from the X "+ "fetch X with Grok Bot's built-in X tools (or the X for Grok Bot connector) and pass the "+ "posts with --x-posts, or unset LAST30DAYS_X_HOST_LANE and set X_BEARER_TOKEN from the X "f"developer console ({BEARER_COVERAGE_NOTE})"),fix_cli=f'{ENGINE_CLI} "<topic>" --x-posts <path-to-x-posts.json>',diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.pyindex c30fb0e6..39b0ce0c 100644--- a/skills/last30days/scripts/lib/render.py+++ b/skills/last30days/scripts/lib/render.py@@ -23,6 +23,7 @@ from . import (schema,signals,skill_meta,+ x_envelope,)@@ -3354,9 +3355,10 @@ def _render_stats(report: schema.Report) -> list[str]:actor_summary = _top_actor_summary(source, items)if actor_summary:parts.append(actor_summary)- if source == "x" and report.artifacts.get("x_provenance") == "connector":+ provenance = report.artifacts.get("x_provenance") if source == "x" else None+ if provenance in x_envelope.PROVENANCE_LABELS:# Host-fetched lane (--x-posts): name the provenance in the footer.- parts.append("via X connector")+ parts.append(f"via {x_envelope.PROVENANCE_LABELS[provenance]}")lines.append(f"- {_source_label(source)}: {' | '.join(parts)}")lines.append("")return linesdiff --git a/skills/last30days/scripts/lib/x_envelope.py b/skills/last30days/scripts/lib/x_envelope.pyindex 670ba574..c5a064bf 100644--- a/skills/last30days/scripts/lib/x_envelope.py+++ b/skills/last30days/scripts/lib/x_envelope.py@@ -84,14 +84,27 @@ COUNTERS = (# Engine-authored fixed outcome details. The envelope's own error text# never becomes a detail string.-DETAIL_CREDITS = "X connector reported no credits"-DETAIL_NOT_CONNECTED = "X connector not connected"-DETAIL_UNAVAILABLE = "X connector unavailable"-DETAIL_ERROR = "X connector error"-DETAIL_GENERATED = "X connector rows rejected (id sequence looks generated)"-DETAIL_PARTIAL = "X connector returned partial results"+_CONNECTOR_LABEL = "X connector"+_NATIVE_LABEL = "Grok Bot X"+DETAIL_CREDITS = f"{_CONNECTOR_LABEL} reported no credits"+DETAIL_NOT_CONNECTED = f"{_CONNECTOR_LABEL} not connected"+DETAIL_UNAVAILABLE = f"{_CONNECTOR_LABEL} unavailable"+DETAIL_ERROR = f"{_CONNECTOR_LABEL} error"+DETAIL_GENERATED = f"{_CONNECTOR_LABEL} rows rejected (id sequence looks generated)"+DETAIL_PARTIAL = f"{_CONNECTOR_LABEL} returned partial results"DETAIL_NOT_PASSED = "connector result not passed"+# The envelope's free-text ``provider`` reaches output only through this+# allowlist: ``x-native`` (Grok Bot's built-in X tools) gets its own label,+# and anything else keeps the connector wording.+PROVIDER_NATIVE = "x-native"+PROVENANCE_NATIVE = "native"+PROVENANCE_CONNECTOR = "connector"+PROVENANCE_LABELS = {+ PROVENANCE_CONNECTOR: _CONNECTOR_LABEL,+ PROVENANCE_NATIVE: _NATIVE_LABEL,+}+CATEGORY_CREDITS = "credits"CATEGORY_NOT_CONNECTED = "not-connected"CATEGORY_UNAVAILABLE = "unavailable"@@ -192,19 +205,32 @@ class Envelope:self._lanes_served = Truereturn list(self.lane_calls)+ @property+ def provenance(self) -> str:+ """``native`` for a Grok Bot built-in X envelope, else ``connector``."""+ if self.provider.lower() == PROVIDER_NATIVE:+ return PROVENANCE_NATIVE+ return PROVENANCE_CONNECTOR+def outcome(self) -> tuple[schema.RunOutcomeState, str] | None:"""The fixed source outcome for a non-ok envelope, else ``None``."""if self.status == "error":- return _error_outcome(self.error_category)+ state, detail = _error_outcome(self.error_category)+ return state, self._labelled(detail)if self.status == "partial":detail = DETAIL_PARTIALif self.error_category:detail += f": {self.error_category}"if self.call_lanes:detail += f" (calls: {', '.join(self.call_lanes)})"- return schema.PARTIAL, detail+ return schema.PARTIAL, self._labelled(detail)return None+ def _labelled(self, detail: str) -> str:+ if self.provenance == PROVENANCE_NATIVE:+ return detail.replace(_CONNECTOR_LABEL, _NATIVE_LABEL, 1)+ return detail+def receipt(self) -> str:dropped = ", ".join(f"{name} {count}" for name, count in self.counters.items() if countdiff --git a/skills/last30days/scripts/x_lane_parity.py b/skills/last30days/scripts/x_lane_parity.pynew file mode 100644index 00000000..036bb637--- /dev/null+++ b/skills/last30days/scripts/x_lane_parity.py@@ -0,0 +1,107 @@+#!/usr/bin/env python3+"""Compare the X results of two saved last30days report JSON files.++Dev tool for checking one X lane against another on the same topic and+window. Each input is the output of ``last30days.py <topic> --emit=json+--json-profile=raw``; the optional envelope is the candidate's ``--x-posts``+file, so a baseline post the candidate fetched but did not keep still counts+toward recall.++ python3 scripts/x_lane_parity.py baseline.json candidate.json [--envelope x-posts.json]+"""++from __future__ import annotations++import argparse+import json+import re+import sys+from pathlib import Path++_STATUS_RE = re.compile(r"/status/(\d+)")+_METRICS = ("likes", "reposts", "replies", "quotes")+TOP_N = 10+++def _load(path: str) -> dict:+ return json.loads(Path(path).read_text(encoding="utf-8"))+++def _x_items(report: dict) -> list[dict]:+ return list((report.get("items_by_source") or {}).get("x") or [])+++def _require_same_run_shape(base: dict, cand: dict, envelope: dict | None) -> None:+ """Refuse to compare reports that cover different topics or windows."""+ for key in ("topic", "range_from", "range_to"):+ if base.get(key) != cand.get(key):+ raise ValueError(f"reports differ on {key}: {base.get(key)!r} vs {cand.get(key)!r}")+ if envelope is not None and envelope.get("topic") != cand.get("topic"):+ raise ValueError(+ f"envelope topic {envelope.get('topic')!r} does not match the candidate report {cand.get('topic')!r}"+ )+++def _post_id(item: dict) -> str | None:+ match = _STATUS_RE.search(str(item.get("url") or ""))+ return match.group(1) if match else None+++def _likes(item: dict) -> int:+ value = (item.get("engagement") or {}).get("likes")+ return int(value) if isinstance(value, (int, float)) else 0+++def _envelope_ids(payload: dict | None) -> set[str]:+ if not payload:+ return set()+ return {+ str(post.get("id"))+ for call in payload.get("calls") or []+ for post in call.get("posts") or []+ if post.get("id")+ }+++def _ratio(numerator: float, denominator: float) -> float:+ return round(numerator / denominator, 3) if denominator else 0.0+++def compare(baseline: str, candidate: str, *, envelope: str | None = None) -> dict:+ """Counts, top-liked recall, field completeness, and author spread."""+ base, cand = _load(baseline), _load(candidate)+ env = _load(envelope) if envelope else None+ _require_same_run_shape(base, cand, env)+ base_items = _x_items(base)+ cand_items = _x_items(cand)+ cand_ids = {pid for pid in map(_post_id, cand_items) if pid} | _envelope_ids(env)+ top = sorted(base_items, key=_likes, reverse=True)[:TOP_N]+ top_ids = [pid for pid in map(_post_id, top) if pid]+ complete = sum(+ 1 for item in cand_items+ if all(isinstance((item.get("engagement") or {}).get(m), (int, float)) for m in _METRICS)+ )+ return {+ "baseline_count": len(base_items),+ "candidate_count": len(cand_items),+ "count_ratio": _ratio(len(cand_items), len(base_items)),+ "top_liked_recall": _ratio(sum(1 for pid in top_ids if pid in cand_ids), len(top_ids)),+ "candidate_field_completeness": _ratio(complete, len(cand_items)),+ "baseline_authors": len({item.get("author") for item in base_items}),+ "candidate_authors": len({item.get("author") for item in cand_items}),+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("baseline")+ parser.add_argument("candidate")+ parser.add_argument("--envelope")+ args = parser.parse_args(argv)+ json.dump(compare(args.baseline, args.candidate, envelope=args.envelope), sys.stdout, indent=2)+ sys.stdout.write("\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/skill_contract.py b/tests/skill_contract.pyindex 9883e319..052792d4 100644--- a/tests/skill_contract.py+++ b/tests/skill_contract.py@@ -19,7 +19,7 @@ ROUTES = {"--agent mode or explicit machine-readable JSON": ("agent-mode",),"Recommendation intent": ("recommendations",),"Identifiable product requires category peers": ("category-peers",),- "Grok Bot official X connector lane": ("grok-bot-x",),+ "Grok Bot X lane": ("grok-bot-x",),"Follow-up on existing research": ("followups",),"HTML/export intent": ("save-html-brief",),}diff --git a/tests/test_doctor.py b/tests/test_doctor.pyindex d8abfa43..90eb8ff5 100644--- a/tests/test_doctor.py+++ b/tests/test_doctor.py@@ -1545,21 +1545,21 @@ class GrokBotHostDoctor(unittest.TestCase):self.assertEqual("ok", rec["status"])self.assertEqual("ok", rec["tier"])self.assertEqual("connector", rec["active_backend"])- self.assertEqual("will use: X connector (host-fetched at run time)", rec["note"])+ self.assertEqual("will use: built-in X tools or X connector (host-fetched at run time)", rec["note"])self.assertEqual("", rec["fix"])backup = rec["backups"][0]self.assertTrue(backup["armed"])- self.assertEqual("X connector lane armed", backup["note"])+ self.assertEqual("host X lane armed (built-in X tools or X connector)", backup["note"])text = "\n".join(_x_text_lines(doctor.render_text(report)))- self.assertIn("will use: X connector (host-fetched at run time)", text)- self.assertIn("X connector lane armed", text)+ self.assertIn("will use: built-in X tools or X connector (host-fetched at run time)", text)+ self.assertIn("host X lane armed (built-in X tools or X connector)", text)self._assert_official_vocabulary(report)def test_lane_with_bearer_keeps_backend_prediction_and_lane_armed(self):report = _build(_grok_bot(LAST30DAYS_X_HOST_LANE="1", X_BEARER_TOKEN="dummy-x-bearer-secret-000"))rec = report["sources"]["x"]self.assertEqual("xapi", rec["active_backend"])- self.assertEqual("X connector lane armed", rec["backups"][0]["note"])+ self.assertEqual("host X lane armed (built-in X tools or X connector)", rec["backups"][0]["note"])def test_bird_pin_names_bird_once_as_pinned(self):config = _grok_bot(diff --git a/tests/test_grok_bot_host_contract.py b/tests/test_grok_bot_host_contract.pyindex 8e231c94..f007387d 100644--- a/tests/test_grok_bot_host_contract.py+++ b/tests/test_grok_bot_host_contract.py@@ -24,7 +24,7 @@ CONFIGURATION = ROOT / "CONFIGURATION.md"AGENTS_MD = ROOT / "AGENTS.md"FLOW_HEADING = "### Grok Bot Prose Flow"-RECIPE_MARKER = "X connector recipe"+RECIPE_MARKER = "Grok Bot X recipe"RECIPE_END = "**Step 1: Run the research script"# R4 vocabulary: none of it may appear in the Grok Bot flow (case-insensitive).@@ -161,6 +161,18 @@ class TestGrokBotProseFlow(unittest.TestCase):bearer = self.flow.index("X_BEARER_TOKEN")self.assertLess(connector, bearer)+ def test_built_in_x_tools_come_before_the_plugin_and_need_no_setup(self):+ native = self.flow.index("namespace `x`")+ plugin = self.flow.index('"X for Grok Bot"')+ bearer = self.flow.index("X_BEARER_TOKEN")+ self.assertLess(native, plugin)+ self.assertLess(plugin, bearer)+ self.assertIn("nothing to configure", self.flow)+ self.assertIn("only when neither is present", self.flow)++ def test_lane_signal_is_exported_only_after_a_fetch_returned_posts(self):+ self.assertIn("only in an engine shell whose fetch returned posts", self.flow)+def test_bearer_coverage_caveat_never_implies_parity(self):self.assertIn("recent posts, about the last week, unless your X developer project has full-archive access",@@ -266,6 +278,56 @@ class TestConnectorRecipe(unittest.TestCase):def test_recipe_has_no_r4_vocabulary(self):self.assertEqual([], _forbidden_hits(self.recipe))+ def test_recipe_names_both_host_lanes_by_source_before_the_engine_chain(self):+ plugin = self.recipe.index('"X for Grok Bot"')+ native = self.recipe.index("namespace `x`")+ bearer = self.recipe.index("X_BEARER_TOKEN")+ self.assertLess(native, plugin)+ self.assertLess(plugin, bearer)+ self.assertIn("never by its name", self.recipe)+ for token in ('"provider": "x-native"', '"x-connector"', "X via Grok Bot X"):+ self.assertIn(token, self.recipe, token)++ def test_recipe_pages_recency_to_the_depth_count(self):+ for token in ("`recency`", "next_token", "max_results", "ONE envelope call", "note_tweet"):+ self.assertIn(token, self.recipe, token)+ for metric in ("like_count", "retweet_count", "reply_count", "quote_count"):+ self.assertIn(metric, self.recipe, metric)++ def test_recipe_samples_popular_posts_across_the_whole_window(self):+ self.assertIn("popular pass", self.recipe)+ popular = self.recipe[self.recipe.index("popular pass"):]+ popular = popular[: popular.index("\n")]+ self.assertIn("first topic query only", popular)+ self.assertIn("10 equal slices", popular)+ self.assertIn("`relevancy`", popular)+ self.assertIn("ONE envelope call", popular)++ def test_recipe_keeps_the_envelope_inside_engine_limits(self):+ self.assertIn("500 posts per call", self.recipe)+ self.assertIn("1,000 posts and 20 calls in total", self.recipe)+ self.assertIn("drop discovered-author calls first", self.recipe)++ def test_comparison_uses_envelopes_only_when_every_entity_has_posts(self):+ self.assertIn("only when every entity's fetch returned posts", self.recipe)++ def test_comparison_paces_tool_calls_under_the_per_minute_limit(self):+ self.assertIn("no minute holds more than 30 tool calls", self.recipe)+ self.assertIn("popular pass for the main entity only", self.recipe)++ def test_recipe_gives_discovered_authors_full_handle_lanes(self):+ authors = self.recipe[self.recipe.index("**Discovered authors.**"):]+ authors = authors[: authors.index("\n - ")]+ self.assertIn("`from` call", authors)+ self.assertIn("8 posts", authors)+ self.assertIn("`mention` call", authors)+ self.assertIn("5 posts", authors)+ self.assertIn("`--x-related`", authors)++ def test_recipe_exports_the_lane_only_after_posts_came_back(self):+ self.assertIn("only when a lane returned posts", self.recipe)+ self.assertIn("unset LAST30DAYS_X_HOST_LANE", self.recipe)+class TestExtrasPassagesRescoped(unittest.TestCase):def test_extras_passages_no_longer_name_grok_bot(self):diff --git a/tests/test_prescriptions.py b/tests/test_prescriptions.pyindex 6e6ad2cc..756a0b10 100644--- a/tests/test_prescriptions.py+++ b/tests/test_prescriptions.py@@ -452,3 +452,10 @@ class TestAltCliArityPin:f"youtube/{failure} lost a platform alternate; quality_nudge ""wording degrades (tolerant, but fix the entry or the prose)")++[email protected]("failure", ["bearer_missing", "connector_missing"])+def test_official_x_repair_names_grok_bots_built_in_tools_before_the_connector(failure):+ fix = prescriptions.for_x(GROK_BOT, failure).fix_nl+ assert "built-in X tools" in fix+ assert fix.index("built-in X tools") < fix.index("X for Grok Bot")diff --git a/tests/test_x_envelope.py b/tests/test_x_envelope.pyindex 88fcf67a..477f4038 100644--- a/tests/test_x_envelope.py+++ b/tests/test_x_envelope.py@@ -808,6 +808,91 @@ class TestPipelineWiring:assert "x" not in report.errors_by_sourceassert report.source_status["x"].state == health.OK+ @staticmethod+ def _many_topic_rows(count: int) -> list[dict]:+ # Distinct wording per row so near-duplicate collapsing keeps them all.+ onsets = ("br", "k", "pl", "st", "gr", "v", "dr", "sh")+ vowels = ("a", "e", "i", "o", "u", "ai", "oo")+ codas = ("n", "x", "lt", "mp", "rd", "sk", "th", "z")++ def word(n: int) -> str:+ return onsets[n % 8] + vowels[(n // 8) % 7] + codas[(n // 56) % 8]++ return [+ _row(+ i, f"user{i}",+ f"ai agents {word(i * 3)} {word(i * 3 + 1)} {word(i * 3 + 2)}",+ likes=count - i,+ )+ for i in range(count)+ ]++ @pytest.mark.parametrize(("depth", "expected"), [("quick", 12), ("default", 24), ("deep", 40)])+ def test_topic_lane_carries_two_x_streams_worth_of_rows(self, tmp_path, depth, expected):+ rows = self._many_topic_rows(57)+ envelope = _read(_write(tmp_path, _envelope([+ _call("topic", posts=rows[:30]), _call("topic", posts=rows[30:]),+ ])))+ report = _run(envelope, depth=depth)+ assert len(report.items_by_source["x"]) == expected++ def test_small_envelope_keeps_every_topic_row(self, tmp_path):+ envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=self._many_topic_rows(9))])))+ report = _run(envelope)+ assert len(report.items_by_source["x"]) == 9++ def test_capped_topic_rows_keep_the_most_engaged_posts(self, tmp_path):+ rows = self._many_topic_rows(57)+ envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=list(reversed(rows)))])))+ report = _run(envelope)+ kept = {item.engagement.get("likes") for item in report.items_by_source["x"]}+ assert max(row["likes"] for row in rows) in kept+ assert min(row["likes"] for row in rows) not in kept++ def test_backend_x_stream_keeps_the_per_stream_limit(self):+ items = [+ {"id": f"X{i}", "text": f"ai agents note {i}", "url": f"https://x.com/u{i}/status/{1900000000000000000 + i}",+ "author_handle": f"u{i}", "date": TO, "engagement": {"likes": i}}+ for i in range(30)+ ]+ with mock.patch("lib.env.x_backend_chain", return_value=["bird"]), \+ mock.patch("lib.pipeline._fetch_x_backend", return_value=(items, {})):+ report = pipeline.run(+ topic=TOPIC, config={}, depth="default", requested_sources=["x"], mock=False,+ external_plan=_plan(), web_backend="none", save_dir="",+ )+ assert len(report.items_by_source["x"]) <= 12++ def test_set_backend_on_grok_bot_yields_to_envelope_and_runs_without_one(self, tmp_path, monkeypatch):+ monkeypatch.setenv("LAST30DAYS_HOST", "grok-bot")+ config = {"LAST30DAYS_HOST": "grok-bot", "LAST30DAYS_X_BACKEND": "xapi", "X_BEARER_TOKEN": "dummy"}+ envelope = _read(_basic(tmp_path))+ served = _run(envelope, config=config, x_handle=SUBJECT)+ assert served.artifacts.get("x_provenance") in {"connector", "native"}+ assert len(served.items_by_source["x"]) == 3+ backend_item = {+ "id": "X1", "text": "ai agents from the set backend",+ "url": "https://x.com/someone/status/1900000000000000001", "author_handle": "someone",+ "date": TO, "engagement": {"likes": 5},+ }+ with mock.patch("lib.pipeline._fetch_x_backend", return_value=([backend_item], {})) as fetch:+ report = pipeline.run(+ topic=TOPIC, config=dict(config), depth="default", requested_sources=["x"], mock=False,+ external_plan=_plan(), web_backend="none", save_dir="",+ )+ assert fetch.called+ assert "x_provenance" not in report.artifacts++ def test_discovered_author_lanes_passed_as_related_keep_their_lanes(self, tmp_path):+ envelope = _read(_write(tmp_path, _envelope([+ _call("topic", posts=[_row(0, "alice", "ai agents review")]),+ _call("from", handles=[RELATED], posts=[_row(1, RELATED, "ai agents in my stack")]),+ _call("mention", handles=[RELATED], posts=[_row(2, "carol", f"@{RELATED} ai agents question")]),+ ])), handles=(), related=(RELATED,))+ assert envelope.lane_counts["from"] == 1+ assert envelope.lane_counts["mention"] == 1+ assert envelope.counters["lane-mismatch"] == 0+def test_available_sources_lists_x_for_envelope_without_backend(self):with mock.patch("lib.env.x_backend_chain", return_value=[]), \mock.patch("lib.env.x_pending_browser_auth", return_value=False):@@ -915,6 +1000,30 @@ class TestPipelineWiring:assert "via X connector" in mdassert "3 items" in md+ def test_footer_provenance_reads_via_grok_bot_x_for_native_envelopes(self, tmp_path):+ envelope = _read(_basic(tmp_path, provider="x-native"))+ report = _run(envelope, x_handle=SUBJECT)+ md = render.render_compact(report)+ assert "via Grok Bot X" in md+ assert "via X connector" not in md++ @pytest.mark.parametrize("provider", ["", "X-Native; rm -rf ~", "grok", "x-native-ish"])+ def test_unknown_provider_falls_back_to_connector_label(self, tmp_path, provider):+ envelope = _read(_basic(tmp_path, provider=provider))+ report = _run(envelope, x_handle=SUBJECT)+ md = render.render_compact(report)+ assert "via X connector" in md+ if provider:+ assert provider not in md++ def test_native_partial_outcome_names_grok_bot_x(self, tmp_path):+ envelope = _read(_basic(tmp_path, provider="x-native", status="partial", error="window-unsupported"))+ state, detail = envelope.outcome()+ assert state == schema.PARTIAL+ assert detail.startswith("Grok Bot X returned partial results")+ connector = _read(_basic(tmp_path, status="partial", error="window-unsupported"))+ assert connector.outcome()[1].startswith("X connector returned partial results")+def test_env_file_lane_line_without_process_env_leaves_x_absent(self, tmp_path, monkeypatch):monkeypatch.delenv("LAST30DAYS_X_HOST_LANE", raising=False)config_file = tmp_path / ".env"diff --git a/tests/test_x_lane_parity.py b/tests/test_x_lane_parity.pynew file mode 100644index 00000000..5996405f--- /dev/null+++ b/tests/test_x_lane_parity.py@@ -0,0 +1,83 @@+"""x_lane_parity: compare the X results of two saved report JSON files."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++import x_lane_parity as parity+++def _item(post_id: int, handle: str, likes: int | None, **engagement) -> dict:+ eng = {"likes": likes, "reposts": 1, "replies": 0, "quotes": 0, **engagement}+ if likes is None:+ eng.pop("likes")+ return {+ "source": "x",+ "url": f"https://x.com/{handle}/status/{post_id}",+ "author": handle,+ "engagement": eng,+ }+++def _report(tmp_path: Path, name: str, items: list[dict], topic: str = "t") -> str:+ path = tmp_path / name+ path.write_text(json.dumps({+ "topic": topic, "range_from": "2026-09-07", "range_to": "2026-10-07",+ "items_by_source": {"x": items},+ }), encoding="utf-8")+ return str(path)+++def test_counts_ratio_and_top_liked_recall(tmp_path):+ baseline = [_item(100 + i, f"b{i}", likes=100 - i) for i in range(12)]+ # The candidate holds 7 of the baseline's 10 most-liked posts plus 3 others.+ candidate = [_item(100 + i, f"b{i}", likes=100 - i) for i in (0, 1, 2, 3, 4, 5, 6)]+ candidate += [_item(900 + i, "c", likes=5) for i in range(3)]+ result = parity.compare(_report(tmp_path, "a.json", baseline), _report(tmp_path, "b.json", candidate))+ assert result["baseline_count"] == 12+ assert result["candidate_count"] == 10+ assert result["count_ratio"] == round(10 / 12, 3)+ assert result["top_liked_recall"] == 0.7+ assert result["baseline_authors"] == 12+ assert result["candidate_authors"] == 8+++def test_recall_also_counts_posts_present_only_in_the_envelope(tmp_path):+ baseline = [_item(100 + i, f"b{i}", likes=50 - i) for i in range(10)]+ candidate = [_item(100, "b0", likes=50)]+ envelope = tmp_path / "env.json"+ envelope.write_text(json.dumps({"topic": "t", "calls": [{"lane": "topic", "posts": [+ {"id": str(100 + i), "author_handle": f"b{i}"} for i in range(1, 5)+ ]}]}), encoding="utf-8")+ result = parity.compare(+ _report(tmp_path, "a.json", baseline), _report(tmp_path, "b.json", candidate), envelope=str(envelope),+ )+ assert result["top_liked_recall"] == 0.5+++def test_field_completeness_counts_missing_metrics(tmp_path):+ candidate = [_item(1, "a", likes=3), _item(2, "b", likes=None)]+ result = parity.compare(_report(tmp_path, "a.json", [_item(1, "a", likes=3)]), _report(tmp_path, "b.json", candidate))+ assert result["candidate_field_completeness"] == 0.5+++def test_empty_reports_do_not_crash(tmp_path):+ result = parity.compare(_report(tmp_path, "a.json", []), _report(tmp_path, "b.json", []))+ assert result["baseline_count"] == 0+ assert result["count_ratio"] == 0.0+ assert result["top_liked_recall"] == 0.0+++def test_reports_for_different_topics_are_refused(tmp_path):+ with pytest.raises(ValueError, match="topic"):+ parity.compare(_report(tmp_path, "a.json", [], topic="t"), _report(tmp_path, "b.json", [], topic="other"))+++def test_envelope_for_another_topic_is_refused(tmp_path):+ envelope = tmp_path / "env.json"+ envelope.write_text(json.dumps({"topic": "other", "calls": []}), encoding="utf-8")+ with pytest.raises(ValueError, match="envelope topic"):+ parity.compare(_report(tmp_path, "a.json", []), _report(tmp_path, "b.json", []), envelope=str(envelope))