AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(techmeme): window Techmeme results to real dates, drop useless sync (#752)
Matt Van Horn1e82659bb47f
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 6ab3001e..0ebdee3a 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -102,7 +102,7 @@ The project-scoped file is useful for **intentional per-client setups**: drop a| Instagram comments | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `instagram_comments` (**on by default** — Step 5 Recommended tier) | top comments (by `comment_like_count`) on the top ~3 Instagram posts, via `/v2/instagram/post/comments` | ~3 calls/run; 10K free calls || Digg | `digg-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install digg --cli-only`; binary defaults to `$HOME/.local/bin` — Hermes/OpenClaw agent subprocesses must inherit that dir on PATH for Digg to activate; prior pp-digg installs use the same path) | always on if `digg-pp-cli` on PATH | yes (free, keyless, read-only) || arXiv | `arxiv-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install arxiv --cli-only`) | always on if `arxiv-pp-cli` on PATH; fires on research/technical topics and stays quiet otherwise (relevance + 365-day recency gating) | yes (free, keyless) |-| Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; syncs a local headline cache once per run, then searches | yes (free, keyless) |+| Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; searches Techmeme's live archive and keeps only headlines dated within the research window (undated headlines flow through as low-confidence) | yes (free, keyless) || Trustpilot | `trustpilot-pp-cli` on PATH (NOT auto-installed; install on demand via `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`) + `INCLUDE_SOURCES` contains `trustpilot` | **opt-in, off by default**; when enabled, activates only on company/brand topics — or on any topic when `--trustpilot-domain=<domain>` pins the review page explicitly (bypasses the brand-shape gate; also the per-entity `trustpilot_domain` key in `--competitors-plan`). Bare company names auto-resolve to the review-page domain via the CLI's search. The session warms once before the search fan-out; a stale session does a ~10s headless-Chrome WAF-cookie harvest (set `LAST30DAYS_TRUSTPILOT_NO_BROWSER=1` to disable in cron/CI) | yes (no API key; cookie-replay after the one-time harvest) || X / Twitter | one of: `AUTH_TOKEN` + `CT0` (browser cookies, Bird CLI), `XAI_API_KEY`, `XQUIK_API_KEY`, `SCRAPECREATORS_API_KEY`, or `FROM_BROWSER` (cookie-jar auth) | X items in results | cookie-jar / Bird = free; Xquik / xAI / ScrapeCreators = key-based || TikTok | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `tiktok` | TikTok items | 10K free calls |diff --git a/skills/last30days/scripts/lib/techmeme.py b/skills/last30days/scripts/lib/techmeme.pyindex 5c5e8098..720a46e6 100644--- a/skills/last30days/scripts/lib/techmeme.py+++ b/skills/last30days/scripts/lib/techmeme.py@@ -1,8 +1,8 @@"""Techmeme tech-news source for last30days.-Shells out to ``techmeme-pp-cli`` (no auth) to surface current tech-news-headlines relevant to a topic. Techmeme caches headlines locally, so the-adapter ensures a one-time sync per run, then searches the cache.+Shells out to ``techmeme-pp-cli`` (no auth). The CLI's ``search`` command hits+Techmeme's live archive search endpoint (results back to ~2005) -- it never+reads the locally synced headline cache, so the adapter performs no ``sync``.Activation gate: only available when ``techmeme-pp-cli`` is on PATH.``pipeline.available_sources`` checks ``shutil.which`` before including@@ -11,23 +11,31 @@ Activation gate: only available when ``techmeme-pp-cli`` is on PATH.Surface choice: ``search "<topic>" --json`` (NOT ``--agent``). ``--agent``implies ``--compact``, which on older binaries stripped headline records to``{}`` (fixed upstream in printing-press-library PR #1383); ``--json`` without-``--compact`` returns the populated ``{num, source, headline, link}`` shape on-every binary version, so the adapter is robust regardless of the installed-build.--The search shape carries no per-item date or velocity, so headlines are dated-to the sync time (Techmeme's cache is the current news cycle) and ranked on-topic relevance plus source quality. Publication-name header rows (very short-``headline`` values) are dropped.+``--compact`` returns the populated record shape on every binary version, so+the adapter is robust regardless of the installed build.++Dates: current binaries emit ``{num, source, headline, link, date}`` where+``date`` is ISO ``YYYY-MM-DD`` (or ``""`` when Techmeme's markup was+unparseable). The adapter windows records to the research range+(``from_date <= date <= to_date``) so archive hits from years past never+masquerade as current news. Records with no usable date -- old binaries emit+no ``date`` key at all -- are kept but flow downstream with no date, so+``normalize._normalize_techmeme`` assigns ``date_confidence: low``. Headlines+are never stamped with today's date. (This deliberately diverges from+``lib/arxiv.py``, which drops entries with unparseable dates -- arXiv's feed+reliably carries dates, so an unparseable one is anomalous; Techmeme's old+binaries emit no ``date`` key at all, so dropping would zero out the source+for every user on an old binary.) Old binaries also print prose+(``No results for "q"``) to stdout on zero hits; that parses as an empty+result set, not a decode failure. Publication-name header rows (very short+``headline`` values) are dropped; ranking is topic relevance plus rank decay."""from __future__ import annotationsimport json+import reimport shutil-import threading-import time-from datetime import datetime, timezonefrom typing import Any, Dict, Listfrom . import log, subproc@@ -48,19 +56,12 @@ DEPTH_CONFIG = {MIN_HEADLINE_WORDS = 4SEARCH_TIMEOUT = 30-SYNC_TIMEOUT = 40-# Refresh the local cache at most once per TTL window, guarded by a lock so-# concurrent fan-out threads do not double-sync (two processes writing the same-# cache file). A monotonic timestamp -- not a bare bool -- so a long-lived host-# process or multi-report fan-out re-syncs instead of serving a stale cache-# indefinitely (headlines are dated to the sync time, so staleness would-# misrepresent old news as current).-_SYNC_LOCK = threading.Lock()-_SYNC_TTL = 600.0 # seconds-_LAST_SYNC = 0.0-# Sentinel used by tests to force a sync regardless of the TTL window.-_NEVER_SYNCED = float("-inf")+# Old binaries print this prose to stdout (exit 0) on zero hits, even in JSON+# mode. It is a zero-result response, not malformed output.+_NO_RESULTS_PREFIX = "No results"++_ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")def _log(msg: str) -> None:@@ -72,33 +73,10 @@ def _is_available() -> bool:return shutil.which(CLI_BIN) is not None-def _today_iso() -> str:- return datetime.now(timezone.utc).date().isoformat()---def _ensure_synced() -> None:- """Refresh the local headline cache at most once per TTL window.-- Lock-guarded so concurrent fan-out threads do not double-sync. Best-effort:- a sync failure is logged and ignored (search can still run on an existing- cache), and the timestamp is stamped before the call so a failing sync does- not retry on every subquery within the window."""- global _LAST_SYNC- with _SYNC_LOCK:- if time.monotonic() - _LAST_SYNC < _SYNC_TTL:- return- _LAST_SYNC = time.monotonic() # stamp first: a failure does not retry- try:- subproc.run_with_timeout([CLI_BIN, "sync", "--agent"], timeout=SYNC_TIMEOUT)- _log("synced headline cache")- except (subproc.SubprocTimeout, FileNotFoundError, OSError) as exc:- _log(f"sync skipped: {exc}")--def _build_search_args(topic: str) -> List[str]:# --json (not --agent) avoids --compact, which blanks headline records on# pre-PR-1383 binaries. Techmeme's `search` has no result-limit flag, so the- # depth cap is applied client-side after parsing.+ # depth cap is applied client-side after windowing.return [CLI_BIN, "search", topic, "--json"]@@ -114,6 +92,18 @@ def _coerce_list(data: Any) -> List[Dict[str, Any]]:return []+def _record_iso_date(rec: Dict[str, Any]) -> str | None:+ """The record's ``date`` as a valid ISO YYYY-MM-DD string, else None.++ Old binaries emit no ``date`` key; current binaries emit ``""`` when+ Techmeme's markup was unparseable. Anything that isn't a clean ISO date is+ treated as absent."""+ value = rec.get("date")+ if isinstance(value, str) and _ISO_DATE_RE.match(value.strip()):+ return value.strip()+ return None++def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:"""Invoke techmeme-pp-cli and return ``{"results": [...records...]}``.Never raises."""@@ -140,6 +130,10 @@ def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:stdout = result.stdout or ""if not stdout.strip():return {"results": []}+ # Old binaries print `No results for "q"` prose (exit 0) even in JSON+ # mode: a legitimate zero-hit response, not a decode failure.+ if stdout.strip().startswith(_NO_RESULTS_PREFIX):+ return {"results": []}try:data = json.loads(stdout)except json.JSONDecodeError as exc:@@ -155,24 +149,55 @@ def search_techmeme(to_date: str,depth: str = "default",) -> Dict[str, Any]:- """Search Techmeme headlines via techmeme-pp-cli.-- Ensures a one-time cache sync, then searches. Returns a dict with a- ``results`` list of raw records. On failure, ``results`` is empty.+ """Search Techmeme's live archive via techmeme-pp-cli.++ Windows records to ``from_date..to_date`` on each record's own ISO date+ (lexicographic compare is exact for ISO strings). Records with no usable+ date are kept -- their recency is resolved downstream as low confidence.+ There is deliberately no keep-all fallback when nothing is in-window:+ Techmeme's archive reaches back decades, so zero in-window records means+ zero results, not "serve stale news". Returns a dict with a ``results``+ list of raw records; on failure ``results`` is empty."""if not topic or not topic.strip():return {"results": []}if not _is_available():return {"results": [], "error": f"{CLI_BIN} not on PATH"}- _ensure_synced()limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])cmd = _build_search_args(topic)_log(f"search '{topic}' (cap={limit})")response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)- # Techmeme returns all matches; apply the depth cap client-side.records = response.get("results") or []- if isinstance(records, list) and len(records) > limit:- response["results"] = records[:limit]+ if isinstance(records, list):+ # Hard date window: drop records whose date falls outside the research+ # range; keep undated records (old binaries / unparseable markup).+ dated_in_window = []+ undated = []+ dropped = 0+ for rec in records:+ iso = _record_iso_date(rec)+ if iso is None:+ undated.append(rec)+ elif from_date <= iso <= to_date:+ dated_in_window.append(rec)+ else:+ dropped += 1+ if dropped:+ _log(f"dropped {dropped} records outside {from_date}..{to_date}")+ if records and not dated_in_window and not dropped:+ # Every record lacks a usable date: old techmeme-pp-cli (no date+ # key) or a Techmeme markup change upstream. Windowing is inactive.+ _log(+ "no records carry usable dates; date windowing inactive "+ "(old techmeme-pp-cli binary or upstream markup change; upgrade "+ "via `npx -y @mvanhorn/printing-press-library install techmeme "+ "--cli-only`)"+ )+ # Techmeme returns all matches; apply the depth cap after windowing.+ # Dated in-window records take cap slots first so undated archive+ # hits can never evict confirmed-fresh stories; undated records fill+ # whatever slots remain.+ response["results"] = (dated_in_window + undated)[:limit]_log(f"found {len(response.get('results') or [])} records")return response@@ -195,16 +220,16 @@ def parse_techmeme_response() -> List[Dict[str, Any]]:"""Parse a Techmeme search envelope into normalized item dicts.- Drops publication-name header rows and records missing a link. Dates each- headline to today (the cache is the current news cycle) and computes a- token-overlap relevance hint. Returns dicts ready for- ``normalize._normalize_techmeme``.+ Drops publication-name header rows and records missing a link. Each item+ carries the record's own ISO date, or None when the record has no usable+ date (never today's date -- undated items get ``date_confidence: low``+ downstream). Computes a token-overlap relevance hint. Returns dicts ready+ for ``normalize._normalize_techmeme``."""raw = response.get("results") if isinstance(response, dict) else Noneif not isinstance(raw, list):return []- today = _today_iso()items: List[Dict[str, Any]] = []for i, rec in enumerate(raw):if not isinstance(rec, dict):@@ -227,7 +252,7 @@ def parse_techmeme_response("title": headline,"url": link,"source_name": source_name,- "date": today,+ "date": _record_iso_date(rec),"engagement": {},"relevance": round(relevance, 2),"why_relevant": (diff --git a/tests/test_techmeme_source.py b/tests/test_techmeme_source.pyindex 2181bf81..61f4651d 100644--- a/tests/test_techmeme_source.py+++ b/tests/test_techmeme_source.py@@ -1,21 +1,29 @@"""Tests for the Techmeme source adapter (lib/techmeme.py).Covers the --json (not --agent) surface choice, header-row filtering,-field mapping, the one-time sync guard, and graceful degradation.+field mapping, date windowing to the research range, old-binary prose+tolerance, and graceful degradation."""from __future__ import annotations+import json+from datetime import datetime, timezone+import pytestfrom lib import techmeme[email protected](autouse=True)-def _reset_sync_flag():- techmeme._LAST_SYNC = techmeme._NEVER_SYNCED- yield- techmeme._LAST_SYNC = techmeme._NEVER_SYNCED+class _FakeProc:+ returncode = 0+ stdout = "{}"+ stderr = ""++ def __init__(self, stdout: str = "{}", returncode: int = 0, stderr: str = ""):+ self.stdout = stdout+ self.returncode = returncode+ self.stderr = stderr# ---- surface choice ----@@ -31,6 +39,189 @@ def test_search_args_use_json_not_agent():assert "search" in args and "AI agents" in args+def test_search_invokes_only_search_no_sync(monkeypatch):+ """search_techmeme must issue exactly one subprocess call -- the search --+ and never a `sync` (search hits Techmeme's live archive, not the cache)."""+ calls = []++ def fake_run(cmd, timeout):+ calls.append(list(cmd))+ return _FakeProc(stdout=json.dumps([+ {"num": 1, "source": "a.com",+ "headline": "A real in-window headline about the topic",+ "link": "https://t.co/a", "date": "2026-06-15"},+ ]))++ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme.subproc, "run_with_timeout", fake_run)+ out = techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27")+ assert len(out["results"]) == 1+ assert calls == [[techmeme.CLI_BIN, "search", "topic", "--json"]]+ assert not any("sync" in c for c in calls)+++# ---- date windowing ----++def _search_with_records(monkeypatch, records, from_date="2026-06-01", to_date="2026-06-27"):+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(+ techmeme.subproc, "run_with_timeout",+ lambda cmd, timeout: _FakeProc(stdout=json.dumps(records)),+ )+ return techmeme.search_techmeme("topic", from_date, to_date)+++def test_in_window_record_kept_with_real_date(monkeypatch):+ out = _search_with_records(monkeypatch, [+ {"num": 1, "source": "a.com",+ "headline": "Fresh in-window story about the research topic",+ "link": "https://t.co/a", "date": "2026-06-15"},+ ])+ assert len(out["results"]) == 1+ items = techmeme.parse_techmeme_response(out, query="topic")+ assert len(items) == 1+ # The item carries the record's real date, never today's.+ assert items[0]["date"] == "2026-06-15"+++def test_out_of_window_record_dropped(monkeypatch):+ out = _search_with_records(monkeypatch, [+ {"num": 1, "source": "a.com",+ "headline": "Stale Parler acquisition story from years ago",+ "link": "https://t.co/old", "date": "2022-12-02"},+ {"num": 2, "source": "b.com",+ "headline": "Fresh in-window story about the research topic",+ "link": "https://t.co/new", "date": "2026-06-15"},+ ])+ links = [r["link"] for r in out["results"]]+ assert links == ["https://t.co/new"]+++def test_zero_in_window_records_means_zero_results(monkeypatch):+ """No keep-all fallback: staleness is the bug, so all-stale means empty."""+ out = _search_with_records(monkeypatch, [+ {"num": 1, "source": "a.com",+ "headline": "Stale story number one from the archive",+ "link": "https://t.co/1", "date": "2022-12-02"},+ {"num": 2, "source": "b.com",+ "headline": "Stale story number two from the archive",+ "link": "https://t.co/2", "date": "2023-08-24"},+ ])+ assert out["results"] == []+++def test_window_endpoints_inclusive(monkeypatch):+ """Records dated exactly from_date or to_date survive the window; a+ strict-< regression would silently shave both edges."""+ out = _search_with_records(monkeypatch, [+ {"num": 1, "source": "a.com",+ "headline": "Story published exactly on the window start date",+ "link": "https://t.co/start", "date": "2026-06-01"},+ {"num": 2, "source": "b.com",+ "headline": "Story published exactly on the window end date",+ "link": "https://t.co/end", "date": "2026-06-27"},+ ])+ assert [r["link"] for r in out["results"]] == ["https://t.co/start", "https://t.co/end"]+++def test_non_string_and_whitespace_dates(monkeypatch):+ """Non-string date values (int/null) are treated as undated and kept;+ a valid ISO date with surrounding whitespace still parses."""+ out = _search_with_records(monkeypatch, [+ {"num": 1, "source": "a.com",+ "headline": "Record carrying an integer where the date belongs",+ "link": "https://t.co/int", "date": 20260615},+ {"num": 2, "source": "b.com",+ "headline": "Record carrying an explicit null date value",+ "link": "https://t.co/null", "date": None},+ {"num": 3, "source": "c.com",+ "headline": "Record with whitespace padded valid ISO date",+ "link": "https://t.co/ws", "date": " 2026-06-15 "},+ ])+ assert len(out["results"]) == 3+ items = techmeme.parse_techmeme_response(out, query="record")+ by_url = {it["url"]: it["date"] for it in items}+ assert by_url["https://t.co/int"] is None+ assert by_url["https://t.co/null"] is None+ assert by_url["https://t.co/ws"] == "2026-06-15"+++def test_dropped_records_logged(monkeypatch):+ logs = []+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme, "_log", lambda msg: logs.append(msg))+ monkeypatch.setattr(+ techmeme.subproc, "run_with_timeout",+ lambda cmd, timeout: _FakeProc(stdout=json.dumps([+ {"num": 1, "source": "a.com",+ "headline": "Stale story from the deep archive years back",+ "link": "https://t.co/old", "date": "2022-12-02"},+ ])),+ )+ techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27")+ assert "dropped 1 records outside 2026-06-01..2026-06-27" in logs+++def test_undated_records_kept_and_never_stamped_today(monkeypatch):+ """Old binaries emit no date key; unparseable dates come through as "" or+ junk. All are kept by the window, and parse yields date None -- never+ today's date."""+ out = _search_with_records(monkeypatch, [+ {"num": 1, "source": "a.com",+ "headline": "Headline with no date key from an old binary",+ "link": "https://t.co/nodate"},+ {"num": 2, "source": "b.com",+ "headline": "Headline whose date was unparseable upstream",+ "link": "https://t.co/empty", "date": ""},+ {"num": 3, "source": "c.com",+ "headline": "Headline carrying non ISO junk in the date",+ "link": "https://t.co/junk", "date": "May 22, 2025"},+ ])+ assert len(out["results"]) == 3+ items = techmeme.parse_techmeme_response(out, query="headline")+ assert len(items) == 3+ today = datetime.now(timezone.utc).date().isoformat()+ for item in items:+ assert item["date"] is None+ assert item["date"] != today+++# ---- old-binary prose tolerance ----++def test_no_results_prose_parses_as_empty_without_error(monkeypatch):+ """Old binaries print `No results for "q"` prose to stdout with exit 0 in+ JSON mode. That is a zero-hit response, not a decode failure."""+ logs = []+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme, "_log", lambda msg: logs.append(msg))+ monkeypatch.setattr(+ techmeme.subproc, "run_with_timeout",+ lambda cmd, timeout: _FakeProc(stdout='No results for "whatever query"\n'),+ )+ resp = techmeme._run_cli([techmeme.CLI_BIN, "search", "whatever query", "--json"],+ timeout=techmeme.SEARCH_TIMEOUT)+ assert resp == {"results": []}+ assert "error" not in resp+ assert not any("decode" in m.lower() for m in logs)+++def test_malformed_stdout_still_yields_decode_error(monkeypatch):+ """Genuinely malformed non-JSON stdout (not the prose sentinel) keeps the+ existing decode-error envelope."""+ logs = []+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme, "_log", lambda msg: logs.append(msg))+ monkeypatch.setattr(+ techmeme.subproc, "run_with_timeout",+ lambda cmd, timeout: _FakeProc(stdout="garbage <<<"),+ )+ resp = techmeme._run_cli([techmeme.CLI_BIN, "search", "topic", "--json"],+ timeout=techmeme.SEARCH_TIMEOUT)+ assert resp["results"] == []+ assert "json decode" in resp.get("error", "")+ assert any("decode" in m.lower() for m in logs)++# ---- header-row filtering ----def test_story_headline_accepts_sentence():@@ -46,10 +237,11 @@ def test_story_headline_rejects_publication_name_rows():def test_parse_drops_header_rows_keeps_stories():resp = {"results": [- {"num": 1, "source": "techcrunch.com", "headline": "TechCrunch", "link": "http://techcrunch.com/"},+ {"num": 1, "source": "techcrunch.com", "headline": "TechCrunch",+ "link": "http://techcrunch.com/", "date": "2026-06-27"},{"num": 2, "source": "techcrunch.com","headline": "Sakana AI's Fugu claims to rival frontier models",- "link": "https://www.techmeme.com/260627/p2"},+ "link": "https://www.techmeme.com/260627/p2", "date": "2026-06-27"},]}items = techmeme.parse_techmeme_response(resp, query="AI")@@ -57,10 +249,12 @@ def test_parse_drops_header_rows_keeps_stories():assert items[0]["title"].startswith("Sakana AI")assert items[0]["url"] == "https://www.techmeme.com/260627/p2"assert items[0]["source_name"] == "techcrunch.com"+ assert items[0]["date"] == "2026-06-27"def test_parse_drops_records_without_link():- resp = {"results": [{"num": 1, "source": "x.com", "headline": "A real headline sentence here", "link": ""}]}+ resp = {"results": [{"num": 1, "source": "x.com", "headline": "A real headline sentence here",+ "link": "", "date": "2026-06-27"}]}assert techmeme.parse_techmeme_response(resp, query="x") == []@@ -69,8 +263,10 @@ def test_parse_drops_records_without_link():def test_more_relevant_headline_ranks_higher():resp = {"results": [- {"num": 1, "source": "a.com", "headline": "Unrelated quarterly earnings report released today", "link": "https://t.co/a"},- {"num": 2, "source": "b.com", "headline": "New AI agent framework launches for developers", "link": "https://t.co/b"},+ {"num": 1, "source": "a.com", "headline": "Unrelated quarterly earnings report released today",+ "link": "https://t.co/a", "date": "2026-06-20"},+ {"num": 2, "source": "b.com", "headline": "New AI agent framework launches for developers",+ "link": "https://t.co/b", "date": "2026-06-20"},]}items = techmeme.parse_techmeme_response(resp, query="AI agent framework")@@ -86,45 +282,104 @@ def test_coerce_list_handles_bare_array_and_wrapped():assert techmeme._coerce_list({"nope": 1}) == []-# ---- sync guard + degradation ------def test_sync_runs_once_per_process(monkeypatch):- calls = []- monkeypatch.setattr(techmeme, "_is_available", lambda: True)- monkeypatch.setattr(techmeme.subproc, "run_with_timeout",- lambda cmd, timeout: calls.append(cmd) or _FakeProc())- techmeme._ensure_synced()- techmeme._ensure_synced()- sync_calls = [c for c in calls if "sync" in c]- assert len(sync_calls) == 1---def test_sync_failure_is_swallowed_and_latched(monkeypatch):- """A sync that raises must not propagate, and the TTL stamp must still latch- so search proceeds against the existing cache."""- def boom(cmd, timeout):- raise techmeme.subproc.SubprocTimeout("sync timed out")- monkeypatch.setattr(techmeme.subproc, "run_with_timeout", boom)- techmeme._ensure_synced() # must not raise- assert techmeme._LAST_SYNC != techmeme._NEVER_SYNCED # latched despite failure-+# ---- depth cap + degradation ----@pytest.mark.parametrize("depth,cap", [("quick", 8), ("default", 16), ("deep", 30)])def test_depth_cap_truncates_client_side(monkeypatch, depth, cap):"""Techmeme `search` has no limit flag, so the depth cap is applied after- parsing -- regression guard for the other half of the --max-results fix."""+ windowing -- regression guard for the other half of the --max-results fix.+ All records are in-window, so the cap alone decides the count."""records = [{"num": i, "source": "x.com", "headline": f"A real headline sentence number {i}",- "link": f"https://t.co/{i}"}+ "link": f"https://t.co/{i}", "date": "2026-06-15"}for i in range(cap + 12)]monkeypatch.setattr(techmeme, "_is_available", lambda: True)- monkeypatch.setattr(techmeme, "_ensure_synced", lambda: None)monkeypatch.setattr(techmeme, "_run_cli", lambda cmd, timeout: {"results": list(records)})out = techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27", depth=depth)assert len(out["results"]) == cap+def test_depth_cap_applies_after_windowing(monkeypatch):+ """Stale records must not consume cap slots: with cap in-window records+ plus stale ones interleaved ahead of them, every in-window record+ survives."""+ cap = techmeme.DEPTH_CONFIG["quick"]+ stale = [+ {"num": i, "source": "old.com", "headline": f"Stale archive headline number {i}",+ "link": f"https://t.co/old{i}", "date": "2022-01-10"}+ for i in range(cap)+ ]+ fresh = [+ {"num": 100 + i, "source": "new.com", "headline": f"Fresh in window headline number {i}",+ "link": f"https://t.co/new{i}", "date": "2026-06-15"}+ for i in range(cap)+ ]+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme, "_run_cli",+ lambda cmd, timeout: {"results": stale + fresh})+ out = techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27", depth="quick")+ links = [r["link"] for r in out["results"]]+ assert links == [f"https://t.co/new{i}" for i in range(cap)]+++def test_dated_records_take_cap_slots_before_undated(monkeypatch):+ """Undated archive hits must never evict confirmed in-window stories:+ dated in-window records fill cap slots first, undated fill the rest."""+ cap = techmeme.DEPTH_CONFIG["quick"]+ undated = [+ {"num": i, "source": "old.com", "headline": f"Undated old binary headline number {i}",+ "link": f"https://t.co/u{i}"}+ for i in range(cap)+ ]+ dated = [+ {"num": 100 + i, "source": "new.com", "headline": f"Dated in window headline number {i}",+ "link": f"https://t.co/d{i}", "date": "2026-06-15"}+ for i in range(cap)+ ]+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ # Undated arrive first in CLI order; dated in-window must still win the cap.+ monkeypatch.setattr(techmeme, "_run_cli",+ lambda cmd, timeout: {"results": undated + dated})+ out = techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27", depth="quick")+ links = [r["link"] for r in out["results"]]+ assert links == [f"https://t.co/d{i}" for i in range(cap)]+++def test_all_undated_flood_capped_with_windowing_inactive_hint(monkeypatch):+ """The realistic old-binary case: every record undated. The cap still+ applies, and a windowing-inactive hint is logged."""+ cap = techmeme.DEPTH_CONFIG["quick"]+ logs = []+ records = [+ {"num": i, "source": "x.com", "headline": f"Undated archive headline number {i}",+ "link": f"https://t.co/{i}"}+ for i in range(cap + 12)+ ]+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme, "_log", lambda msg: logs.append(msg))+ monkeypatch.setattr(techmeme, "_run_cli", lambda cmd, timeout: {"results": records})+ out = techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27", depth="quick")+ assert len(out["results"]) == cap+ assert any("date windowing inactive" in m for m in logs)+++def test_windowing_inactive_hint_absent_when_dates_present(monkeypatch):+ """The hint must not fire when the binary emits dates -- even if every+ dated record is out of window (windowing IS active there)."""+ logs = []+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)+ monkeypatch.setattr(techmeme, "_log", lambda msg: logs.append(msg))+ monkeypatch.setattr(techmeme, "_run_cli", lambda cmd, timeout: {"results": [+ {"num": 1, "source": "a.com", "headline": "Stale but properly dated archive story",+ "link": "https://t.co/old", "date": "2022-12-02"},+ {"num": 2, "source": "b.com", "headline": "Undated companion record from mixed output",+ "link": "https://t.co/mixed"},+ ]})+ techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27")+ assert not any("date windowing inactive" in m for m in logs)++@pytest.mark.parametrize("words,expected", [(3, False), (4, True)])def test_story_headline_word_count_boundary(words, expected):headline = " ".join(["word"] * words)@@ -150,9 +405,3 @@ def test_empty_topic_returns_empty():def test_parse_handles_non_list_results():assert techmeme.parse_techmeme_response({"results": "oops"}, query="x") == []assert techmeme.parse_techmeme_response({}, query="x") == []---class _FakeProc:- returncode = 0- stdout = "{}"- stderr = ""