Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(review): address code-review findings

Matt Van Horn9e2f0bab7d58
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 17d35005..35114743 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -65,7 +65,7 @@ The project-scoped file is the cleanest pattern for **per-client setups**: drop
| TruthSocial | `TRUTHSOCIAL_TOKEN` | TruthSocial items | yes |
| Web search | one of: `BRAVE_API_KEY`, `EXA_API_KEY`, `SERPER_API_KEY`, `PARALLEL_API_KEY` | `--auto-resolve` and Step 2 supplements | Brave has a free tier; native WebSearch on Claude Code / Codex / Gemini works as a fallback |
| Perplexity Deep Research | `OPENROUTER_API_KEY` | `--deep-research` flag (~$0.90/query) | no |
-| Caption-free transcription | `GROQ_API_KEY` (free tier, preferred) or `OPENAI_API_KEY` (paid backstop); requires `ffmpeg` | Whisper transcription for audio/video without captions | Groq free tier is generous; needs ffmpeg installed |
+| Caption-free transcription | `GROQ_API_KEY` (free tier, preferred) or `OPENAI_API_KEY` (paid backstop); requires `ffmpeg` | Whisper transcription for audio/video without captions (groundwork: module shipped, not yet auto-invoked by the engine) | Groq free tier is generous; needs ffmpeg installed |
| Jobs / careers pages | none for public ATS pages; web backend improves fallback discovery | `--hiring-signals` and strong Hiring Signals in standard company reports | yes |
| Apify (alternate scraper) | `APIFY_API_TOKEN` | fallback for Reddit/TikTok/Instagram when ScrapeCreators is exhausted | yes (limited) |
diff --git a/skills/last30days/scripts/lib/github.py b/skills/last30days/scripts/lib/github.py
index 1ccb400d..6df72656 100644
--- a/skills/last30days/scripts/lib/github.py
+++ b/skills/last30days/scripts/lib/github.py
@@ -202,11 +202,12 @@ def search_github(
envelope = {"items": [], "context": {"core": core, "from_date": from_date,
"to_date": to_date, "count": count}}
if not authed:
- # Most likely the anon rate limit (403). Surface it so the pipeline
- # records a degraded/failed reason instead of silently showing zero.
+ # Could be the anon rate limit (403) or an unprocessable query (422)
+ # -- _fetch_json maps both to None. Don't over-claim which; suggest a
+ # token since that fixes the common (rate-limit) case.
envelope["error"] = (
- "GitHub unauthenticated request failed (likely anon rate limit; "
- "set GITHUB_TOKEN or run gh auth login for higher limits)"
+ "GitHub unauthenticated request returned no data (anon rate limit "
+ "or unprocessable query; set GITHUB_TOKEN or run gh auth login)"
)
return envelope
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index 2d8f6880..201d7e6e 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -272,34 +272,49 @@ def get_text(
class RateLimiter:
- """Thread-safe minimum-interval throttle for an endpoint family.
+ """Thread-safe token-bucket throttle for an endpoint family.
The keyless source tiers run under the pipeline's ThreadPoolExecutor, so a
multi-subquery run can fire many requests at the same host at once. A bare
per-request retry budget does not prevent that stampede — it only reacts
- after a 429. This spaces calls so concurrent futures sharing one limiter
- cannot burst past ``min_interval`` seconds between requests.
+ after a 429. A token bucket bounds the *sustained* rate while still allowing
+ a short burst, so legitimate parallelism is preserved (unlike a strict
+ min-interval gate that would serialize every concurrent caller and could
+ push later futures past their result timeouts).
+
+ ``rate_per_sec`` tokens refill per second; ``burst`` is the bucket capacity
+ (max simultaneous calls before throttling kicks in). The lock is released
+ while sleeping so waiting threads don't serialize on each other.
"""
- def __init__(self, min_interval: float):
- self.min_interval = min_interval
- self._last = 0.0
+ def __init__(self, rate_per_sec: float, burst: int | None = None):
+ self.rate = rate_per_sec
+ self.capacity = burst if burst is not None else max(1, int(rate_per_sec))
+ self._tokens = float(self.capacity)
+ self._last = time.monotonic()
self._lock = threading.Lock()
def acquire(self) -> None:
- """Block until at least ``min_interval`` has elapsed since the last call."""
- with self._lock:
- now = time.monotonic()
- wait = self.min_interval - (now - self._last)
- if wait > 0:
- time.sleep(wait)
+ """Consume one token, blocking only when the bucket is empty."""
+ while True:
+ with self._lock:
now = time.monotonic()
- self._last = now
+ # Clamp elapsed to >= 0: a backward clock reading must never
+ # drive tokens negative (which would spin this loop forever).
+ elapsed = max(0.0, now - self._last)
+ self._tokens = min(self.capacity, self._tokens + elapsed * self.rate)
+ self._last = now
+ if self._tokens >= 1.0:
+ self._tokens -= 1.0
+ return
+ wait = (1.0 - self._tokens) / self.rate
+ time.sleep(wait)
# Shared across all keyless Reddit tiers (RSS, listing, shreddit) so their
-# combined fan-out is throttled as one family, not three independent bursts.
-REDDIT_KEYLESS_LIMITER = RateLimiter(min_interval=0.5)
+# combined fan-out is throttled as one family. Burst lets the parallel
+# enrichment workers proceed; sustained rate caps the stampede.
+REDDIT_KEYLESS_LIMITER = RateLimiter(rate_per_sec=5.0, burst=5)
def reddit_keyless_get_text(
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 64857bf6..80adc6eb 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -1166,10 +1166,10 @@ def _retrieve_stream(
token = github.resolve_token(config.get("GITHUB_TOKEN"))
response = github.search_github(subquery.search_query, from_date, to_date, depth=depth, token=token)
items = github.parse_github_response(response)
- if not items and response.get("error"):
- # Surface unauth rate-limit (or other hard failure) so the run
- # records it as degraded/failed instead of silently showing zero.
- raise RuntimeError(response["error"])
+ # Note: an unauth rate-limit (response["error"]) is expected on the
+ # tokenless anon tier and returns empty here rather than raising — github
+ # is now always eligible, so raising would spam "github failed" on every
+ # tokenless run. The condition is logged in github.search_github.
items = github.enrich_with_comments(items, depth=depth, token=token)
return items, {}
if source == "pinterest":
diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.py
index 4e9dde8b..027b4276 100644
--- a/skills/last30days/scripts/lib/setup_wizard.py
+++ b/skills/last30days/scripts/lib/setup_wizard.py
@@ -119,18 +119,24 @@ def _open_secret_append(path: Path):
def _format_env_value(value: str) -> str:
"""Quote a value so it round-trips through env.load_env_file.
- The loader strips a single layer of matching surrounding quotes, so values
- containing whitespace or a leading quote are wrapped in double quotes to
- survive the parse. Plain tokens (the common case) are returned unchanged.
- Embedded double quotes are backslash-escaped. Newlines are not permitted in
- a single-line env value and are stripped defensively.
+ env.load_env_file strips a single layer of matching surrounding quotes but
+ does NOT process backslash escapes, so we wrap (never escape):
+ - plain tokens (no whitespace, no leading quote): returned unchanged;
+ - values with whitespace/leading quote and no double-quote: double-quoted;
+ - values containing a double-quote but no single-quote: single-quoted;
+ - values containing both quote types: returned as-is (best effort; no
+ wrapper round-trips through the loader, and tokens never hit this).
+ Newlines are not valid in a single-line env value and are stripped.
"""
value = value.replace("\r", "").replace("\n", " ")
needs_quoting = (not value) or value[0] in ("'", '"') or any(c.isspace() for c in value)
if not needs_quoting:
return value
- escaped = value.replace("\\", "\\\\").replace('"', '\\"')
- return f'"{escaped}"'
+ if '"' not in value:
+ return f'"{value}"'
+ if "'" not in value:
+ return f"'{value}'"
+ return value
def write_setup_config(env_path: Path, from_browser: str = "auto") -> bool:
diff --git a/skills/last30days/scripts/lib/transcribe.py b/skills/last30days/scripts/lib/transcribe.py
index c3dc2b99..e470000d 100644
--- a/skills/last30days/scripts/lib/transcribe.py
+++ b/skills/last30days/scripts/lib/transcribe.py
@@ -20,12 +20,11 @@ from __future__ import annotations
import os
import shutil
-import subprocess
import tempfile
from dataclasses import dataclass, field
from typing import Optional
-from . import env, health
+from . import env, health, subproc
# Whisper's documented upload ceiling. We compress to stay under it and chunk
# when a single clip still exceeds it.
@@ -224,9 +223,13 @@ def _post_audio(provider: str, path: str, api_key: str, timeout: float) -> Optio
def _run(command: list[str], timeout: float = 120.0) -> bool:
- """Run a subprocess; return True on exit 0, False on any failure. No raise."""
+ """Run a subprocess; return True on exit 0, False on any failure. No raise.
+
+ Uses subproc.run_with_timeout so a timed-out yt-dlp/ffmpeg is killed at the
+ process-group level (os.setsid/killpg) instead of orphaning child trees.
+ """
try:
- proc = subprocess.run(command, capture_output=True, timeout=timeout)
- except (FileNotFoundError, OSError, subprocess.TimeoutExpired):
+ result = subproc.run_with_timeout(command, timeout=int(timeout))
+ except (subproc.SubprocTimeout, FileNotFoundError, OSError):
return False
- return proc.returncode == 0
+ return result.returncode == 0
diff --git a/skills/last30days/scripts/lib/web_search_keyless.py b/skills/last30days/scripts/lib/web_search_keyless.py
index f5363d4c..4664ba26 100644
--- a/skills/last30days/scripts/lib/web_search_keyless.py
+++ b/skills/last30days/scripts/lib/web_search_keyless.py
@@ -24,7 +24,7 @@ from __future__ import annotations
import html
import re
-from urllib.parse import parse_qs, urlparse
+from urllib.parse import parse_qs, urlencode, urlparse
from . import http
@@ -48,8 +48,10 @@ _SNIPPET_RE = re.compile(
def _domain(url: str) -> str:
+ # Normalize identically to grounding._domain (strip + lowercase) so keyless
+ # and paid results dedupe/group consistently by source_domain.
try:
- return urlparse(url).netloc
+ return urlparse(url).netloc.strip().lower()
except (ValueError, AttributeError):
return ""
@@ -96,30 +98,33 @@ def keyless_search(
def _search_ddg(query: str, count: int) -> list[dict]:
- from urllib.parse import urlencode
-
url = f"{_DDG_HTML_URL}?{urlencode({'q': query})}"
text = http.get_text(url, accept="text/html", retries=2)
if not text:
return []
items: list[dict] = []
- snippets = _SNIPPET_RE.findall(text)
- for i, match in enumerate(_RESULT_A_RE.finditer(text)):
+ # Associate each result's snippet by position, not by a parallel index:
+ # some result anchors (video/news modules) have no snippet, so a global
+ # zip would shift every later snippet onto the wrong result. Take the first
+ # snippet that falls between this anchor and the next one.
+ matches = list(_RESULT_A_RE.finditer(text))
+ for idx, match in enumerate(matches):
if len(items) >= count:
break
target = _unwrap_ddg_redirect(match.group("href"))
if not target.startswith("http"):
continue
+ next_start = matches[idx + 1].start() if idx + 1 < len(matches) else len(text)
+ window = text[match.end():next_start]
+ snippet_match = _SNIPPET_RE.search(window)
+ snippet = _strip_html(snippet_match.group("snippet")) if snippet_match else ""
title = _strip_html(match.group("title"))
- snippet = _strip_html(snippets[i]) if i < len(snippets) else ""
- items.append(_to_item(i, title, target, snippet))
+ items.append(_to_item(len(items), title, target, snippet))
return items
def _search_searxng(query: str, count: int, instance_url: str) -> list[dict]:
base = instance_url.rstrip("/")
- from urllib.parse import urlencode
-
url = f"{base}/search?{urlencode({'q': query, 'format': 'json'})}"
try:
data = http.get(url, headers={"Accept": "application/json"}, timeout=15, retries=2)
diff --git a/tests/test_reddit_keyless_backoff.py b/tests/test_reddit_keyless_backoff.py
index f2af0da7..fc44aaa4 100644
--- a/tests/test_reddit_keyless_backoff.py
+++ b/tests/test_reddit_keyless_backoff.py
@@ -6,28 +6,32 @@ from lib import http, reddit_rss
class TestRateLimiter:
- def test_first_acquire_does_not_sleep(self):
- limiter = http.RateLimiter(min_interval=0.5)
+ def test_burst_does_not_sleep(self):
+ # A full bucket lets `burst` calls through immediately.
+ limiter = http.RateLimiter(rate_per_sec=5.0, burst=3)
with mock.patch.object(http.time, "monotonic", return_value=100.0), \
mock.patch.object(http.time, "sleep") as slept:
limiter.acquire()
+ limiter.acquire()
+ limiter.acquire()
slept.assert_not_called()
- def test_second_acquire_sleeps_to_maintain_interval(self):
- limiter = http.RateLimiter(min_interval=0.5)
- # First call at t=100, second call 0.1s later -> must wait ~0.4s.
- times = iter([100.0, 100.1, 100.5])
+ def test_sleeps_when_bucket_empty(self):
+ # burst=1: first call passes, second (same instant) must wait ~1/rate.
+ limiter = http.RateLimiter(rate_per_sec=2.0, burst=1)
+ times = iter([100.0, 100.0, 100.0, 100.5])
with mock.patch.object(http.time, "monotonic", side_effect=lambda: next(times)), \
mock.patch.object(http.time, "sleep") as slept:
- limiter.acquire()
- limiter.acquire()
- slept.assert_called_once()
+ limiter.acquire() # consumes the one token
+ limiter.acquire() # bucket empty -> sleep, then refilled token consumed
+ slept.assert_called()
waited = slept.call_args.args[0]
- assert abs(waited - 0.4) < 1e-6
+ assert abs(waited - 0.5) < 1e-6 # (1 token deficit) / 2 per sec
- def test_no_sleep_when_interval_already_elapsed(self):
- limiter = http.RateLimiter(min_interval=0.5)
- times = iter([100.0, 102.0]) # 2s gap > interval
+ def test_refill_over_time_avoids_sleep(self):
+ limiter = http.RateLimiter(rate_per_sec=2.0, burst=1)
+ # Second call 1s later: bucket refilled (2/s * 1s capped at burst=1) -> no sleep.
+ times = iter([100.0, 101.0])
with mock.patch.object(http.time, "monotonic", side_effect=lambda: next(times)), \
mock.patch.object(http.time, "sleep") as slept:
limiter.acquire()