
Last30days
- 26.4k installs
- 54.2k repo stars
- Updated July 26, 2026
- mvanhorn/last30days-skill
last30days is an agent research skill that pulls real-time sentiment, trends, and discussions from Reddit, X, YouTube, and the open web for developers who need current-topic intelligence within the past 30 days.
About
A research skill that searches 20+ sources (Reddit, X, YouTube, TikTok, Hacker News, Polymarket, GitHub, arXiv, Techmeme) in parallel and synthesizes findings into a single brief scored by real engagement. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and 50+ AI agent platforms. Zero configuration for Reddit, HN, Polymarket, and GitHub.
- AI-agent-led search scored by engagement - Reddit upvotes, X likes, TikTok views, Polymarket odds
- Searches 20+ platforms in parallel - Reddit, HN, X, YouTube, TikTok, arXiv, Techmeme, LinkedIn, GitHub
- Synthesized briefs with citations grounded in real engagement over last 30 days
Last30days by the numbers
- 26,365 all-time installs (skills.sh)
- +2,055 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #47 of 3,301 Productivity & Planning skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mvanhorn/last30days-skill --skill last30daysAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 26.4k |
|---|---|
| repo stars | ★ 54.2k |
| Security audit | 0 / 3 scanners passed |
| Last updated | July 26, 2026 |
| Repository | mvanhorn/last30days-skill ↗ |
How do you research developer sentiment from the last 30 days?
A research skill that searches 20+ sources (Reddit, X, YouTube, TikTok, Hacker News, Polymarket, GitHub, arXiv, Techmeme) in parallel and synthesizes findings into a single brief scored by real engag
Who is it for?
Developers evaluating frameworks, APIs, or developer-community trends who need multi-source signals newer than static documentation.
Skip if: Deep academic literature reviews, historical analysis beyond 30 days, or teams blocked from external network access.
When should I use this skill?
A developer asks what people are saying about a technology lately, wants last-30-day Reddit/X/YouTube research, or requests a shareable HTML research brief.
What you get
Synthesized expert-style research answers, copy-paste prompts, and optional shareable HTML briefs covering the past 30 days.
- Synthesized research summary
- Copy-paste prompts
- Optional shareable HTML brief
Files
interface: display_name: "Last 30 Days" short_description: "Research any topic across Reddit, X, YouTube, and the web from the last 30 days. Returns synthesized expert answers and copy-paste prompts." default_prompt: "Research this topic from the last 30 days across Reddit, X, YouTube, and web. Synthesize what people are actually saying, upvoting, and sharing right now." brand_color: "#FF6B35"
policy: allow_implicit_invocation: true
Save shareable HTML brief
This reference file is loaded by the main SKILL.md when the user asked for an HTML brief (either explicitly via --emit=html / --emit:html / --html, or in natural language - "give me a shareable HTML brief", "for Slack", "for Notion", "export as HTML", etc.). The detection happens in SKILL.md so that the common no-HTML path stays short; the implementation lives here.
The contract: the synthesis still appears in chat as the primary output. The HTML is an additional artifact saved to disk for sharing. Both happen in the same turn.
When to fire this flow
- After you have already emitted the full chat response: badge, "What I learned:" (or comparison title), bold-lead-in paragraphs with citations, KEY PATTERNS list, engine footer pass-through, invitation block.
- BEFORE the WAIT FOR USER'S RESPONSE pause.
- ONLY if the user asked. Do NOT save HTML when the user didn't ask for it.
How to fire it
# 1. Write your synthesis prose VERBATIM to a temp file. The synthesis is the
# "What I learned:" prose label, the bold-lead-in paragraphs with their
# inline citations as you wrote them in chat, and the "KEY PATTERNS from
# the research:" numbered list. Do NOT include the badge or the engine
# footer in the temp file - the engine adds those when it renders the HTML.
# Use the EXACT text you just wrote in chat. Do not paraphrase, do not
# summarize, do not reorder. The HTML must read identically to the chat
# response in voice and citations.
SYNTHESIS_FILE="/tmp/last30days-synthesis-${CLAUDE_SESSION_ID}.md"
cat > "$SYNTHESIS_FILE" <<'SYNTHESIS_EOF'
What I learned:
**{First headline}** - {body with [name](url) inline citations}
**{Second headline}** - {body}
**{Third headline}** - {body}
KEY PATTERNS from the research:
1. {pattern} - per [@handle](url)
2. {pattern} - per [r/sub](url)
3. {pattern} - per [@handle](url)
SYNTHESIS_EOF
# 2. Convert the synthesis to a self-contained HTML file via the engine.
# The engine reuses the cache from your earlier engine run (same topic
# + plan), so this second invocation is typically <1s on cache hit.
SLUG=$(echo "$TOPIC" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//')
HTML_PATH="${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.html"
"${LAST30DAYS_PYTHON}" "${SKILL_ROOT}/scripts/last30days.py" "${TOPIC}" \
--emit=html \
--synthesis-file "$SYNTHESIS_FILE" \
> "$HTML_PATH"
# 3. Append ONE line to your already-emitted chat response, after the
# invitation block. Use a paperclip emoji as a visible signal that an
# artifact was produced:
echo "📎 Shareable brief saved to $HTML_PATH"What ends up in the HTML file
The engine's --emit=html renderer combines:
- The badge (
🌐 last30days vX.Y.Z · synced YYYY-MM-DD) at the top - A single inline metadata line (
{date range} · {active sources}) below the badge - Your synthesis verbatim, with prose labels promoted to
<h2>and bold lead-ins preserved - All
[name](url)citations rendered as<a>tags - The engine footer (
✅ All agents reported back!tree) preserved verbatim in monospace - A colophon with the topic and a re-run hint
The renderer strips engine-internal noise that doesn't belong in a shareable artifact: the # last30days vX.Y.Z: TOPIC debug file header, the model-facing > Safety note: blockquote, and the I'm now an expert on X invitation block. Data quality warnings (degraded run, thin evidence, etc.) stay in the engine's stderr logs - they never leak into the share-ready f
interface:
display_name: "Last 30 Days"
short_description: "Research any topic across Reddit, X, YouTube, and the web from the last 30 days. Returns synthesized expert answers and copy-paste prompts."
default_prompt: "Research this topic from the last 30 days across Reddit, X, YouTube, and web. Synthesize what people are actually saying, upvoting, and sharing right now."
brand_color: "#FF6B35"
policy:
allow_implicit_invocation: true
Save shareable HTML brief
This reference file is loaded by the main SKILL.md when the user asked for an HTML brief (either explicitly via --emit=html / --emit:html / --html, or in natural language - "give me a shareable HTML brief", "for Slack", "for Notion", "export as HTML", etc.). The detection happens in SKILL.md so that the common no-HTML path stays short; the implementation lives here.
The contract: the synthesis still appears in chat as the primary output. The HTML is an additional artifact saved to disk for sharing. Both happen in the same turn.
When to fire this flow
- After you have already emitted the full chat response: badge, "What I learned:" (or comparison title), bold-lead-in paragraphs with citations, KEY PATTERNS list, engine footer pass-through, invitation block.
- BEFORE the WAIT FOR USER'S RESPONSE pause.
- ONLY if the user asked. Do NOT save HTML when the user didn't ask for it.
How to fire it
# 1. Write your synthesis prose VERBATIM to a temp file. The synthesis is the
# "What I learned:" prose label, the bold-lead-in paragraphs with their
# inline citations as you wrote them in chat, and the "KEY PATTERNS from
# the research:" numbered list. Do NOT include the badge or the engine
# footer in the temp file - the engine adds those when it renders the HTML.
# Use the EXACT text you just wrote in chat. Do not paraphrase, do not
# summarize, do not reorder. The HTML must read identically to the chat
# response in voice and citations.
SYNTHESIS_FILE="/tmp/last30days-synthesis-${CLAUDE_SESSION_ID}.md"
cat > "$SYNTHESIS_FILE" <<'SYNTHESIS_EOF'
What I learned:
**{First headline}** - {body with [name](url) inline citations}
**{Second headline}** - {body}
**{Third headline}** - {body}
KEY PATTERNS from the research:
1. {pattern} - per [@handle](url)
2. {pattern} - per [r/sub](url)
3. {pattern} - per [@handle](url)
SYNTHESIS_EOF
# 2. Convert the synthesis to a self-contained HTML file via the engine.
# The engine reuses the cache from your earlier engine run (same topic
# + plan), so this second invocation is typically <1s on cache hit.
SLUG=$(echo "$TOPIC" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//')
HTML_PATH="${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.html"
"${LAST30DAYS_PYTHON}" "${SKILL_ROOT}/scripts/last30days.py" "${TOPIC}" \
--emit=html \
--synthesis-file "$SYNTHESIS_FILE" \
> "$HTML_PATH"
# 3. Append ONE line to your already-emitted chat response, after the
# invitation block. Use a paperclip emoji as a visible signal that an
# artifact was produced:
echo "📎 Shareable brief saved to $HTML_PATH"What ends up in the HTML file
The engine's --emit=html renderer combines:
- The badge (
🌐 last30days vX.Y.Z · synced YYYY-MM-DD) at the top - A single inline metadata line (
{date range} · {active sources}) below the badge - Your synthesis verbatim, with prose labels promoted to
<h2>and bold lead-ins preserved - All
[name](url)citations rendered as<a>tags - The engine footer (
✅ All agents reported back!tree) preserved verbatim in monospace - A colophon with the topic and a re-run hint
The renderer strips engine-internal noise that doesn't belong in a shareable artifact: the # last30days vX.Y.Z: TOPIC debug file header, the model-facing > Safety note: blockquote, and the I'm now an expert on X invitation block. Data quality warnings (degraded run, thin evidence, etc.) stay in the engine's stderr logs - they never leak into the share-ready file.
Comparison mode
Same flow when the topic is X vs Y (or X vs Y vs Z). The engine routes through render_for_html_comparison internally; you don't need to do anything special. The synthesis temp file should still contain the comparison-shaped synthesis you wrote in chat (## Quick Verdict, ## {Entity} per entity, ## Head-to-Head table, ## The Bottom Line, ## The emerging stack per LAW 4 comparison exception).
Follow-up turn
If the user runs /last30days OpenClaw normally, sees the synthesis in chat, and THEN says "save that as HTML" or "give me a shareable version" in a follow-up turn, do the same save flow on the synthesis you wrote in the previous turn. Do not re-research; the synthesis is already in the conversation history. Just write it to the temp file and call the engine with --emit=html --synthesis-file.
What NOT to do
- Do NOT save HTML if the user didn't ask. The sparse mode (no synthesis) produces a thin file; not useful as a shareable.
- Do NOT add content to the temp file beyond your synthesis prose. The badge / footer / colophon come from the engine.
- Do NOT change the file path convention.
${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.htmlis the canonical location. - Do NOT silently overwrite an existing file without telling the user. If
$HTML_PATHalready exists from a prior run, the engine will pick a date-suffixed name ({slug}-brief-YYYY-MM-DD.html) automatically; just print whichever path the redirect produced. - Do NOT include the data quality warning text in the temp file or in your final chat line. Warnings are an engine-stderr concern, not an artifact concern.
Edge cases
- Topic with shell-special characters (quotes, ampersands): the temp filename uses a slugified version, but the engine receives the raw topic. The
cat <<'SYNTHESIS_EOF'quoted heredoc form handles arbitrary content without expansion. Your synthesis text can include any character. - Very long synthesis: no upper bound. The engine handles long markdown bodies. Just paste verbatim.
- Synthesis with images or non-ASCII: emoji and Unicode pass through. Image tags pass through as raw HTML; the renderer doesn't transform them. If you didn't include images in chat, don't add them here.
- No `${LAST30DAYS_MEMORY_DIR}` set: defaults to
~/Documents/Last30Days/per the SKILL.mdConfigurationsection.
#!/usr/bin/env python3
"""Morning briefing generator for last30days.
Synthesizes accumulated findings into formatted briefings.
The Python script collects the data; the agent (via SKILL.md) does the
beautiful synthesis. This script provides the structured data.
Usage:
python3 briefing.py generate # Daily briefing data
python3 briefing.py generate --weekly # Weekly digest data
python3 briefing.py show [--date DATE] # Show saved briefing
"""
import argparse
import json
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent.resolve()
sys.path.insert(0, str(SCRIPT_DIR))
import store
BRIEFS_DIR = Path.home() / ".local" / "share" / "last30days" / "briefs"
def _parse_sqlite_utc_timestamp(value: str) -> datetime:
return datetime.strptime(value, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
def generate_daily(since: str = None) -> dict:
"""Generate daily briefing data.
Returns structured data for the agent to synthesize into a beautiful briefing.
"""
store.init_db()
topics = store.list_topics()
if not topics:
return {
"status": "no_topics",
"message": "No watchlist topics yet. Add one with: last30days watch add \"your topic\"",
}
enabled = [t for t in topics if t["enabled"]]
if not enabled:
return {
"status": "no_enabled",
"message": "All topics are paused. Enable a topic to generate briefings.",
}
# Default: findings since yesterday
if not since:
since = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
briefing_topics = []
total_new = 0
for topic in enabled:
findings = store.get_new_findings(topic["id"], since)
last_run = topic.get("last_run")
last_status = topic.get("last_status", "unknown")
# Calculate staleness
stale = False
hours_ago = None
if last_run:
try:
run_dt = _parse_sqlite_utc_timestamp(last_run)
hours_ago = (datetime.now(timezone.utc) - run_dt).total_seconds() / 3600
stale = hours_ago > 36 # Stale if > 36 hours
except (ValueError, TypeError):
stale = True
topic_data = {
"name": topic["name"],
"findings": findings,
"new_count": len(findings),
"last_run": last_run,
"last_status": last_status,
"stale": stale,
"hours_ago": round(hours_ago, 1) if hours_ago else None,
}
# Extract top finding by engagement
if findings:
top = max(findings, key=lambda f: f.get("engagement_score", 0))
topic_data["top_finding"] = {
"title": top.get("source_title", ""),
"source": top.get("source", ""),
"author": top.get("author", ""),
"engagement": top.get("engagement_score", 0),
"content": top.get("content", "")[:300],
}
briefing_topics.append(topic_data)
total_new += len(findings)
# Cost info
daily_cost = store.get_daily_cost()
budget = float(store.get_setting("daily_budget", "5.00"))
# Find the single top finding across all topics (for TL;DR)
all_findings = []
for t in briefing_topics:
for f in t["findings"]:
f["_topic"] = t["name"]
all_findings.append(f)
top_overall = None
if all_findings:
top_overall = max(all_findings, key=lambda f: f.get("engagement_score", 0))
result = {
"status": "ok",
"date": datetime.now().strftime("%Y-%m-%d"),
"since": since,
"topics": briefing_topics,
"total_new": total_new,
"total_topics": len(briefing_topics),
"top_finding": {
"title": top_overall.get("source_title", ""),
"topic": top_overall.get("_topic", ""),
"engagement": top_overall.get("engagement_score", 0),
} if top_overall else None,
"cost": {
"daily": daily_cost,
"budget": budget,
},
"failed_topics": [
t["name"] for t in briefing_topics if t["last_status"] == "failed"
],
}
# Save briefing data
_save_briefing(result)
return result
def generate_weekly() -> dict:
"""Generate weekly digest data with trend analysis."""
store.init_db()
week_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
two_weeks_ago = (datetime.now() - timedelta(days=14)).strftime("%Y-%m-%d")
topics = store.list_topics()
if not topics:
return {"status": "no_topics", "message": "No watchlist topics."}
weekly_topics = []
for topic in topics:
if not topic["enabled"]:
continue
# This week's findings
this_week = store.get_new_findings(topic["id"], week_ago)
# Last week's findings (for comparison)
conn = store._connect()
try:
last_week_rows = conn.execute(
"""SELECT * FROM findings
WHERE topic_id = ? AND first_seen >= ? AND first_seen < ? AND dismissed = 0
ORDER BY engagement_score DESC""",
(topic["id"], two_weeks_ago, week_ago),
).fetchall()
last_week = [dict(r) for r in last_week_rows]
finally:
conn.close()
this_engagement = sum(f.get("engagement_score", 0) for f in this_week)
last_engagement = sum(f.get("engagement_score", 0) for f in last_week)
# Trend calculation
if last_engagement > 0:
engagement_change = ((this_engagement - last_engagement) / last_engagement) * 100
else:
engagement_change = 100 if this_engagement > 0 else 0
weekly_topics.append({
"name": topic["name"],
"this_week_count": len(this_week),
"last_week_count": len(last_week),
"this_week_engagement": this_engagement,
"last_week_engagement": last_engagement,
"engagement_change_pct": round(engagement_change, 1),
"top_findings": this_week[:5], # Top 5 by engagement (already sorted)
})
result = {
"status": "ok",
"type": "weekly",
"week_of": week_ago,
"topics": weekly_topics,
}
_save_briefing(result, suffix="-weekly")
return result
def show_briefing(date: str = None) -> dict:
"""Load a saved briefing by date."""
if not date:
date = datetime.now().strftime("%Y-%m-%d")
path = BRIEFS_DIR / f"{date}.json"
if not path.exists():
# Try weekly
path = BRIEFS_DIR / f"{date}-weekly.json"
if not path.exists():
return {"status": "not_found", "message": f"No briefing found for {date}."}
with open(path, encoding="utf-8") as f:
return json.load(f)
def _save_briefing(data: dict, suffix: str = ""):
"""Save briefing data to local archive."""
BRIEFS_DIR.mkdir(parents=True, exist_ok=True)
date = datetime.now().strftime("%Y-%m-%d")
path = BRIEFS_DIR / f"{date}{suffix}.json"
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, default=str)
def main():
parser = argparse.ArgumentParser(description="Generate last30days briefings")
sub = parser.add_subparsers(dest="command")
# generate
g = sub.add_parser("generate", help="Generate a briefing")
g.add_argument("--weekly", action="store_true", help="Weekly digest")
g.add_argument("--since", help="Findings since date (YYYY-MM-DD)")
# show
s = sub.add_parser("show", help="Show a saved briefing")
s.add_argument("--date", help="Date (YYYY-MM-DD, default: today)")
args = parser.parse_args()
if args.command == "generate":
if args.weekly:
result = generate_weekly()
else:
result = generate_daily(since=args.since)
print(json.dumps(result, indent=2, default=str))
elif args.command == "show":
result = show_briefing(date=args.date)
print(json.dumps(result, indent=2, default=str))
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env bash
# build-skill.sh - package this repo as a claude.ai-upload-ready .skill file
# Usage: bash skills/last30days/scripts/build-skill.sh (run from repo root)
#
# Produces dist/last30days.skill, a zip with a single top-level `last30days/`
# directory containing SKILL.md and the scripts/ runtime from skills/last30days.
# See
# docs/plans/2026-04-14-001-fix-skill-upload-200-file-limit-plan.md.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "$REPO_ROOT"
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "error: working tree is dirty; commit or stash before building" >&2
exit 1
fi
mkdir -p dist
OUT="dist/last30days.skill"
git archive --format=zip --prefix=last30days/ --output="$OUT" HEAD:skills/last30days
COUNT=$(unzip -l "$OUT" | tail -1 | awk '{print $2}')
SIZE=$(du -h "$OUT" | cut -f1)
if [ "$COUNT" -gt 200 ]; then
echo "error: $COUNT files in zip, claude.ai's cap is 200" >&2
echo " check .gitattributes export-ignore entries and this script's zip -d excludes" >&2
exit 1
fi
SKILL_MD_COUNT=$(unzip -l "$OUT" | grep -c "SKILL.md" || true)
if [ "$SKILL_MD_COUNT" -ne 1 ]; then
echo "error: expected exactly one SKILL.md, found $SKILL_MD_COUNT" >&2
exit 1
fi
echo "built $OUT ($COUNT files, $SIZE)"
echo "upload via the claude.ai skill UI"
#!/bin/bash
# A/B test runner: public release vs private beta
# Usage: bash skills/last30days/scripts/compare.sh "Kanye West"
#
# Runs /last30days (public release) and /last30days-beta (private beta)
# sequentially with a 30s gap, saves raw results with distinct suffixes,
# prints file paths for comparison.
set -e
if [ $# -eq 0 ]; then
echo "Usage: bash skills/last30days/scripts/compare.sh <topic>"
echo " Example: bash skills/last30days/scripts/compare.sh Kevin Rose"
exit 1
fi
TOPIC="$*"
SLUG=$(echo "$TOPIC" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//')
LAST30DAYS_MEMORY_DIR="${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}"
DIR="$LAST30DAYS_MEMORY_DIR"
DATE=$(date +%Y-%m-%d)
echo "=============================================="
echo " A/B Test: $TOPIC"
echo " Date: $DATE"
echo "=============================================="
echo ""
# Run 1: public release
echo "[1/2] Running /last30days (public release)..."
echo " This takes 2-4 minutes..."
claude -p --dangerously-skip-permissions "/last30days $TOPIC" > /dev/null 2>&1 || true
RELEASE_FILE="$DIR/${SLUG}-raw.md"
[ -f "$RELEASE_FILE" ] && echo " Done: $RELEASE_FILE" || echo " FAILED: no output file"
echo ""
echo " Waiting 30s for API rate limits..."
sleep 30
# Run 2: private beta
echo "[2/2] Running /last30days-beta (private beta)..."
echo " This takes 2-4 minutes..."
claude -p --dangerously-skip-permissions "/last30days-beta $TOPIC" > /dev/null 2>&1 || true
BETA_FILE="$DIR/${SLUG}-raw-beta.md"
[ -f "$BETA_FILE" ] && echo " Done: $BETA_FILE" || echo " FAILED: no output file"
echo ""
echo "=============================================="
echo " Both complete. Raw files:"
echo "=============================================="
echo ""
ls -la "$DIR/${SLUG}-raw"*.md 2>/dev/null || echo " (no files found - check if skills saved correctly)"
echo ""
echo "To compare, run in Claude Code:"
echo " Read and compare these raw research files, produce a detailed report:"
echo " $RELEASE_FILE"
echo " $BETA_FILE"
echo ""
echo "Beta output should start with a line like:"
echo " 🧪 last30days-beta · branch <name> · synced $DATE"
echo "If that line is missing, the beta badge regressed. See docs/plans/2026-04-17-005-*-plan.md."
echo ""
#!/usr/bin/env python3
"""Compare two last30days revisions on the v3 ranked candidate output."""
from __future__ import annotations
import argparse
import json
import math
import os
import subprocess
import sys
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
sys.path.insert(0, str(Path(__file__).parent))
from lib import env as envlib
from lib import schema
from lib.providers import GEMINI_FLASH_LITE
SKILL_ROOT = Path(__file__).resolve().parents[1]
REPO_ROOT = Path(__file__).resolve().parents[3]
EVAL_TOPICS_FILE = REPO_ROOT / "fixtures" / "eval_topics.json"
def _load_default_topics() -> list[tuple[str, str]]:
if EVAL_TOPICS_FILE.exists():
rows = json.loads(EVAL_TOPICS_FILE.read_text())
return [(row["topic"], row["query_type"]) for row in rows]
return [
("nano banana pro prompting", "product"),
("codex vs claude code", "comparison"),
("openclaw vs nanoclaw vs ironclaw", "comparison"),
("anthropic odds", "prediction"),
("kanye west", "breaking_news"),
("remotion animations for Claude Code", "how_to"),
]
DEFAULT_TOPICS = _load_default_topics()
DEFAULT_SEARCH = ""
DEFAULT_JUDGE_MODEL = GEMINI_FLASH_LITE
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
def stable_item_key(item: dict[str, Any]) -> str:
return str(item.get("candidate_id") or item.get("url") or item.get("title") or "")
def row_sources(row: dict[str, Any]) -> list[str]:
candidate = schema.candidate_from_dict(row)
return schema.candidate_sources(candidate)
def row_best_date(row: dict[str, Any]) -> str | None:
candidate = schema.candidate_from_dict(row)
return schema.candidate_best_published_at(candidate)
V2_SOURCE_KEYS = [
("reddit", "title"),
("x", "text"),
("youtube", "title"),
("tiktok", "text"),
("instagram", "text"),
("hackernews", "title"),
("bluesky", "text"),
("truthsocial", "text"),
("polymarket", "question"),
("web", "title"),
]
def build_ranked_items(report: dict[str, Any], limit: int) -> list[dict[str, Any]]:
# v3 format: ranked_candidates list
if report.get("ranked_candidates"):
ranked = []
for row in report["ranked_candidates"][:limit]:
candidate_sources = row_sources(row)
ranked.append({
"key": stable_item_key(row),
"source": ", ".join(candidate_sources),
"sources": candidate_sources,
"url": str(row.get("url") or ""),
"text": str(row.get("title") or ""),
"date": row_best_date(row),
"score": float(row.get("final_score") or 0.0),
})
return ranked
# v2 format: per-source lists (reddit, x, youtube, etc.)
all_items = []
for source_key, text_field in V2_SOURCE_KEYS:
for item in report.get(source_key) or []:
if not isinstance(item, dict):
continue
all_items.append({
"key": str(item.get("url") or item.get("id") or item.get(text_field) or ""),
"source": source_key,
"sources": [source_key],
"url": str(item.get("url") or ""),
"text": str(item.get(text_field) or item.get("title") or ""),
"date": item.get("date"),
"score": float(item.get("score") or 0.0),
})
all_items.sort(key=lambda x: x["score"], reverse=True)
return all_items[:limit]
def source_sets(report: dict[str, Any], limit: int) -> dict[str, set[str]]:
grouped: dict[str, set[str]] = {}
for item in build_ranked_items(report, limit):
for source in item["sources"]:
grouped.setdefault(source, set()).add(item["key"])
return grouped
def jaccard(left: set[str], right: set[str]) -> float:
if not left and not right:
return 1.0
union = left | right
if not union:
return 1.0
return len(left & right) / len(union)
def retention(left: set[str], right: set[str]) -> float:
if not left:
return 1.0
return len(left & right) / len(left)
def precision_at_k(ranking: list[dict[str, Any]], judgments: dict[str, int], k: int) -> float:
top = ranking[:k]
if not top:
return 0.0
return sum(1 for item in top if judgments.get(item["key"], 0) >= 2) / len(top)
def ndcg_at_k(ranking: list[dict[str, Any]], judgments: dict[str, int], k: int, judged_pool: list[dict[str, Any]]) -> float:
top = ranking[:k]
if not top:
return 0.0
def dcg(grades: list[int]) -> float:
total = 0.0
for index, grade in enumerate(grades, start=1):
total += (2**grade - 1) / math.log2(index + 1)
return total
actual = [judgments.get(item["key"], 0) for item in top]
ideal = sorted((judgments.get(item["key"], 0) for item in judged_pool), reverse=True)[: len(top)]
ideal_score = dcg(ideal)
if ideal_score == 0:
return 0.0
return dcg(actual) / ideal_score
def source_coverage_recall(ranking: list[dict[str, Any]], judged_pool: list[dict[str, Any]], judgments: dict[str, int]) -> float:
good_sources = {
source
for item in judged_pool
if judgments.get(item["key"], 0) >= 2
for source in item["sources"]
}
if not good_sources:
return 1.0
hit_sources = {
source
for item in ranking
if judgments.get(item["key"], 0) >= 2
for source in item["sources"]
}
return len(hit_sources & good_sources) / len(good_sources)
def resolve_google_judge_api_key(config: dict[str, Any]) -> str | None:
return (
os.environ.get("GOOGLE_API_KEY")
or config.get("GOOGLE_API_KEY")
or os.environ.get("GEMINI_API_KEY")
or config.get("GEMINI_API_KEY")
or os.environ.get("GOOGLE_GENAI_API_KEY")
or config.get("GOOGLE_GENAI_API_KEY")
)
def extract_gemini_text(payload: dict[str, Any]) -> str:
for candidate in payload.get("candidates") or []:
content = candidate.get("content") or {}
for part in content.get("parts") or []:
if part.get("text"):
return part["text"]
raise ValueError("Gemini response did not contain text.")
def call_gemini_judge(api_key: str, model: str, prompt: str) -> dict[str, Any]:
body = {
"contents": [{"parts": [{"text": prompt}]}],
"generationConfig": {"temperature": 0, "responseMimeType": "application/json"},
}
request = Request(
GEMINI_API_URL.format(model=model, api_key=api_key),
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urlopen(request, timeout=120) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise RuntimeError(f"Gemini HTTP {exc.code}: {detail}") from exc
except URLError as exc:
raise RuntimeError(f"Gemini request failed: {exc}") from exc
return json.loads(extract_gemini_text(payload))
def build_judge_prompt(topic: str, query_type: str, items: list[dict[str, Any]]) -> str:
item_lines = []
for item in items:
item_lines.append(
"\n".join([
f"- id: {item['key']}",
f" source: {item['source']}",
f" title: {item['text'][:220]}",
f" url: {item['url']}",
f" date: {item.get('date') or 'unknown'}",
])
)
return f"""
Judge search-result relevance for a last-30-days research tool.
Topic: {topic}
Query type: {query_type}
Score each item on this 0-3 scale:
- 0 = off-topic or clearly bad
- 1 = weak or tangential
- 2 = relevant and useful
- 3 = highly relevant, one of the best results
Return JSON only:
{{
"judgments": [
{{"id": "ITEM_ID", "grade": 0}}
]
}}
Items:
{chr(10).join(item_lines)}
""".strip()
def get_judgments(
*,
output_dir: Path,
slug: str,
topic: str,
query_type: str,
items: list[dict[str, Any]],
judge_model: str,
gemini_api_key: str | None,
) -> dict[str, int]:
cache_file = output_dir / "judgments" / f"{slug}.json"
cache_file.parent.mkdir(parents=True, exist_ok=True)
if cache_file.exists():
payload = json.loads(cache_file.read_text())
return {row["id"]: int(row["grade"]) for row in payload.get("judgments") or []}
if not gemini_api_key or not items:
return {}
payload = call_gemini_judge(gemini_api_key, judge_model, build_judge_prompt(topic, query_type, items))
cache_file.write_text(json.dumps(payload, indent=2))
return {row["id"]: int(row["grade"]) for row in payload.get("judgments") or []}
def create_eval_env() -> dict[str, str]:
config = envlib.get_config()
passthrough = {
"PATH": os.environ.get("PATH", ""),
"LANG": os.environ.get("LANG", "en_US.UTF-8"),
"LC_ALL": os.environ.get("LC_ALL", ""),
"TMPDIR": os.environ.get("TMPDIR", ""),
"PYTHONUTF8": "1",
"LAST30DAYS_CONFIG_DIR": "",
}
for key in (
"GOOGLE_API_KEY",
"GEMINI_API_KEY",
"GOOGLE_GENAI_API_KEY",
"OPENAI_API_KEY",
"XAI_API_KEY",
"SCRAPECREATORS_API_KEY",
"BSKY_HANDLE",
"BSKY_APP_PASSWORD",
"TRUTHSOCIAL_TOKEN",
"AUTH_TOKEN",
"CT0",
):
value = os.environ.get(key) or config.get(key)
if value:
passthrough[key] = value
return passthrough
def run_last30days(repo_dir: Path, topic: str, *, search: str, timeout_seconds: int, quick: bool, mock: bool, env: dict[str, str]) -> dict[str, Any]:
engine = repo_dir / "skills" / "last30days" / "scripts" / "last30days.py"
if not engine.exists():
engine = repo_dir / "scripts" / "last30days.py"
cmd = [sys.executable, str(engine), topic, "--emit=json"]
if search:
cmd.extend(["--search", search])
if quick:
cmd.append("--quick")
if mock:
cmd.append("--mock")
result = subprocess.run(
cmd,
cwd=repo_dir,
env=env,
capture_output=True,
text=True,
timeout=timeout_seconds,
check=False,
)
if result.returncode != 0:
raise RuntimeError(f"{repo_dir.name} failed for '{topic}' with exit {result.returncode}\n{result.stderr.strip()}")
return json.loads(result.stdout)
def create_worktree(rev: str) -> Path:
worktree_dir = Path(tempfile.mkdtemp(prefix="last30days-eval-"))
subprocess.run(
["git", "worktree", "add", "--detach", str(worktree_dir), rev],
cwd=REPO_ROOT,
check=True,
capture_output=True,
text=True,
)
return worktree_dir
def resolve_repo_dir(label: str) -> tuple[Path, bool]:
"""Resolve a benchmark label into a repo directory and whether it is temporary."""
if label == "WORKTREE":
return REPO_ROOT, False
return create_worktree(label), True
def remove_worktree(path: Path) -> None:
subprocess.run(
["git", "worktree", "remove", "--force", str(path)],
cwd=REPO_ROOT,
check=False,
capture_output=True,
text=True,
)
try:
os.rmdir(path)
except OSError:
pass
def summarize_topic(topic: str, query_type: str, baseline_report: dict[str, Any], candidate_report: dict[str, Any], judgments: dict[str, int], judged_pool: list[dict[str, Any]], limit: int) -> dict[str, Any]:
baseline_ranked = build_ranked_items(baseline_report, limit)
candidate_ranked = build_ranked_items(candidate_report, limit)
baseline_sets = source_sets(baseline_report, limit)
candidate_sets = source_sets(candidate_report, limit)
overall_left = set().union(*baseline_sets.values()) if baseline_sets else set()
overall_right = set().union(*candidate_sets.values()) if candidate_sets else set()
sources = sorted(set(baseline_sets) | set(candidate_sets))
return {
"topic": topic,
"query_type": query_type,
"baseline": {
"precision_at_5": precision_at_k(baseline_ranked, judgments, 5),
"ndcg_at_5": ndcg_at_k(baseline_ranked, judgments, 5, judged_pool),
"source_coverage_recall": source_coverage_recall(baseline_ranked, judged_pool, judgments),
},
"candidate": {
"precision_at_5": precision_at_k(candidate_ranked, judgments, 5),
"ndcg_at_5": ndcg_at_k(candidate_ranked, judgments, 5, judged_pool),
"source_coverage_recall": source_coverage_recall(candidate_ranked, judged_pool, judgments),
},
"stability": {
"overall_jaccard": jaccard(overall_left, overall_right),
"overall_retention_vs_baseline": retention(overall_left, overall_right),
"per_source": {
source: {
"baseline_count": len(baseline_sets.get(source, set())),
"candidate_count": len(candidate_sets.get(source, set())),
"jaccard": jaccard(baseline_sets.get(source, set()), candidate_sets.get(source, set())),
"retention_vs_baseline": retention(baseline_sets.get(source, set()), candidate_sets.get(source, set())),
}
for source in sources
},
},
}
def write_summary(output_dir: Path, baseline_label: str, candidate_label: str, summaries: list[dict[str, Any]]) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
payload = {
"generated_at": datetime.now().isoformat(timespec="seconds"),
"baseline": baseline_label,
"candidate": candidate_label,
"topics": summaries,
}
(output_dir / "metrics.json").write_text(json.dumps(payload, indent=2))
lines = [
"# Search Quality Evaluation",
"",
f"- Baseline: `{baseline_label}`",
f"- Candidate: `{candidate_label}`",
f"- Generated: {payload['generated_at']}",
"",
"| Topic | Base P@5 | Cand P@5 | Base nDCG@5 | Cand nDCG@5 | Jaccard | Retention |",
"|---|---:|---:|---:|---:|---:|---:|",
]
for row in summaries:
lines.append(
"| {topic} | {bp:.2f} | {cp:.2f} | {bn:.2f} | {cn:.2f} | {jac:.2f} | {ret:.2f} |".format(
topic=row["topic"],
bp=row["baseline"]["precision_at_5"],
cp=row["candidate"]["precision_at_5"],
bn=row["baseline"]["ndcg_at_5"],
cn=row["candidate"]["ndcg_at_5"],
jac=row["stability"]["overall_jaccard"],
ret=row["stability"]["overall_retention_vs_baseline"],
)
)
(output_dir / "summary.md").write_text("\n".join(lines) + "\n")
def write_failure_summary(
output_dir: Path,
baseline_label: str,
candidate_label: str,
summaries: list[dict[str, Any]],
failures: list[dict[str, Any]],
) -> None:
write_summary(output_dir, baseline_label, candidate_label, summaries)
metrics_path = output_dir / "metrics.json"
payload = json.loads(metrics_path.read_text()) if metrics_path.exists() else {
"generated_at": datetime.now().isoformat(timespec="seconds"),
"baseline": baseline_label,
"candidate": candidate_label,
"topics": [],
}
payload["failures"] = failures
metrics_path.write_text(json.dumps(payload, indent=2))
summary_path = output_dir / "summary.md"
lines = summary_path.read_text().splitlines() if summary_path.exists() else ["# Search Quality Evaluation", ""]
if failures:
lines.extend([
"",
"## Failures",
"",
])
for failure in failures:
lines.append(f"- `{failure['topic']}`: {failure['error']}")
summary_path.write_text("\n".join(lines).rstrip() + "\n")
def parse_topics_file(path: Path) -> list[tuple[str, str]]:
rows = json.loads(path.read_text())
return [(str(row["topic"]), str(row.get("query_type") or "general")) for row in rows]
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Compare two last30days revisions on ranked candidate quality")
parser.add_argument("--baseline", default="HEAD~1")
parser.add_argument("--candidate", default="WORKTREE")
parser.add_argument("--search", default=DEFAULT_SEARCH)
parser.add_argument("--output-dir", default="tmp/search-quality")
parser.add_argument("--judge-model", default=DEFAULT_JUDGE_MODEL)
parser.add_argument("--timeout", type=int, default=240)
parser.add_argument("--limit", type=int, default=20)
parser.add_argument("--mock", action="store_true")
parser.add_argument("--quick", action="store_true")
parser.add_argument("--topics-file")
return parser
def main() -> int:
args = build_parser().parse_args()
topics = parse_topics_file(Path(args.topics_file)) if args.topics_file else DEFAULT_TOPICS
output_dir = Path(args.output_dir).resolve()
config = envlib.get_config()
gemini_api_key = resolve_google_judge_api_key(config)
run_env = create_eval_env()
baseline_dir, baseline_temp = resolve_repo_dir(args.baseline)
candidate_dir, candidate_temp = resolve_repo_dir(args.candidate)
try:
summaries = []
failures = []
for topic, query_type in topics:
try:
baseline_report = run_last30days(
baseline_dir,
topic,
search=args.search,
timeout_seconds=args.timeout,
quick=args.quick,
mock=args.mock,
env=run_env,
)
candidate_report = run_last30days(
candidate_dir,
topic,
search=args.search,
timeout_seconds=args.timeout,
quick=args.quick,
mock=args.mock,
env=run_env,
)
judged_pool_map = {
item["key"]: item
for item in build_ranked_items(baseline_report, args.limit) + build_ranked_items(candidate_report, args.limit)
}
judged_pool = list(judged_pool_map.values())
judgments = get_judgments(
output_dir=output_dir,
slug="".join(char.lower() if char.isalnum() else "-" for char in topic).strip("-"),
topic=topic,
query_type=query_type,
items=judged_pool,
judge_model=args.judge_model,
gemini_api_key=gemini_api_key,
)
summaries.append(summarize_topic(topic, query_type, baseline_report, candidate_report, judgments, judged_pool, args.limit))
except Exception as exc:
failures.append({"topic": topic, "query_type": query_type, "error": str(exc)})
write_failure_summary(output_dir, args.baseline, args.candidate, summaries, failures)
finally:
if baseline_temp:
remove_worktree(baseline_dir)
if candidate_temp:
remove_worktree(candidate_dir)
result = {"output_dir": str(output_dir), "topics": len(topics), "failures": len(failures)}
print(json.dumps(result, indent=2))
return 1 if failures else 0
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
# ruff: noqa: E402
"""last30days CLI."""
from __future__ import annotations
import argparse
import atexit
import datetime
import json
import os
import re
import signal
import sys
import threading
from pathlib import Path
MIN_PYTHON = (3, 12)
def ensure_supported_python(version_info: tuple[int, int, int] | object | None = None) -> None:
if version_info is None:
version_info = sys.version_info
major, minor, micro = tuple(version_info[:3])
if (major, minor) >= MIN_PYTHON:
return
sys.stderr.write(
"last30days v3 requires Python 3.12+.\n"
f"Detected Python {major}.{minor}.{micro}.\n"
"Install and use python3.12 or python3.13, then rerun this command.\n"
)
raise SystemExit(1)
ensure_supported_python()
if os.name == "nt":
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8", errors="replace")
SCRIPT_DIR = Path(__file__).parent.resolve()
sys.path.insert(0, str(SCRIPT_DIR))
from lib import env, html_render, pipeline, render, schema, ui
_child_pids: set[int] = set()
_child_pids_lock = threading.Lock()
def register_child_pid(pid: int) -> None:
with _child_pids_lock:
_child_pids.add(pid)
def unregister_child_pid(pid: int) -> None:
with _child_pids_lock:
_child_pids.discard(pid)
def _cleanup_children() -> None:
with _child_pids_lock:
pids = list(_child_pids)
for pid in pids:
try:
if hasattr(os, "killpg"):
os.killpg(os.getpgid(pid), signal.SIGTERM)
else:
os.kill(pid, signal.SIGTERM)
except (ProcessLookupError, PermissionError, OSError):
continue
atexit.register(_cleanup_children)
def parse_search_flag(raw: str) -> list[str]:
sources = []
for source in raw.split(","):
source = source.strip().lower()
if not source:
continue
normalized = pipeline.SEARCH_ALIAS.get(source, source)
if normalized not in pipeline.MOCK_AVAILABLE_SOURCES:
raise SystemExit(f"Unknown search source: {source}")
if normalized not in sources:
sources.append(normalized)
if not sources:
raise SystemExit("--search requires at least one source.")
return sources
def slugify(value: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
return slug or "last30days"
def save_output(
report: schema.Report,
emit: str,
save_dir: str,
suffix: str = "",
synthesis_md: str | None = None,
topic_override: str | None = None,
rendered_content: str | None = None,
) -> Path:
from datetime import datetime
path = Path(save_dir).expanduser().resolve()
path.mkdir(parents=True, exist_ok=True)
slug = slugify(topic_override or report.topic)
extension = "json" if emit == "json" else "html" if emit == "html" else "md"
raw_label = "raw-html" if emit == "html" else "raw"
suffix_part = f"-{suffix}" if suffix else ""
out_path = path / f"{slug}-{raw_label}{suffix_part}.{extension}"
if out_path.exists():
out_path = path / f"{slug}-{raw_label}{suffix_part}-{datetime.now().strftime('%Y-%m-%d')}.{extension}"
# Markdown saves keep the complete debug artifact. JSON and HTML preserve
# their requested wire format so file extensions match their content.
if rendered_content is not None:
content = rendered_content
elif emit in {"json", "html"}:
content = emit_output(report, emit, synthesis_md=synthesis_md)
else:
content = render.render_full(report)
out_path.write_text(content, encoding="utf-8")
return out_path
def emit_output(
report: schema.Report,
emit: str,
fun_level: str = "medium",
save_path: str | None = None,
synthesis_md: str | None = None,
) -> str:
if emit == "json":
return json.dumps(schema.to_dict(report), indent=2, sort_keys=True)
if emit == "html":
return html_render.render_html(
report, fun_level=fun_level, save_path=save_path, synthesis_md=synthesis_md,
)
if emit in {"compact", "md"}:
return render.render_compact(report, fun_level=fun_level, save_path=save_path)
if emit == "context":
return render.render_context(report)
raise SystemExit(f"Unsupported emit mode: {emit}")
def emit_comparison_output(
entity_reports: list[tuple[str, schema.Report]],
emit: str,
fun_level: str = "medium",
save_path: str | None = None,
synthesis_md: str | None = None,
) -> str:
if emit == "json":
payload = {
"comparison": True,
"entities": [label for label, _ in entity_reports],
"reports": [
{"entity": label, "report": schema.to_dict(report)}
for label, report in entity_reports
],
}
return json.dumps(payload, indent=2, sort_keys=True)
if emit == "html":
return html_render.render_html_comparison(
entity_reports,
fun_level=fun_level,
save_path=save_path,
synthesis_md=synthesis_md,
)
if emit in {"compact", "md"}:
return render.render_comparison_multi(
entity_reports, fun_level=fun_level, save_path=save_path,
)
if emit == "context":
return render.render_comparison_multi_context(entity_reports)
raise SystemExit(f"Unsupported emit mode: {emit}")
def comparison_topic(entity_reports: list[tuple[str, schema.Report]]) -> str:
return " vs ".join(label for label, _ in entity_reports)
def compute_save_path_display(save_dir: str, topic: str, suffix: str, emit: str) -> str:
"""Compute the user-friendly save path string that will be shown in the footer.
Uses ~ when the saved file is under the user's home directory; otherwise
returns the absolute path.
"""
from pathlib import Path as _Path
path = _Path(save_dir).expanduser().resolve()
slug = slugify(topic)
extension = "json" if emit == "json" else "html" if emit == "html" else "md"
raw_label = "raw-html" if emit == "html" else "raw"
suffix_part = f"-{suffix}" if suffix else ""
raw = path / f"{slug}-{raw_label}{suffix_part}.{extension}"
try:
home = _Path.home().resolve()
relative = raw.relative_to(home)
return f"~/{relative.as_posix()}"
except ValueError:
return raw.as_posix()
def read_synthesis_file(path: str) -> str:
try:
return Path(path).expanduser().read_text(encoding="utf-8")
except OSError as exc:
sys.stderr.write(f"[last30days] Cannot read --synthesis-file: {exc}\n")
raise SystemExit(2)
def persist_report(report: schema.Report) -> dict[str, int]:
import store
store.init_db()
topic_row = store.add_topic(report.topic)
topic_id = topic_row["id"]
source_mode = ",".join(sorted(report.items_by_source)) or "v3"
run_id = store.record_run(topic_id, source_mode=source_mode, status="running")
try:
findings = store.findings_from_report(report)
counts = store.store_findings(run_id, topic_id, findings)
store.update_run(
run_id,
status="completed",
findings_new=counts["new"],
findings_updated=counts["updated"],
)
return counts
except Exception as exc:
store.update_run(run_id, status="failed", error_message=str(exc)[:500])
raise
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Research a topic across live social, market, and grounded web sources.")
parser.add_argument("topic", nargs="*", help="Research topic")
parser.add_argument("--emit", default="compact", choices=["compact", "json", "context", "md", "html"])
parser.add_argument("--search", help="Comma-separated source list")
parser.add_argument("--quick", action="store_true", help="Lower-latency retrieval profile")
parser.add_argument("--deep", action="store_true", help="Higher-recall retrieval profile")
parser.add_argument("--debug", action="store_true", help="Enable HTTP debug logging")
parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures")
parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability")
parser.add_argument("--save-dir", help="Optional directory for saving the rendered output")
parser.add_argument("--synthesis-file", help="Markdown synthesis to embed in --emit=html output")
parser.add_argument("--store", action="store_true", help="Persist ranked findings to the SQLite research store")
parser.add_argument("--x-handle", help="X handle for targeted supplemental search")
parser.add_argument("--x-related", help="Comma-separated related X handles (searched with lower weight)")
parser.add_argument("--web-backend", default="auto",
choices=["auto", "brave", "exa", "serper", "parallel", "none"],
help="Web search backend (default: auto, tries Brave then Exa then Serper then Parallel)")
parser.add_argument("--deep-research", action="store_true",
help="Use Perplexity Deep Research (~$0.90/query) for in-depth analysis. Requires OPENROUTER_API_KEY.")
parser.add_argument("--plan", help="JSON query plan (skips internal LLM planner). Can be a JSON string or a file path.")
parser.add_argument("--save-suffix", help="Suffix for saved output filename (e.g., 'gemini' → kanye-west-raw-gemini.md)")
parser.add_argument("--subreddits", help="Comma-separated subreddit names to search (e.g., SaaS,Entrepreneur)")
parser.add_argument("--tiktok-hashtags", help="Comma-separated TikTok hashtags without # (e.g., tella,screenrecording)")
parser.add_argument("--tiktok-creators", help="Comma-separated TikTok creator handles (e.g., TellaHQ,taborplace)")
parser.add_argument("--ig-creators", help="Comma-separated Instagram creator handles (e.g., tella.tv,laborstories)")
parser.add_argument(
"--days",
"--lookback-days",
dest="lookback_days",
type=int,
default=30,
help="Number of days to look back for research (default: 30, watchlist uses 90)",
)
parser.add_argument("--auto-resolve", action="store_true",
help="Use web search to discover subreddits/handles before planning (for platforms without WebSearch)")
parser.add_argument("--github-user", help="GitHub username for person-mode search (e.g., steipete)")
parser.add_argument("--github-repo", help="Comma-separated owner/repo for project-mode search (e.g., openclaw/openclaw,paperclipai/paperclip)")
parser.add_argument(
"--competitors",
nargs="?",
const=2,
type=int,
default=None,
metavar="N",
help="Auto-discover N competitor entities and fan out last30days across all of them as a comparison (default N=2 → 3-way: original + 2 peers; range 1..6). Use --competitors-list to override discovery.",
)
parser.add_argument(
"--competitors-list",
dest="competitors_list",
help="Comma-separated competitor entities to skip discovery (e.g., 'Anthropic,xAI,Google Gemini'). Implies --competitors.",
)
parser.add_argument(
"--polymarket-keywords",
dest="polymarket_keywords",
help=(
"Comma-separated keywords that Polymarket market titles must match "
"to be included. Use for ambiguous single-token topics like 'Warriors' "
"(nba,gsw,golden-state) to filter out Glasgow Warriors rugby, Honor "
"of Kings Rogue Warriors, etc. When omitted, Polymarket returns all "
"matching markets — so expect cross-entity noise on generic topics."
),
)
parser.add_argument(
"--competitors-plan",
dest="competitors_plan",
help=(
"JSON mapping of per-entity Step 0.55 targeting for competitor / vs-mode "
"sub-runs. Schema: {entity_name: {x_handle?, x_related?, subreddits?, "
"github_user?, github_repos?, context?}}. Accepts inline JSON or a file "
"path. Implies --competitors. Preferred over --competitors-list when the "
"hosting model has already resolved per-entity handles and subs."
),
)
return parser
def parse_competitors_plan(raw: str | None) -> dict[str, dict]:
"""Parse a --competitors-plan argument into a {entity_name_lower: plan_entry} dict.
Accepts inline JSON or a file path (matches --plan). Returns {} on None/empty.
Validation: top-level must be a dict; each value must be a dict. Unknown fields
in entry values log a warning but do not abort. Invalid JSON or non-dict shape
raises SystemExit(2) with a clear stderr message.
"""
if not raw:
return {}
plan_str = raw
if os.path.isfile(plan_str):
try:
plan_str = open(plan_str).read()
except OSError as exc:
sys.stderr.write(f"[CompetitorsPlan] Cannot read plan file: {exc}\n")
raise SystemExit(2)
try:
parsed = json.loads(plan_str)
except json.JSONDecodeError as exc:
sys.stderr.write(f"[CompetitorsPlan] Invalid JSON: {exc}\n")
raise SystemExit(2)
if not isinstance(parsed, dict):
sys.stderr.write(
f"[CompetitorsPlan] Top-level must be a dict of "
f"{{entity: {{targeting}}}}, got {type(parsed).__name__}\n"
)
raise SystemExit(2)
known_fields = {
"x_handle", "x_related", "subreddits",
"github_user", "github_repos", "context",
}
normalized: dict[str, dict] = {}
for entity, entry in parsed.items():
if not isinstance(entry, dict):
sys.stderr.write(
f"[CompetitorsPlan] Entry for {entity!r} must be a dict, "
f"got {type(entry).__name__}; skipping.\n"
)
continue
unknown = set(entry.keys()) - known_fields
if unknown:
sys.stderr.write(
f"[CompetitorsPlan] Unknown fields in {entity!r}: "
f"{sorted(unknown)}; ignoring.\n"
)
normalized[entity.strip().lower()] = {
k: v for k, v in entry.items() if k in known_fields
}
return normalized
def subrun_kwargs_for(
entity: str,
plan_entry: dict,
*,
resolved: dict,
) -> dict:
"""Build an explicit per-entity kwargs dict for pipeline.run().
Plan values win over auto_resolve values. Returns keys for all per-entity
targeting flags so callers never fall through to closure defaults.
This helper is the single source of truth for sub-run kwargs — main-topic
flags can only leak if a caller bypasses it.
"""
def _choose(plan_key: str, resolved_key: str | None = None):
if plan_key in plan_entry and plan_entry[plan_key]:
return plan_entry[plan_key]
if resolved_key is not None and resolved.get(resolved_key):
return resolved[resolved_key]
return None
x_handle = _choose("x_handle", "x_handle")
if isinstance(x_handle, str):
x_handle = x_handle.lstrip("@") or None
subreddits = _choose("subreddits", "subreddits")
if isinstance(subreddits, list):
subreddits = [s.strip().removeprefix("r/") for s in subreddits if s.strip()] or None
x_related = plan_entry.get("x_related")
if isinstance(x_related, list):
x_related = [h.strip().lstrip("@") for h in x_related if h.strip()] or None
else:
x_related = None
github_user = _choose("github_user", "github_user")
if isinstance(github_user, str):
github_user = github_user.lstrip("@").lower() or None
github_repos = _choose("github_repos", "github_repos")
if isinstance(github_repos, list):
github_repos = [r.strip() for r in github_repos if r.strip() and "/" in r.strip()] or None
context = plan_entry.get("context") or resolved.get("context") or ""
return {
"x_handle": x_handle,
"x_related": x_related,
"subreddits": subreddits,
"github_user": github_user,
"github_repos": github_repos,
"_context": context,
}
COMPETITORS_MIN = 1
COMPETITORS_MAX = 6
COMPETITORS_DEFAULT = 2
def resolve_competitors_args(args: argparse.Namespace) -> tuple[bool, int, list[str]]:
"""Normalize --competitors / --competitors-list into (enabled, count, explicit_list).
- (False, 0, []) when neither flag is set.
- An explicit list always wins; count is derived from list length.
- A numeric count outside [1, 6] is clamped with a stderr warning.
- count <= 0 (explicit) raises SystemExit(2).
"""
explicit_list: list[str] = []
list_flag_provided = args.competitors_list is not None
if list_flag_provided:
explicit_list = [
entity.strip()
for entity in args.competitors_list.split(",")
if entity.strip()
]
if not explicit_list:
sys.stderr.write("[Competitors] --competitors-list is empty.\n")
raise SystemExit(2)
competitors_flag = args.competitors
list_present = bool(explicit_list)
flag_present = competitors_flag is not None
if not list_present and not flag_present:
return False, 0, []
if list_present:
count = len(explicit_list)
if flag_present and competitors_flag != count:
sys.stderr.write(
f"[Competitors] --competitors={competitors_flag} ignored; using "
f"{count} entries from --competitors-list.\n"
)
if count > COMPETITORS_MAX:
sys.stderr.write(
f"[Competitors] --competitors-list has {count} entries, clamping to {COMPETITORS_MAX}.\n"
)
explicit_list = explicit_list[:COMPETITORS_MAX]
count = COMPETITORS_MAX
return True, count, explicit_list
# flag_present, no explicit list
count = competitors_flag
if count < COMPETITORS_MIN:
sys.stderr.write(
f"[Competitors] --competitors must be >= {COMPETITORS_MIN} (got {count}).\n"
)
raise SystemExit(2)
if count > COMPETITORS_MAX:
sys.stderr.write(
f"[Competitors] --competitors={count} exceeds max {COMPETITORS_MAX}; clamping.\n"
)
count = COMPETITORS_MAX
return True, count, []
def _missing_sources_for_promo(diag: dict[str, object]) -> str | None:
available = set(diag.get("available_sources") or [])
missing = []
if "reddit" not in available:
missing.append("reddit")
if "x" not in available:
missing.append("x")
if "grounding" not in available:
missing.append("web")
if not missing:
return None
if "reddit" in missing and "x" in missing:
return "both"
return missing[0]
def _show_runtime_ui(
report: schema.Report,
progress: ui.ProgressDisplay,
diag: dict[str, object],
suppress_web_promo: bool = False,
) -> None:
counts = {source: len(items) for source, items in report.items_by_source.items()}
display_sources = list(
dict.fromkeys(
[
*report.query_plan.source_weights.keys(),
*report.items_by_source.keys(),
*report.errors_by_source.keys(),
]
)
)
progress.end_processing()
progress.show_complete(
source_counts=counts,
display_sources=display_sources,
)
promo = _missing_sources_for_promo(diag)
# The `web` promo nudges users to set BRAVE_API_KEY / SERPER_API_KEY, which
# is wrong advice when a hosting reasoning model (Claude Code, Codex,
# Hermes, Gemini) is driving — those already have WebSearch and can
# pre-resolve Step 0.55 themselves. Suppress the web promo when a hosting
# model signal is present (--plan or --competitors-plan was passed).
if promo:
if suppress_web_promo and promo == "web":
return
if suppress_web_promo and promo == "both":
# "both" means reddit + web both missing; still nudge reddit but
# skip the web line. show_promo has a per-source variant.
progress.show_promo("reddit", diag=diag)
return
progress.show_promo(promo, diag=diag)
def _write_last_run(topic: str, report: "schema.Report") -> None:
try:
if env.CONFIG_DIR is None:
return
target = env.CONFIG_DIR
target.mkdir(parents=True, exist_ok=True)
counts = {source: len(items) for source, items in report.items_by_source.items()}
payload = {
"topic": topic,
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"sources": counts,
"total": sum(counts.values()),
}
(target / "last-run.json").write_text(json.dumps(payload, indent=2))
except Exception:
pass
def main() -> int:
parser = build_parser()
# Use parse_known_args so setup sub-flags (--device-auth, --github,
# --openclaw) pass through without argparse hard-exiting.
args, extra_argv = parser.parse_known_args()
if args.debug:
os.environ["LAST30DAYS_DEBUG"] = "1"
config = env.get_config()
# Surface SSH-routing config as an env var so library modules (e.g.
# youtube_yt) can read it without taking a config dependency. This
# routes yt-dlp through `ssh <host>` to bypass YouTube's bot-wall on
# datacenter IPs (see lib/youtube_yt.py for details).
if config.get("LAST30DAYS_YOUTUBE_SSH_HOST") and "LAST30DAYS_YOUTUBE_SSH_HOST" not in os.environ:
os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = config["LAST30DAYS_YOUTUBE_SSH_HOST"]
# Handle setup subcommand
topic = " ".join(args.topic).strip()
if topic.lower() == "setup":
from lib import setup_wizard
if "--openclaw" in extra_argv:
results = setup_wizard.run_openclaw_setup(config)
print(json.dumps(results))
return 0
if "--github" in extra_argv:
results = setup_wizard.run_github_auth()
print(json.dumps(results))
return 0
if "--device-auth" in extra_argv:
results = setup_wizard.run_full_device_auth()
print(json.dumps(results))
return 0
sys.stderr.write("Running auto-setup...\n")
results = setup_wizard.run_auto_setup(config)
from_browser = "auto"
if results.get("cookies_found"):
first_browser = next(iter(results["cookies_found"].values()))
from_browser = first_browser
setup_wizard.write_setup_config(env.CONFIG_FILE, from_browser=from_browser)
results["env_written"] = True
sys.stderr.write(setup_wizard.get_setup_status_text(results) + "\n")
return 0
requested_sources = parse_search_flag(args.search) if args.search else None
diag = pipeline.diagnose(config, requested_sources)
if args.diagnose:
print(json.dumps(diag, indent=2, sort_keys=True))
return 0
if not topic:
parser.print_usage(sys.stderr)
return 2
synthesis_md = None
if args.synthesis_file:
if args.emit == "html":
synthesis_md = read_synthesis_file(args.synthesis_file)
else:
sys.stderr.write("[last30days] Warning: --synthesis-file is only used with --emit=html; ignoring.\n")
if not os.environ.get("LAST30DAYS_SKIP_PREFLIGHT"):
from lib import preflight
refuse_msg = preflight.check_class_1_trap(topic)
if refuse_msg:
sys.stderr.write(refuse_msg)
return 2
progress = ui.ProgressDisplay(topic, show_banner=True)
progress.start_processing()
depth = "deep" if args.deep else "quick" if args.quick else "default"
try:
x_related = [h.strip() for h in args.x_related.split(",") if h.strip()] if args.x_related else None
subreddits = [s.strip().removeprefix("r/") for s in args.subreddits.split(",") if s.strip()] if args.subreddits else None
tiktok_hashtags = [h.strip().lstrip("#") for h in args.tiktok_hashtags.split(",") if h.strip()] if args.tiktok_hashtags else None
tiktok_creators = [c.strip().lstrip("@") for c in args.tiktok_creators.split(",") if c.strip()] if args.tiktok_creators else None
ig_creators = [c.strip().lstrip("@") for c in args.ig_creators.split(",") if c.strip()] if args.ig_creators else None
# Parse external plan if provided via --plan flag
external_plan = None
if args.plan:
import json as _json
plan_str = args.plan
if os.path.isfile(plan_str):
plan_str = open(plan_str).read()
try:
external_plan = _json.loads(plan_str)
except _json.JSONDecodeError as exc:
sys.stderr.write(f"[Planner] Invalid --plan JSON: {exc}\n")
# Auto-resolve: use web search to discover subreddits/handles before planning.
# This is the engine-side equivalent of SKILL.md Steps 0.55/0.75 for platforms
# without WebSearch (OpenClaw, Codex, raw CLI).
repos_from_auto_resolve = False
if args.auto_resolve and not external_plan:
from lib import resolve
resolution = resolve.auto_resolve(topic, config)
if resolution.get("subreddits") and not subreddits:
subreddits = resolution["subreddits"]
sys.stderr.write(f"[AutoResolve] Subreddits: {', '.join(subreddits)}\n")
if resolution.get("x_handle") and not args.x_handle:
args.x_handle = resolution["x_handle"]
sys.stderr.write(f"[AutoResolve] X handle: @{args.x_handle}\n")
if resolution.get("github_user") and not args.github_user:
args.github_user = resolution["github_user"]
sys.stderr.write(f"[AutoResolve] GitHub user: @{args.github_user}\n")
if resolution.get("github_repos") and not args.github_repo:
args.github_repo = ",".join(resolution["github_repos"])
# auto_resolve already canonicalized via canonicalize_github_repos(cap=5);
# mark so we don't re-canonicalize below and clobber its relevance order.
repos_from_auto_resolve = True
sys.stderr.write(f"[AutoResolve] GitHub repos: {args.github_repo}\n")
if resolution.get("context"):
# Inject context into external_plan metadata for the planner to use
if not external_plan:
external_plan = None # planner will use its own, but with context
# Store context for the planner prompt injection
config["_auto_resolve_context"] = resolution["context"]
sys.stderr.write(f"[AutoResolve] Context: {resolution['context'][:80]}...\n")
github_user = args.github_user.lstrip("@").lower() if args.github_user else None
github_repos = [r.strip() for r in args.github_repo.split(",") if r.strip() and "/" in r.strip()] if args.github_repo else None
# Only canonicalize when repos came from a user-supplied --github-repo flag.
# When repos_from_auto_resolve is True, auto_resolve already ran
# canonicalize_github_repos(cap=5) and ranked by relevance; re-running here
# with cap=None can re-sort by topic-slug match and lose that ordering.
if github_repos and not repos_from_auto_resolve:
from lib import resolve as resolve_lib
original_github_repos = github_repos[:]
github_repos = resolve_lib.canonicalize_github_repos(topic, github_repos, cap=None)
if github_repos != original_github_repos:
sys.stderr.write(
"[GitHub] Canonicalized repos: "
f"{','.join(original_github_repos)} -> {','.join(github_repos)}\n"
)
# --deep-research: auto-enable perplexity source and set deep flag
if args.deep_research:
if not config.get("OPENROUTER_API_KEY"):
print("Error: --deep-research requires OPENROUTER_API_KEY", file=sys.stderr)
sys.exit(1)
config["_deep_research"] = True
# Auto-enable perplexity in INCLUDE_SOURCES
include = config.get("INCLUDE_SOURCES") or ""
if "perplexity" not in include.lower():
config["INCLUDE_SOURCES"] = f"{include},perplexity" if include else "perplexity"
comp_enabled, comp_count, comp_explicit = resolve_competitors_args(args)
comp_plan = parse_competitors_plan(args.competitors_plan)
# Polymarket disambiguation: if user passed --polymarket-keywords,
# store on config so the polymarket adapter can filter matches.
if args.polymarket_keywords:
keywords = [
k.strip().lower()
for k in args.polymarket_keywords.split(",")
if k.strip()
]
if keywords:
config["_polymarket_keywords"] = keywords
# vs-mode: if the topic string contains " vs " / " versus " and the
# planner can split it into >=2 entities, route through the same
# N-pass fanout path as --competitors. The first entity becomes the
# main topic; remaining entities become the competitor list. User's
# outer --x-handle / --subreddits apply to the first entity unless
# --competitors-plan covers it.
from lib import planner as _planner
vs_entities = _planner._comparison_entities(topic)
if len(vs_entities) >= 2 and not comp_enabled:
topic = vs_entities[0]
comp_enabled = True
comp_count = len(vs_entities) - 1
comp_explicit = vs_entities[1:]
sys.stderr.write(
f"[Competitors] vs-mode: routing to N-pass fanout: "
f"{' vs '.join(vs_entities)}\n"
)
def _main_runner() -> schema.Report:
r = pipeline.run(
topic=topic,
config=config,
depth=depth,
requested_sources=requested_sources,
mock=args.mock,
x_handle=args.x_handle,
x_related=x_related,
web_backend=args.web_backend,
external_plan=external_plan,
subreddits=subreddits,
tiktok_hashtags=tiktok_hashtags,
tiktok_creators=tiktok_creators,
ig_creators=ig_creators,
lookback_days=args.lookback_days,
github_user=github_user,
github_repos=github_repos,
)
r.artifacts["resolved"] = {
"entity": topic,
"x_handle": (args.x_handle or "").lstrip("@"),
"subreddits": list(subreddits or []),
"github_user": (github_user or ""),
"github_repos": list(github_repos or []),
"context": config.get("_auto_resolve_context", "") or "",
}
return r
if comp_enabled:
from lib import competitors as competitors_mod
from lib import fanout, resolve as resolve_mod
if comp_explicit:
discovered = comp_explicit
else:
if not resolve_mod._has_backend(config) and not args.mock:
sys.stderr.write(
"[Competitors] Cannot auto-discover peers without help.\n"
"\n"
"RECOMMENDED PATH (hosting reasoning models — Claude Code, Codex, "
"Hermes, Gemini, any agent with a WebSearch tool): YOU have "
"WebSearch. Use it to run full Step 0.55 per entity, then invoke "
"the engine with a vs-topic plus --competitors-plan:\n"
" 1. WebSearch for '{topic} competitors' or '{topic} alternatives'.\n"
" 2. For each peer, WebSearch for handles/subs/github (Step 0.55).\n"
" 3. Re-invoke: /last30days '{topic} vs {peer1} vs {peer2}' "
"--competitors-plan '{\"Peer1\":{\"x_handle\":\"h1\",\"subreddits\":"
"[\"s1\"],...},\"Peer2\":{...}}'.\n"
"See SKILL.md 'Competitor mode' for the full protocol.\n"
"\n"
"HEADLESS / CRON PATH (no hosting model available): set "
"BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / PARALLEL_API_KEY / "
"OPENROUTER_API_KEY and re-run.\n"
"\n"
"MINIMUM ESCAPE HATCH: pass --competitors-list 'A,B,C' to skip "
"discovery. Without --competitors-plan, peer sub-runs fall back to "
"planner defaults and produce visibly thinner data than the main.\n"
)
return 2
discovered = competitors_mod.discover_competitors(
topic, comp_count, config, lookback_days=args.lookback_days,
)
if not discovered:
sys.stderr.write(
f"[Competitors] No peers discovered for {topic!r}; aborting "
"comparison run. Pass --competitors-list to override.\n"
)
return 2
sys.stderr.write(
f"[Competitors] Comparing: {topic} vs " + " vs ".join(discovered) + "\n"
)
def _competitor_runner(entity: str) -> schema.Report:
# Deep-copy config so per-entity auto_resolve context does not
# leak across sub-runs. Each sub-run writes its own
# `_auto_resolve_context` into its local config copy.
entity_config = dict(config)
plan_entry = comp_plan.get(entity.strip().lower(), {})
resolved = {
"entity": entity,
"x_handle": "",
"subreddits": [],
"github_user": "",
"github_repos": [],
"context": "",
}
# Skip engine-internal auto_resolve when the hosting model
# pre-resolved via --competitors-plan (saves a redundant
# round-trip and makes per-entity Step 0.55 purely
# hosting-model-driven).
plan_covers_fully = bool(plan_entry.get("x_handle")) and bool(
plan_entry.get("subreddits")
)
if (
not args.mock
and not plan_covers_fully
and resolve_mod._has_backend(entity_config)
):
try:
r = resolve_mod.auto_resolve(entity, entity_config)
except Exception as exc:
sys.stderr.write(
f"[Competitors] auto_resolve failed for {entity!r}: "
f"{type(exc).__name__}: {exc}\n"
)
r = {}
resolved["x_handle"] = r.get("x_handle", "") or ""
resolved["subreddits"] = list(r.get("subreddits") or [])
resolved["github_user"] = r.get("github_user", "") or ""
resolved["github_repos"] = list(r.get("github_repos") or [])
resolved["context"] = r.get("context", "") or ""
kwargs = subrun_kwargs_for(entity, plan_entry, resolved=resolved)
# Record effective per-entity targeting for the Resolved block.
resolved_effective = {
"entity": entity,
"x_handle": kwargs["x_handle"] or "",
"subreddits": kwargs["subreddits"] or [],
"github_user": kwargs["github_user"] or "",
"github_repos": kwargs["github_repos"] or [],
"context": kwargs["_context"],
}
if kwargs["_context"]:
entity_config["_auto_resolve_context"] = kwargs["_context"]
sys.stderr.write(
f"[Competitors] {entity}: "
f"x=@{resolved_effective['x_handle'] or '-'} "
f"subs={len(resolved_effective['subreddits'])} "
f"gh={resolved_effective['github_user'] or '-'} "
f"({'plan' if plan_entry else 'auto'})\n"
)
report = pipeline.run(
topic=entity,
config=entity_config,
depth=depth,
requested_sources=requested_sources,
mock=args.mock,
x_handle=kwargs["x_handle"],
x_related=kwargs["x_related"],
subreddits=kwargs["subreddits"],
github_user=kwargs["github_user"],
github_repos=kwargs["github_repos"],
web_backend=args.web_backend,
lookback_days=args.lookback_days,
internal_subrun=True,
)
report.artifacts["resolved"] = resolved_effective
return report
entity_reports = fanout.run_competitor_fanout(
main_topic=topic,
main_runner=_main_runner,
competitors=discovered,
competitor_runner=_competitor_runner,
)
if len(entity_reports) < 2:
progress.end_processing()
sys.stderr.write(
f"[Competitors] Fewer than 2 sub-runs survived ({len(entity_reports)}); "
"cannot render a comparison. Re-run without --competitors or check the "
"warnings above.\n"
)
return 1
report = entity_reports[0][1]
else:
entity_reports = None
report = _main_runner()
except Exception as exc:
progress.end_processing()
progress.show_error(str(exc))
raise
_show_runtime_ui(
report, progress, diag,
suppress_web_promo=bool(external_plan or comp_plan),
)
_write_last_run(topic, report)
# LAST30DAYS_STORE env var = persistence default-on. Read both os.environ
# (for shell-exported users) and config (for users who set it in
# ~/.config/last30days/.env, which env.py loads but does not propagate
# to os.environ). Mirrors the LAST30DAYS_DEBUG / LAST30DAYS_SKIP_PREFLIGHT
# convention; env-var or config wins, with `--store` flag still working.
_store_env = (
os.environ.get("LAST30DAYS_STORE")
or config.get("LAST30DAYS_STORE")
or ""
).lower()
if args.store or _store_env in ("1", "true", "yes"):
counts = persist_report(report)
sys.stderr.write(
f"[last30days] Stored {counts['new']} new, {counts['updated']} updated findings\n"
)
sys.stderr.flush()
# Show quality nudge if applicable
try:
from lib import quality_nudge
# Populate transcript-fetch ratio so quality_nudge can detect the
# degraded-YouTube failure mode (videos returned but transcripts
# silently failed - typically a stale yt-dlp binary).
youtube_items = report.items_by_source.get("youtube") or []
instagram_items = report.items_by_source.get("instagram") or []
research_results = {
"youtube_videos_count": len(youtube_items),
"youtube_transcripts_count": sum(
1 for it in youtube_items
if (it.metadata.get("transcript_highlights") or it.metadata.get("transcript_snippet"))
),
"youtube_error": report.errors_by_source.get("youtube"),
"x_error": report.errors_by_source.get("x"),
# Captions-disabled videos can never produce a transcript regardless
# of yt-dlp version; subtract them from the degraded-ratio
# denominator so a single uploader-disabled video does not trip the
# "stale yt-dlp" nudge.
"youtube_captions_disabled_count": sum(
1 for it in youtube_items if it.metadata.get("captions_disabled")
),
# Track Instagram returned-zero-items so quality_nudge can detect
# the silent-failure case (SC configured but the v2 reels endpoint
# 500'd through both the original query and the hashtag retry).
"instagram_items_count": len(instagram_items),
}
quality = quality_nudge.compute_quality_score(config, research_results)
if quality.get("nudge_text"):
sys.stderr.write(f"\n{quality['nudge_text']}\n")
sys.stderr.flush()
except Exception:
pass
fun_level = config.get("FUN_LEVEL", "medium").lower()
# Comparison HTML is the one case where the saved file's title and content
# have to be overridden away from the leading entity's report. Compute the
# gate once so the footer-display and save-output paths can't disagree.
is_comparison_html = bool(entity_reports) and args.emit == "html"
footer_save_path = None
if args.save_dir:
save_topic_for_display = comparison_topic(entity_reports) if is_comparison_html else report.topic
footer_save_path = compute_save_path_display(
args.save_dir, save_topic_for_display, args.save_suffix or "", args.emit
)
# Signal to render_compact whether pre-research flags were supplied.
# Used to emit a Pre-Research Status warning when the model skipped
# Step 0.5 / 0.55 and invoked the engine bare on an eligible topic.
pre_research_flags_present = bool(
args.x_handle
or args.github_user
or args.subreddits
or args.plan
or args.auto_resolve
or args.tiktok_creators
or args.ig_creators
)
report.artifacts["pre_research_flags_present"] = pre_research_flags_present
if entity_reports:
rendered = emit_comparison_output(
entity_reports,
args.emit,
fun_level=fun_level,
save_path=footer_save_path,
synthesis_md=synthesis_md,
)
else:
rendered = emit_output(
report,
args.emit,
fun_level=fun_level,
save_path=footer_save_path,
synthesis_md=synthesis_md,
)
if args.save_dir:
# Save the main topic's raw file (single-entity or comparison main).
save_path = save_output(
report,
args.emit,
args.save_dir,
suffix=args.save_suffix or "",
synthesis_md=synthesis_md,
topic_override=comparison_topic(entity_reports) if is_comparison_html else None,
rendered_content=rendered if is_comparison_html else None,
)
sys.stderr.write(f"[last30days] Saved output to {save_path}\n")
# Competitor / vs-mode: also save a per-entity raw file for each peer.
# Matches historical vs-mode behavior (N passes → N save files).
if entity_reports and len(entity_reports) > 1:
for label, entity_report in entity_reports[1:]:
peer_path = save_output(
entity_report, args.emit, args.save_dir,
suffix=args.save_suffix or "",
synthesis_md=synthesis_md,
)
sys.stderr.write(f"[last30days] Saved output to {peer_path}\n")
sys.stderr.flush()
print(rendered)
return 0
if __name__ == "__main__":
raise SystemExit(main())
# last30days library modules
"""Bird X search client for the v3.0.0 last30days pipeline.
Uses a vendored subset of @steipete/bird v0.8.0 (MIT License) to search X
via Twitter's GraphQL API. No external `bird` CLI binary needed - just Node.js.
See scripts/lib/vendor/bird-search/package.json for authoritative version.
"""
import json
import os
import shutil
import sys
import time
from pathlib import Path
from . import http, log, subproc
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from .relevance import token_overlap_relevance as _compute_relevance
# How many times to retry the bird-search subprocess when stdout is non-JSON
# (typically an HTML anti-bot interstitial from Twitter's edge).
MAX_JSON_DECODE_RETRIES = 2
JSON_DECODE_RETRY_DELAY = 5.0 # seconds between retry attempts
def _first_of(*values):
"""Return first value that is not None."""
for v in values:
if v is not None:
return v
return None
# Path to the vendored bird-search wrapper
_BIRD_SEARCH_MJS = Path(__file__).parent / "vendor" / "bird-search" / "bird-search.mjs"
# Depth configurations: number of results to request
DEPTH_CONFIG = {
"quick": 12,
"default": 30,
"deep": 60,
}
# Module-level credentials injected from .env config
_credentials: Dict[str, str] = {}
def set_credentials(auth_token: Optional[str], ct0: Optional[str]):
"""Inject AUTH_TOKEN/CT0 from .env config so Node subprocesses can use them."""
if auth_token:
_credentials['AUTH_TOKEN'] = auth_token
if ct0:
_credentials['CT0'] = ct0
def _has_injected_credentials() -> bool:
"""Return True when both X session cookies were injected from config."""
return bool(_credentials.get('AUTH_TOKEN') and _credentials.get('CT0'))
def _has_process_credentials() -> bool:
"""Return True when AUTH_TOKEN/CT0 are present in process env."""
return bool(os.environ.get("AUTH_TOKEN") and os.environ.get("CT0"))
def _subprocess_env() -> Dict[str, str]:
"""Build env dict for Node subprocesses, merging injected credentials."""
env = os.environ.copy()
env.update(_credentials)
# Hard-disable browser-cookie fallback so normal pipeline runs never hit
# Safari/Chrome Keychain prompts during source detection or search.
env["BIRD_DISABLE_BROWSER_COOKIES"] = "1"
return env
def _log(msg: str):
log.source_log("Bird", msg, tty_only=False)
def _extract_core_subject(topic: str) -> str:
"""Extract core subject from verbose query for X search.
X search is literal keyword AND matching — all words must appear.
Aggressively strip question/meta/research words to keep only the
core product/concept name (max 5 words).
"""
from .query import extract_core_subject
return extract_core_subject(topic, max_words=5, strip_suffixes=True)
def is_bird_installed() -> bool:
"""Check if vendored Bird search module is available.
Returns:
True if bird-search.mjs exists and Node.js is in PATH.
"""
if not _BIRD_SEARCH_MJS.exists():
return False
return shutil.which("node") is not None
def is_bird_authenticated() -> Optional[str]:
"""Check if explicit X credentials are available.
Returns:
Auth source string if authenticated, None otherwise.
"""
if not is_bird_installed():
return None
if _has_injected_credentials():
return "env AUTH_TOKEN"
if _has_process_credentials():
return "env AUTH_TOKEN"
return None
def check_npm_available() -> bool:
"""Check if npm is available (kept for API compatibility).
Returns:
True if 'npm' command is available in PATH, False otherwise.
"""
return shutil.which("npm") is not None
def install_bird() -> Tuple[bool, str]:
"""No-op. Bird search is vendored in v3.0.0, no installation needed.
Returns:
Tuple of (success, message).
"""
if is_bird_installed():
return True, "Bird search is bundled with /last30days v3.0.0 - no installation needed."
if not shutil.which("node"):
return False, "Node.js 22+ is required for X search. Install Node.js first."
return False, f"Vendored bird-search.mjs not found at {_BIRD_SEARCH_MJS}"
def get_bird_status() -> Dict[str, Any]:
"""Get comprehensive Bird search status.
Returns:
Dict with keys: installed, authenticated, username, can_install
"""
installed = is_bird_installed()
auth_source = is_bird_authenticated() if installed else None
return {
"installed": installed,
"authenticated": auth_source is not None,
"username": auth_source, # Now returns auth source (e.g., "Safari", "env AUTH_TOKEN")
"can_install": True, # Always vendored in v3.0.0
}
def _invoke_bird_subprocess(query: str, count: int, timeout: int):
"""Invoke the vendored bird-search.mjs subprocess once.
Returns (result, error_dict). If error_dict is non-None, treat it as the
final result and do not retry — those errors are terminal (timeout,
spawn failure). If error_dict is None, the subprocess ran to completion
and `result` is the SubprocResult; the caller decides whether to retry
based on the result.stdout content.
"""
cmd = [
"node", str(_BIRD_SEARCH_MJS),
query,
"--count", str(count),
"--json",
]
pid_holder: list[int] = []
def _register(pid: int) -> None:
pid_holder.append(pid)
try:
from last30days import register_child_pid
register_child_pid(pid)
except ImportError:
pass
try:
result = subproc.run_with_timeout(
cmd,
timeout=timeout,
env=_subprocess_env(),
on_pid=_register,
)
except subproc.SubprocTimeout:
return None, {"error": f"Search timed out after {timeout}s", "items": []}
except Exception as e:
return None, {"error": str(e), "items": []}
finally:
if pid_holder:
try:
from last30days import unregister_child_pid
unregister_child_pid(pid_holder[0])
except Exception:
pass
return result, None
def _run_bird_search(query: str, count: int, timeout: int) -> Dict[str, Any]:
"""Run a search using the vendored bird-search.mjs module.
Retries the subprocess on JSON-decode failure (typically a Twitter
anti-bot HTML interstitial in stdout) up to MAX_JSON_DECODE_RETRIES
times with JSON_DECODE_RETRY_DELAY seconds between attempts. Terminal
errors (subprocess timeout, non-zero return code) are returned
immediately without retry.
Args:
query: Full search query string (including since: filter)
count: Number of results to request
timeout: Timeout in seconds (per attempt)
Returns:
Raw Bird JSON response or error dict.
"""
last_decode_error: Optional[str] = None
for attempt in range(MAX_JSON_DECODE_RETRIES):
result, terminal_error = _invoke_bird_subprocess(query, count, timeout)
if terminal_error is not None:
return terminal_error
if result.returncode != 0:
error = result.stderr.strip() or "Bird search failed"
return {"error": error, "items": []}
output = result.stdout.strip()
if not output:
return {"items": []}
try:
parsed = json.loads(output)
except json.JSONDecodeError as e:
# Twitter's edge sometimes serves an HTML anti-bot interstitial
# in place of JSON. Tag the failure shape so it's distinguishable
# from "no results" in logs, then retry the subprocess.
looks_html = output.lstrip().lower().startswith(("<!doctype", "<html", "<"))
attempt_num = attempt + 1
log_msg = (
f"Bird search returned non-JSON stdout "
f"(looks_html={looks_html}, attempt {attempt_num}/{MAX_JSON_DECODE_RETRIES}, "
f"first 80 chars: {output[:80]!r})"
)
last_decode_error = str(e)
if attempt_num < MAX_JSON_DECODE_RETRIES:
log.source_log(
"X/bird",
f"{log_msg}; retrying in {JSON_DECODE_RETRY_DELAY:.0f}s",
)
time.sleep(JSON_DECODE_RETRY_DELAY)
continue
log.source_log("X/bird", log_msg)
return {
"error": (
f"Invalid JSON response after {MAX_JSON_DECODE_RETRIES} attempts "
f"(likely Twitter anti-bot interstitial): {e}"
),
"items": [],
}
if isinstance(parsed, list):
return {"items": parsed}
return parsed
# Defensive fallthrough — loop should always return above.
return {
"error": f"Bird search exhausted retries: {last_decode_error}",
"items": [],
}
def search_x(
topic: str,
from_date: str,
to_date: str,
depth: str = "default",
) -> Dict[str, Any]:
"""Search X using Bird CLI with automatic retry on 0 results.
Args:
topic: Search topic
from_date: Start date (YYYY-MM-DD)
to_date: End date (YYYY-MM-DD) - unused but kept for API compatibility
depth: Research depth - "quick", "default", or "deep"
Returns:
Raw Bird JSON response or error dict.
"""
count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
timeout = 30 if depth == "quick" else 45 if depth == "default" else 60
# Extract core subject - X search is literal, not semantic
core_topic = _extract_core_subject(topic)
query = f"{core_topic} since:{from_date}"
_log(f"Searching: {query}")
response = _run_bird_search(query, count, timeout)
# Check if we got results
items = parse_bird_response(response, query=core_topic)
# Retry with OR groups for multi-word queries (X supports OR operator)
core_words = core_topic.split()
if not items and len(core_words) >= 2:
from .query import extract_compound_terms
compounds = extract_compound_terms(topic)
if compounds:
# Build OR-group query: ("multi-agent" OR "agent simulation") since:DATE
or_parts = ' OR '.join(f'"{t}"' for t in compounds[:3])
_log(f"0 results for '{core_topic}', retrying with OR groups: {or_parts}")
query = f"({or_parts}) since:{from_date}"
response = _run_bird_search(query, count, timeout)
items = parse_bird_response(response, query=core_topic)
# Retry with fewer keywords if still 0 results and query has 3+ words
if not items and len(core_words) > 2:
shorter = ' '.join(core_words[:2])
_log(f"0 results for '{core_topic}', retrying with '{shorter}'")
query = f"{shorter} since:{from_date}"
response = _run_bird_search(query, count, timeout)
items = parse_bird_response(response, query=core_topic)
# Last-chance retry: use strongest remaining token (often the product name)
if not items and core_words:
low_signal = {
'trendiest', 'trending', 'hottest', 'hot', 'popular', 'viral',
'best', 'top', 'latest', 'new', 'plugin', 'plugins',
'skill', 'skills', 'tool', 'tools',
}
candidates = [w for w in core_words if w not in low_signal]
if candidates:
strongest = max(candidates, key=len)
_log(f"0 results for '{core_topic}', retrying with strongest token '{strongest}'")
query = f"{strongest} since:{from_date}"
response = _run_bird_search(query, count, timeout)
return response
def search_handles(
handles: List[str],
topic: Optional[str],
from_date: str,
count_per: int = 5,
) -> List[Dict[str, Any]]:
"""Search specific X handles for topic-related content.
Runs targeted Bird searches using `from:handle topic` syntax.
Used in Phase 2 supplemental search after entity extraction.
Args:
handles: List of X handles to search (without @)
topic: Search topic (core subject), or None for unfiltered search
from_date: Start date (YYYY-MM-DD)
count_per: Results to request per handle
Returns:
List of raw item dicts (same format as parse_bird_response output).
"""
core_topic = _extract_core_subject(topic) if topic else None
def _search_one_handle(handle: str) -> List[Dict[str, Any]]:
handle = handle.lstrip("@")
if core_topic:
query = f"from:{handle} {core_topic} since:{from_date}"
else:
query = f"from:{handle} since:{from_date}"
cmd = [
"node", str(_BIRD_SEARCH_MJS),
query,
"--count", str(count_per),
"--json",
]
try:
result = subproc.run_with_timeout(cmd, timeout=15, env=_subprocess_env())
except subproc.SubprocTimeout:
_log(f"Handle search timed out for @{handle}")
return []
except OSError as e:
_log(f"Handle search error for @{handle}: {e}")
return []
if result.returncode != 0:
_log(f"Handle search failed for @{handle}: {result.stderr.strip()}")
return []
output = result.stdout.strip()
if not output:
return []
try:
response = json.loads(output)
except json.JSONDecodeError:
_log(f"Invalid JSON from handle search for @{handle}")
return []
return parse_bird_response(response, query=core_topic)
from concurrent.futures import ThreadPoolExecutor, as_completed
all_items: List[Dict[str, Any]] = []
with ThreadPoolExecutor(max_workers=min(5, len(handles))) as executor:
futures = {executor.submit(_search_one_handle, h): h for h in handles}
for future in as_completed(futures):
all_items.extend(future.result())
return all_items
def parse_bird_response(response: Dict[str, Any], query: str = "") -> List[Dict[str, Any]]:
"""Parse Bird response to match xai_x output format.
Args:
response: Raw Bird JSON response
query: Original search query for relevance scoring
Returns:
List of normalized item dicts matching xai_x.parse_x_response() format.
"""
items = []
# Check for errors
if "error" in response and response["error"]:
_log(f"Bird error: {response['error']}")
return items
# Bird returns a list of tweets directly or under a key
raw_items = response if isinstance(response, list) else response.get("items", response.get("tweets", []))
if not isinstance(raw_items, list):
return items
for i, tweet in enumerate(raw_items):
if not isinstance(tweet, dict):
continue
# Extract URL - Bird uses permanent_url or we construct from id
url = tweet.get("permanent_url") or tweet.get("url", "")
if not url and tweet.get("id"):
# Try different field structures Bird might use
author = tweet.get("author", {}) or tweet.get("user", {})
screen_name = author.get("username") or author.get("screen_name", "")
if screen_name:
url = f"https://x.com/{screen_name}/status/{tweet['id']}"
if not url:
continue
# Parse date from created_at/createdAt (e.g., "Wed Jan 15 14:30:00 +0000 2026")
date = None
created_at = tweet.get("createdAt") or tweet.get("created_at", "")
if created_at:
try:
# Try ISO format first (e.g., "2026-02-03T22:33:32Z")
# Check for ISO date separator, not just "T" (which appears in "Tue")
if len(created_at) > 10 and created_at[10] == "T":
dt = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
else:
# Twitter format: "Wed Jan 15 14:30:00 +0000 2026"
dt = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
date = dt.strftime("%Y-%m-%d")
except (ValueError, TypeError):
pass
# Extract user info (Bird uses author.username, older format uses user.screen_name)
author = tweet.get("author", {}) or tweet.get("user", {})
author_handle = author.get("username") or author.get("screen_name", "") or tweet.get("author_handle", "")
# Build engagement dict (Bird uses camelCase: likeCount, retweetCount, etc.)
engagement = {
"likes": _first_of(tweet.get("likeCount"), tweet.get("like_count"), tweet.get("favorite_count")),
"reposts": _first_of(tweet.get("retweetCount"), tweet.get("retweet_count")),
"replies": _first_of(tweet.get("replyCount"), tweet.get("reply_count")),
"quotes": _first_of(tweet.get("quoteCount"), tweet.get("quote_count")),
}
# Convert to int where possible
for key in engagement:
if engagement[key] is not None:
try:
engagement[key] = int(engagement[key])
except (ValueError, TypeError):
engagement[key] = None
# Build normalized item
item = {
"id": f"X{i+1}",
"text": str(tweet.get("text", tweet.get("full_text", ""))).strip()[:500],
"url": url,
"author_handle": author_handle.lstrip("@"),
"date": date,
"engagement": engagement if any(v is not None for v in engagement.values()) else None,
"why_relevant": "", # Bird doesn't provide relevance explanations
"relevance": _compute_relevance(query, str(tweet.get("text", ""))) if query else 0.7,
}
items.append(item)
return items
"""Bluesky search via AT Protocol (requires app password).
Uses bsky.social for auth and api.bsky.app for post search (the canonical
authenticated AppView). The previous default `public.api.bsky.app` is the
unauthenticated public mirror, which BunnyCDN now blocks for searchPosts
regardless of auth header (verified 2026-05-04). Override the search host
via BSKY_SEARCH_HOST env var if Bluesky migrates infrastructure again.
Requires BSKY_HANDLE and BSKY_APP_PASSWORD env vars. App passwords are
19-char xxxx-xxxx-xxxx-xxxx; generate at bsky.app/settings/app-passwords.
The createSession endpoint accepts main-account passwords too, but they're
bad hygiene (no scope, can't revoke individually).
"""
import math
import os
import re
import sys
import time
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from . import http, log
BSKY_SESSION_URL = "https://bsky.social/xrpc/com.atproto.server.createSession"
_DEFAULT_BSKY_SEARCH_HOST = "api.bsky.app"
def _resolve_search_url(config: Optional[Dict[str, Any]] = None) -> str:
"""Resolve the Bluesky search URL with BSKY_SEARCH_HOST override.
Default is api.bsky.app. Override via BSKY_SEARCH_HOST in shell env or
.env file. The project's env.py loads .env into config but not into
os.environ, so check both — same hybrid pattern as last30days.py for
LAST30DAYS_STORE.
Hardens user-supplied host values against three common mis-configurations:
whitespace (e.g. " api.bsky.app "), embedded path components (e.g.
"api.bsky.app/xrpc/proxy") that would double the /xrpc/ segment, and
embedded scheme prefixes (e.g. "https://api.bsky.app"). On any of these
we log a warning and fall back to the default rather than building an
invalid URL with an opaque downstream error.
"""
config = config or {}
raw = (
os.environ.get("BSKY_SEARCH_HOST")
or config.get("BSKY_SEARCH_HOST")
or _DEFAULT_BSKY_SEARCH_HOST
)
host = raw.strip().rstrip("/")
# Strip embedded scheme so users who paste full URLs do not break the f-string.
for prefix in ("https://", "http://"):
if host.lower().startswith(prefix):
host = host[len(prefix):]
break
if not host or "/" in host or " " in host:
# Embedded path or whitespace remains — don't trust it. Default + log.
if raw != _DEFAULT_BSKY_SEARCH_HOST:
_log(
f"BSKY_SEARCH_HOST={raw!r} is not a bare hostname; "
f"falling back to default {_DEFAULT_BSKY_SEARCH_HOST!r}"
)
host = _DEFAULT_BSKY_SEARCH_HOST
return f"https://{host}/xrpc/app.bsky.feed.searchPosts"
# App-password format: xxxx-xxxx-xxxx-xxxx (19 chars, lowercase alphanumeric
# with three hyphens at fixed positions).
_APP_PASSWORD_RE = re.compile(r"^[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$")
def _validate_app_password_format(value) -> bool:
"""Return True if value matches Bluesky's 19-char app-password format.
False for non-strings (None, int, list) so callers passing config dict
values directly don't crash. Detect-but-not-gate: the createSession
endpoint also accepts main-account passwords, so failing this check is
a hygiene smell, not a hard error.
"""
if not isinstance(value, str):
return False
return bool(_APP_PASSWORD_RE.fullmatch(value))
DEPTH_CONFIG = {
"quick": 15,
"default": 30,
"deep": 60,
}
# Module-level token cache (valid for the lifetime of a single research run)
_cached_token: Optional[str] = None
_token_created_at: float = 0.0
_session_error: Optional[str] = None
_TOKEN_MAX_AGE_SECONDS = 5400 # 90 minutes (conservative, tokens last ~2 hours)
def _log(msg: str):
log.source_log("Bluesky", msg)
def _create_session(handle: str, app_password: str) -> Optional[str]:
"""Create an AT Protocol session and return the access token.
Args:
handle: Bluesky handle (e.g. user.bsky.social)
app_password: App password from bsky.app/settings/app-passwords
Returns:
Access JWT string, or None on failure. Sets _session_error on failure.
"""
global _cached_token, _token_created_at, _session_error
if _cached_token and (time.monotonic() - _token_created_at < _TOKEN_MAX_AGE_SECONDS):
return _cached_token
if _cached_token:
_log("Session token expired, re-authenticating")
_cached_token = None
_token_created_at = 0.0
try:
response = http.request(
"POST",
BSKY_SESSION_URL,
json_data={"identifier": handle, "password": app_password},
timeout=15,
)
token = response.get("accessJwt")
if token:
_cached_token = token
_token_created_at = time.monotonic()
_session_error = None
_log("Session created successfully")
return token
_log("No accessJwt in session response")
_session_error = "No accessJwt in session response"
return None
except http.HTTPError as e:
if e.status_code == 403 and e.body and "cloudflare" in e.body.lower():
_session_error = "Cloudflare blocked the request (403 Forbidden). This is a network-level block, not an auth issue. Try a different network or VPN."
elif e.status_code == 401:
_session_error = "Invalid credentials (401 Unauthorized). Check BSKY_HANDLE and BSKY_APP_PASSWORD."
else:
_session_error = f"Session request failed: {e}"
_log(f"Session creation failed: {_session_error}")
return None
except Exception as e:
_session_error = f"Session request failed: {type(e).__name__}: {e}"
_log(f"Session creation failed: {_session_error}")
return None
def _reset_session_cache() -> None:
global _cached_token, _token_created_at, _session_error
_cached_token = None
_token_created_at = 0.0
_session_error = None
def _extract_core_subject(topic: str) -> str:
"""Extract core subject from verbose query for Bluesky search."""
from .query import extract_core_subject
_BSKY_NOISE = frozenset({
'best', 'top', 'good', 'great', 'awesome',
'latest', 'new', 'news', 'update', 'updates',
'trending', 'hottest', 'popular', 'viral',
'practices', 'features', 'recommendations', 'advice',
})
return extract_core_subject(topic, noise=_BSKY_NOISE)
def _parse_date(item: Dict[str, Any]) -> Optional[str]:
"""Parse date from Bluesky post to YYYY-MM-DD.
AT Protocol uses ISO 8601 format in indexedAt and createdAt fields.
"""
for key in ("indexedAt", "createdAt"):
val = item.get(key)
if val and isinstance(val, str):
try:
dt = datetime.fromisoformat(val.replace("Z", "+00:00"))
return dt.strftime("%Y-%m-%d")
except (ValueError, TypeError):
pass
return None
def search_bluesky(
topic: str,
from_date: str,
to_date: str,
depth: str = "default",
config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Search Bluesky via AT Protocol API.
Args:
topic: Search topic
from_date: Start date (YYYY-MM-DD)
to_date: End date (YYYY-MM-DD)
depth: 'quick', 'default', or 'deep'
config: Config dict with BSKY_HANDLE and BSKY_APP_PASSWORD
Returns:
Dict with 'posts' list from AT Protocol response.
"""
config = config or {}
handle = config.get("BSKY_HANDLE", "")
app_password = config.get("BSKY_APP_PASSWORD", "")
if not handle or not app_password:
return {"posts": [], "error": "Bluesky credentials not configured"}
# One-shot hygiene warning if BSKY_APP_PASSWORD is not in app-password
# form. createSession accepts main-account passwords too — but main
# passwords have no scope (full account access), can't be revoked
# individually, and rotating them breaks every service that holds them.
# We warn but do not gate, matching the project's detect-don't-block
# philosophy elsewhere.
if not _validate_app_password_format(app_password):
_log(
"BSKY_APP_PASSWORD does not look like an app password "
"(expected xxxx-xxxx-xxxx-xxxx, 19 chars). It may be a main "
"account password — those work but are bad hygiene. Generate "
"an app password at https://bsky.app/settings/app-passwords"
)
count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
core_topic = _extract_core_subject(topic)
_log(f"Searching for '{core_topic}' (depth={depth}, limit={count})")
from urllib.parse import urlencode
params = {
"q": core_topic,
"limit": str(min(count, 100)),
"sort": "top",
}
url = f"{_resolve_search_url(config)}?{urlencode(params)}"
def _auth_and_search() -> tuple[Optional[Dict[str, Any]], Optional[str]]:
token = _create_session(handle, app_password)
if not token:
error_msg = _session_error or "Bluesky session creation failed (unknown error)"
return None, error_msg
try:
response = http.request(
"GET", url,
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
return response, None
except http.HTTPError as e:
_log(f"Search failed: {e}")
if e.status_code == 401:
_reset_session_cache()
return None, "refresh"
if e.status_code == 403 and e.body and "cloudflare" in e.body.lower():
return None, "Bluesky search blocked by Cloudflare (403). This is a network-level block - try a different network or VPN."
return None, f"Bluesky search failed: {e}"
except Exception as e:
_log(f"Search failed: {e}")
return None, f"Bluesky search failed: {type(e).__name__}: {e}"
response, error_msg = _auth_and_search()
if error_msg == "refresh":
_log("Session expired; recreating token and retrying once")
response, error_msg = _auth_and_search()
if error_msg:
return {"posts": [], "error": error_msg}
if response is None:
return {"posts": [], "error": "Bluesky search failed (unknown error)"}
posts = response.get("posts", [])
_log(f"Found {len(posts)} posts")
return response
def parse_bluesky_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Parse AT Protocol response into normalized item dicts.
Returns:
List of item dicts ready for normalization.
"""
posts = response.get("posts", [])
items = []
for i, post in enumerate(posts):
record = post.get("record") or {}
text = record.get("text") or ""
author = post.get("author") or {}
handle = author.get("handle") or ""
display_name = author.get("displayName") or handle
# Post URI -> URL
# URI format: at://did:plc:xxx/app.bsky.feed.post/rkey
uri = post.get("uri") or ""
rkey = uri.rsplit("/", 1)[-1] if uri else ""
url = f"https://bsky.app/profile/{handle}/post/{rkey}" if handle and rkey else ""
likes = post.get("likeCount") or 0
reposts = post.get("repostCount") or 0
replies = post.get("replyCount") or 0
quotes = post.get("quoteCount") or 0
date_str = _parse_date(post) or _parse_date(record)
# Relevance: position-based (AT Protocol sorts by relevance with sort=top)
rank_score = max(0.3, 1.0 - (i * 0.02))
engagement_boost = min(0.2, math.log1p(likes + reposts) / 40)
relevance = min(1.0, rank_score * 0.7 + engagement_boost + 0.1)
items.append({
"handle": handle,
"display_name": display_name,
"text": text,
"url": url,
"date": date_str,
"engagement": {
"likes": likes,
"reposts": reposts,
"replies": replies,
"quotes": quotes,
},
"relevance": round(relevance, 2),
"why_relevant": f"Bluesky: @{handle}: {text[:60]}" if text else f"Bluesky: {handle}",
})
return items
"""Category-peer subreddit map for Step 0.55 community resolution.
When a topic is a product in a known category (AI image generation, AI coding
agents, SaaS screen recording, etc.), brand-specific subreddits returned by
WebSearch are insufficient: cross-product technique discussion lives in
category-peer subs. This module classifies a topic into a category by matching
compound-term patterns against the lowercased topic string, then returns the
priority-ordered peer subreddit list for that category.
The map is intentionally small, curated, and code-reviewed. Adding a new
category is a code change; there is no user-editable override surface.
False-positive guard: every pattern is either a multi-word compound (e.g.
"image generation", "text to image") or a domain-specific single word
(e.g. "midjourney", "stablediffusion"). Bare common nouns like "image",
"ai", or "model" are never used as patterns.
First-match-wins: categories are evaluated in declared order. Entries are
sorted from most-specific to least-specific so narrower categories claim a
topic before broader ones. For example, `ai_image_generation` appears
before `ai_chat_model` so "gpt image 2" matches the image-gen category.
"""
from __future__ import annotations
from typing import List, Optional, TypedDict
class _CategoryEntry(TypedDict):
patterns: List[str]
peer_subs: List[str]
CATEGORY_PEERS: dict[str, _CategoryEntry] = {
"ai_image_generation": {
"patterns": [
"image generation",
"image gen",
"text to image",
"text-to-image",
"gpt image",
"gpt-image",
"nano banana",
"midjourney",
"stable diffusion",
"stablediffusion",
"dall-e",
"dalle",
"flux.1",
"flux schnell",
"imagen",
"seedance",
"ideogram",
"recraft",
],
"peer_subs": [
"StableDiffusion",
"midjourney",
"dalle2",
"aiArt",
"PromptEngineering",
"MediaSynthesis",
],
},
"ai_video_generation": {
"patterns": [
"video generation",
"text to video",
"text-to-video",
"sora",
"veo 3",
"veo3",
"runway gen",
"kling",
"pika labs",
"luma dream machine",
"hailuo",
],
"peer_subs": [
"aivideo",
"StableDiffusion",
"runwayml",
"singularity",
"MediaSynthesis",
],
},
"ai_music_generation": {
"patterns": [
"music generation",
"ai music",
"suno",
"udio",
"riffusion",
"stable audio",
],
"peer_subs": [
"SunoAI",
"udiomusic",
"aimusic",
"artificial",
],
},
"ai_coding_agent": {
"patterns": [
"claude code",
"cursor ide",
"github copilot",
"windsurf",
"aider",
"cline",
"openclaw",
"hermes agent",
"continue.dev",
"codeium",
"sweep ai",
"devin ai",
"coding agent",
"coding assistant",
],
"peer_subs": [
"ChatGPTCoding",
"LocalLLaMA",
"singularity",
"PromptEngineering",
],
},
"ai_agent_framework": {
"patterns": [
"agent framework",
"agentic framework",
"langchain",
"langgraph",
"crewai",
"autogen",
"llamaindex",
"dspy",
"smolagents",
],
"peer_subs": [
"LangChain",
"LocalLLaMA",
"AI_Agents",
"MachineLearning",
],
},
"ai_chat_model": {
"patterns": [
"gpt-5",
"gpt-4",
"claude opus",
"claude sonnet",
"claude haiku",
"gemini pro",
"gemini flash",
"llama 3",
"llama 4",
"deepseek",
"qwen",
"mistral large",
"grok",
],
"peer_subs": [
"LocalLLaMA",
"ChatGPT",
"ClaudeAI",
"singularity",
"artificial",
],
},
"saas_screen_recording": {
"patterns": [
"screen recording",
"screen recorder",
"loom video",
"tella screen",
"vidyard",
"screen capture tool",
],
"peer_subs": [
"SaaS",
"screenrecording",
"productivity",
"Entrepreneur",
],
},
"saas_productivity": {
"patterns": [
"notion app",
"obsidian plugin",
"obsidian app",
"linear app",
"asana",
"clickup",
"productivity app",
],
"peer_subs": [
"productivity",
"SaaS",
"ObsidianMD",
"Notion",
],
},
"prediction_markets": {
"patterns": [
"polymarket",
"kalshi",
"prediction market",
"event contracts",
"manifold markets",
],
"peer_subs": [
"Polymarket",
"Kalshi",
"predictionmarkets",
],
},
"crypto_defi": {
"patterns": [
"defi protocol",
"yield farming",
"liquidity pool",
"stablecoin",
"ethereum layer",
"layer 2",
"l2 rollup",
],
"peer_subs": [
"defi",
"ethfinance",
"CryptoCurrency",
"ethereum",
],
},
"dev_tool_cli": {
"patterns": [
"cli tool",
"command line tool",
"terminal app",
"dev tool",
],
"peer_subs": [
"commandline",
"programming",
"webdev",
],
},
}
def detect_category(topic: Optional[str]) -> Optional[str]:
"""Classify a topic into a known category by compound-term match.
Returns the category id (e.g. "ai_image_generation") or None if no
category's patterns match. Matching is case-insensitive substring over
the lowercased topic. Declaration order wins (first-match-wins), so the
map is ordered from most-specific to least-specific.
A None or empty topic returns None. Classification never raises on
normal string inputs; callers do not need to wrap in try/except for
typical paths, though defensive callers may.
"""
if not topic:
return None
lowered = topic.lower()
for category_id, entry in CATEGORY_PEERS.items():
for pattern in entry["patterns"]:
if pattern in lowered:
return category_id
return None
def peer_subs_for(category_id: Optional[str]) -> List[str]:
"""Return the priority-ordered peer subreddit list for a category.
Returns an empty list for None or unknown category ids. The returned
list is a fresh copy; callers may safely mutate it.
"""
if not category_id:
return []
entry = CATEGORY_PEERS.get(category_id)
if not entry:
return []
return list(entry["peer_subs"])
"""Date utilities for last30days skill."""
from datetime import datetime, timedelta, timezone
from typing import Optional, Tuple
def get_date_range(days: int = 30) -> Tuple[str, str]:
"""Get the date range for the last N days.
Returns:
Tuple of (from_date, to_date) as YYYY-MM-DD strings
"""
today = datetime.now(timezone.utc).date()
from_date = today - timedelta(days=days)
return from_date.isoformat(), today.isoformat()
def parse_date(date_str: Optional[str]) -> Optional[datetime]:
"""Parse a date string in various formats.
Supports: YYYY-MM-DD, ISO 8601, Unix timestamp
"""
if not date_str:
return None
# Try Unix timestamp (from Reddit)
try:
ts = float(date_str)
return datetime.fromtimestamp(ts, tz=timezone.utc)
except (ValueError, TypeError):
pass
# Try ISO formats
formats = [
"%Y-%m-%d",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%dT%H:%M:%S%z",
"%Y-%m-%dT%H:%M:%S.%f%z",
]
for fmt in formats:
try:
dt = datetime.strptime(date_str, fmt)
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc)
return dt.replace(tzinfo=timezone.utc)
except ValueError:
continue
return None
def timestamp_to_date(ts: Optional[float]) -> Optional[str]:
"""Convert Unix timestamp to YYYY-MM-DD string."""
if ts is None:
return None
try:
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
return dt.date().isoformat()
except (ValueError, TypeError, OSError):
return None
def get_date_confidence(date_str: Optional[str], from_date: str, to_date: str) -> str:
"""Determine confidence level for a date.
Args:
date_str: The date to check (YYYY-MM-DD or None)
from_date: Start of valid range (YYYY-MM-DD)
to_date: End of valid range (YYYY-MM-DD)
Returns:
'high', 'med', or 'low'
"""
if not date_str:
return 'low'
try:
dt = datetime.strptime(date_str, "%Y-%m-%d").date()
start = datetime.strptime(from_date, "%Y-%m-%d").date()
end = datetime.strptime(to_date, "%Y-%m-%d").date()
return 'high' if start <= dt <= end else 'low'
except ValueError:
return 'low'
def days_ago(date_str: Optional[str]) -> Optional[int]:
"""Calculate how many days ago a date is.
Returns None if date is invalid or missing.
"""
if not date_str:
return None
try:
dt = datetime.strptime(date_str, "%Y-%m-%d").date()
today = datetime.now(timezone.utc).date()
delta = today - dt
return delta.days
except ValueError:
return None
def recency_score(date_str: Optional[str], max_days: int = 30) -> int:
"""Calculate recency score (0-100).
0 days ago = 100, max_days ago = 0, clamped.
"""
age = days_ago(date_str)
if age is None:
return 0 # Unknown date gets worst score
if age < 0:
return 100 # Future date (treat as today)
if age >= max_days:
return 0
return int(100 * (1 - age / max_days))
"""Within-source near-duplicate detection."""
from __future__ import annotations
import re
from . import schema
STOPWORDS = frozenset(
{
"the",
"a",
"an",
"to",
"for",
"how",
"is",
"in",
"of",
"on",
"and",
"with",
"from",
"by",
"at",
"this",
"that",
"it",
"what",
"are",
"do",
"can",
}
)
def normalize_text(text: str) -> str:
text = re.sub(r"[^\w\s]", " ", text.lower())
return re.sub(r"\s+", " ", text).strip()
def _ngrams_of_normalized(norm: str, n: int = 3) -> set[str]:
if len(norm) < n:
return {norm} if norm else set()
return {norm[index:index + n] for index in range(len(norm) - n + 1)}
def get_ngrams(text: str, n: int = 3) -> set[str]:
return _ngrams_of_normalized(normalize_text(text), n)
def jaccard_similarity(left: set[str], right: set[str]) -> float:
if not left or not right:
return 0.0
union = left | right
if not union:
return 0.0
return len(left & right) / len(union)
def token_jaccard(text_a: str, text_b: str) -> float:
tokens_a = {
token
for token in normalize_text(text_a).split()
if len(token) > 1 and token not in STOPWORDS
}
tokens_b = {
token
for token in normalize_text(text_b).split()
if len(token) > 1 and token not in STOPWORDS
}
return jaccard_similarity(tokens_a, tokens_b)
def hybrid_similarity(text_a: str, text_b: str) -> float:
return max(
jaccard_similarity(get_ngrams(text_a), get_ngrams(text_b)),
token_jaccard(text_a, text_b),
)
def _tokenize(normalized: str) -> frozenset[str]:
return frozenset(
tok for tok in normalized.split()
if len(tok) > 1 and tok not in STOPWORDS
)
class _PreparedText:
"""Pre-computed text representations for fast repeated similarity checks."""
__slots__ = ("ngrams", "tokens")
def __init__(self, raw: str) -> None:
norm = normalize_text(raw)
self.ngrams = _ngrams_of_normalized(norm)
self.tokens = _tokenize(norm)
def prepared_similarity(a: _PreparedText, b: _PreparedText) -> float:
return max(
jaccard_similarity(a.ngrams, b.ngrams),
jaccard_similarity(a.tokens, b.tokens),
)
def item_text(item: schema.SourceItem) -> str:
parts = [item.title, item.body, item.author or "", item.container or ""]
return " ".join(part for part in parts if part).strip()
def dedupe_items(items: list[schema.SourceItem], threshold: float = 0.7) -> list[schema.SourceItem]:
"""Remove near-duplicates while keeping earlier, better-scored items."""
kept: list[schema.SourceItem] = []
kept_prepared: list[_PreparedText] = []
for item in items:
text = item_text(item)
if not text:
kept.append(item)
continue
prep = _PreparedText(text)
is_duplicate = False
for existing_prep in kept_prepared:
if prepared_similarity(prep, existing_prep) >= threshold:
is_duplicate = True
break
if not is_duplicate:
kept.append(item)
kept_prepared.append(prep)
return kept
export {};
//# sourceMappingURL=twitter-client-types.js.mapRelated skills
How it compares
Choose last30days over generic web search skills when you need cross-platform developer chatter from exactly the past 30 days with optional HTML export.
FAQ
Which sources does last30days cover?
last30days researches Reddit, X, YouTube, and the open web from the last 30 days. The interface short_description promises synthesized expert answers and copy-paste prompts from those live channels.
How do you get an HTML brief from last30days?
last30days emits a shareable HTML brief when invoked with --emit=html, --emit:html, --html, or natural-language phrasing like give me a shareable HTML brief for the research output.
Is Last30days safe to install?
skills.sh reports 0 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.