Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: Twitter/X integration, filter improvements, Agent-Reach, schedule updates, WORKFLOW docs

Tiioluwani657982634329
diff --git a/ai_agents/devable_research_agent/.env.example b/ai_agents/devable_research_agent/.env.example
index aa45a1f..501ec9a 100644
--- a/ai_agents/devable_research_agent/.env.example
+++ b/ai_agents/devable_research_agent/.env.example
@@ -1,10 +1,15 @@
# Copy to .env or ~/.config/morning-ai/.env and fill in values.
+# Project root for cross-platform paths (OpenClaw prompt, pipeline scripts)
+DEVABLE_PROJECT_ROOT=C:\Users\HP\Documents\MorningAI
+
MESSAGE_ENABLED=true
ARXIV_LOOKBACK_DAYS=1
GITHUB_TOKEN=
TAVILY_API_KEY=
+TWITTER_AUTH_TOKEN=
+TWITTER_CT0=
MISTRAL_API_KEY=
OPENAI_API_KEY=
GEMINI_API_KEY=
diff --git a/ai_agents/devable_research_agent/.gitignore b/ai_agents/devable_research_agent/.gitignore
index 1553907..9d7ad43 100644
--- a/ai_agents/devable_research_agent/.gitignore
+++ b/ai_agents/devable_research_agent/.gitignore
@@ -1,19 +1,38 @@
-__pycache__/
-*.pyc
-*.pyo
-.env
-.env.local
-env.local
-/data_*.json
-data_today.json
-digest_input_today.json
-digest_input_*.json
-logs/delivered_items.json
-logs/pipeline.log
-entities/custom/*.md
-goodailist_debug.html
-*_test.json
-temp_digest*
-digest_output_today.md
-digest_for_slack.txt
-notepad
+__pycache__/
+
+*.pyc
+
+*.pyo
+
+.env
+
+.env.local
+
+env.local
+
+/data_*.json
+
+data_today.json
+
+digest_input_today.json
+
+digest_input_*.json
+
+logs/delivered_items.json
+
+logs/pipeline.log
+
+entities/custom/*.md
+
+goodailist_debug.html
+
+*_test.json
+
+temp_digest*
+
+digest_output_today.md
+
+digest_for_slack.txt
+
+notepad
+
diff --git a/ai_agents/devable_research_agent/WORKFLOW.md b/ai_agents/devable_research_agent/WORKFLOW.md
index 2e7a128..0ca765b 100644
--- a/ai_agents/devable_research_agent/WORKFLOW.md
+++ b/ai_agents/devable_research_agent/WORKFLOW.md
@@ -6,7 +6,7 @@ This document explains how the AI Research Agent works for anyone on the team wh
## 1. What is this?
-The **Devable Research Agent** (also called the AI Research Agent) is an automated daily briefing for AI engineering news. Every weekday morning it collects signals from papers, repos, models, community threads, and web sources, picks the most useful items, and posts a curated digest to Slack.
+The **Devable Research Agent** (also called the AI Research Agent) is an automated daily briefing for AI engineering news. Every weekday morning it collects signals from papers, repos, models, community threads, X, and web sources, picks the most useful items, and posts a curated digest to Slack.
We built it so the team stays current on what matters for builders (new models, repos, tools, papers, and community signals) without manually checking dozens of sites. The goal is one reliable Slack message each morning, written for engineers who ship products.
@@ -14,7 +14,7 @@ We built it so the team stays current on what matters for builders (new models,
## 2. What it collects and where from
-The agent pulls from **seven sources**. Each source feeds into a shared daily file before filtering.
+The agent pulls from **eight sources**. Each source feeds into a shared daily file before filtering. Tavily is still in the table but paused when credits run out.
| Source | What we get | Where it comes from |
|--------|------------|---------------------|
@@ -24,7 +24,8 @@ The agent pulls from **seven sources**. Each source feeds into a shared daily fi
| **Hacker News** | Community discussions and Show HN launches | Hacker News via Algolia search |
| **Good AI List** | Curated AI engineering repos | [goodailist.com](https://goodailist.com/repos) (Chip Huyen's list), scraped with Playwright |
| **AINews (smol.ai)** | Daily digest of Reddit, X, and Discord highlights | RSS feed + HTML parsing from [news.smol.ai](https://news.smol.ai) |
-| **Tavily** | Web signals and release announcements | Tavily Search API (**currently paused**: free tier credits exhausted) |
+| **Twitter/X** | KOL posts, team accounts, and search hits for LLM releases, agent frameworks, model weights, and inference engines | `twitter-cli` via `lib/twitter_collector.py` (subprocess). Auth: `TWITTER_AUTH_TOKEN` + `TWITTER_CT0` in `~/.config/morning-ai/.env`. Watches `@askalphaxiv`, `@huggingpapers`, `@dair_ai`, `@ArtificialAnlys` plus fixed search queries. Replaces the old `x_agent.py` (Anthropic API), which is deprecated and not used. |
+| **Tavily** | Web signals and release announcements | Tavily Search API (**currently paused** when free tier credits are exhausted) |
**Entity tracking:** We watch 80+ companies, labs, and tools defined in markdown files under `entities/`. Collectors use those lists to decide what to search for, rather than generic keyword scraping.
@@ -34,6 +35,12 @@ The agent pulls from **seven sources**. Each source feeds into a shared daily fi
The pipeline runs in three steps: **collect**, **filter**, **deliver**.
+### Step 0 - OpenClaw gateway (7:30am Lagos time)
+
+- **Windows Task Scheduler** runs `scripts/start_openclaw_gateway.bat` (or the registered OpenClaw Gateway task) so the gateway is up before the pipeline and cron.
+- OpenClaw version: **2026.7.1**.
+- Telegram is **disabled** in `~/.openclaw/openclaw.json`; Slack is the only delivery channel.
+
### Step 1 - Collect (7:45am Lagos time)
- **Windows Task Scheduler** runs `scripts/run_pipeline.bat`.
@@ -45,18 +52,28 @@ The pipeline runs in three steps: **collect**, **filter**, **deliver**.
- `scripts/filter_top_items.py` reads `data_today.json`.
- It selects the best items using:
- - **LLM paper relevance scoring (Mistral):** arXiv papers scored 1-5; low-scoring papers are dropped.
- - **Category diversity quotas:** Ensures mix of papers, repos, web signals, X (via AINews), Hacker News, and Good AI List items (not all from one source).
+ - **LLM paper relevance scoring (Mistral):** arXiv papers scored 1-5; low-scoring papers are dropped. Scores are cached and written to **`logs/paper_scores_today.json`**.
+ - **Pre-written digest descriptions:** Mistral generates a short one-line `digest_description` per item during filter so OpenClaw has consistent copy to work from.
+ - **Category diversity quotas:** Rebalanced min/max per bucket (papers, GitHub, web, AINews, X, Hacker News, HuggingFace, Good AI List) so the digest is not dominated by one source.
- **Frequency cap:** The same GitHub or Good AI List repo will not dominate the digest; repos that appeared twice in the last **30 days** are held back.
- - **Deduplication log:** Items already delivered in the last **7-14 days** (depending on source) are skipped so stories do not repeat.
+ - **Deduplication log:** Items already delivered are skipped. GitHub **releases** dedupe by repo + semver. **Shorter lookbacks (3 days)** apply to GitHub Trending, AINews, and HN Show/Launch items so fresh stories can surface without repeating older ones.
- **Mistral editorial verify:** A second pass removes items that duplicate recent deliveries or overlap the same story.
+ - **Rejected items log:** Dropped items are written to **`logs/rejected_items_today.json`** for debugging.
- Output: **`digest_input_today.json`** with up to **20 items**, plus updates to **`logs/delivered_items.json`**.
+- **Debug:** Run filter with `--debug` for a per-stage breakdown (collection counts, dedup, quotas, verify).
### Step 3 - Deliver (8:00am Lagos time)
-- **OpenClaw cron** runs on the team machine.
-- It reads `digest_input_today.json`, editorial rules from `~/.config/morning-ai/editorial_profile.md`, and formatting rules from `scripts/openclaw_digest_prompt.txt`.
-- Mistral writes the final digest text and OpenClaw posts it to the team Slack channel automatically.
+- **OpenClaw cron** runs on the team machine (job: AI Research Agent).
+- Model: **`mistral-openai/mistral-small-latest`**.
+- Cron delivery mode is **`none`** (not `announce`) so OpenClaw does not auto-post the agent's final reply.
+- The cron job allows **`read`** and **`message`** tools only (`toolsAllow: ["read", "message"]`).
+- The agent reads `digest_input_today.json`, editorial rules from `~/.config/morning-ai/editorial_profile.md`, and formatting rules from `scripts/openclaw_digest_prompt.txt`.
+- The agent posts to Slack channel **`C0BH9MD221H`** via the OpenClaw **`message` tool** in two steps:
+ 1. **Top-level message:** title only, e.g. `πŸ“° AI Engineering Digest - 2026-07-17`
+ 2. **Thread reply:** all section content (papers, repos, X, etc.) using `threadId` from step 1's returned `messageId`
+- The agent's final assistant reply is a brief internal confirmation only (not posted to Slack).
+- Slack config in `~/.openclaw/openclaw.json`: **`unfurlLinks: false`** and **`unfurlMedia: false`** so bot messages do not expand link preview cards. The digest still uses `<https://url|link>` on every item line as a belt-and-braces rule.
**Manual runs:** Anyone can run `scripts/run_pipeline.bat` or `python scripts/run_pipeline.py` to collect and filter on demand. Use `scripts/refresh_digest_input.bat` to re-filter without re-collecting.
@@ -64,13 +81,17 @@ The pipeline runs in three steps: **collect**, **filter**, **deliver**.
## 4. What the digest looks like
-The Slack message uses emoji section headers. **Empty sections are omitted** (if there are no qualifying papers that day, the Papers section does not appear).
+The digest uses a **title + thread** layout in Slack. The top-level channel message is the title only; all section content lives in a thread reply beneath it. **Empty sections are omitted** (if there are no qualifying papers that day, the Papers section does not appear).
-Typical structure:
+**Top-level message (title only):**
```
πŸ“° AI Engineering Digest - 2026-07-10
+```
+
+**Thread reply (all sections):**
+```
πŸ“„ Top Papers
- Paper title - short technical description - <https://arxiv.org/abs/1234|link>
@@ -96,6 +117,8 @@ Typical structure:
- Links must use Slack format `<https://full-url|link>` so Slack does not show large preview cards.
- Bare URLs like `https://example.com` are not allowed in the digest.
- Descriptions should be specific and technical, not marketing fluff.
+- OpenClaw cron delivery mode is **`none`**: the agent posts via the **`message` tool** (title first, then thread); the agent's final reply is not delivered to Slack.
+- The cron job must allow **`read`** and **`message`** tools (`--tools read,message`). Without `message`, delivery fails silently.
---
@@ -103,9 +126,9 @@ Typical structure:
| Provider | Model | Used for |
|----------|-------|----------|
-| **Mistral** | Mistral Small (`mistral-small-latest`) | Digest writing (OpenClaw), arXiv paper relevance scoring, editorial verify step in filter |
-| **Gemini** | Gemini 2.0 Flash | Planned for native X/Twitter search when Anthropic credits are restored |
-| **OpenAI** | GPT-4o-mini | Fallback option in the broader stack |
+| **Mistral** | Mistral Small (`mistral-small-latest`) | arXiv paper relevance scoring, editorial verify, pre-written `digest_description` in the filter step |
+| **Mistral (OpenAI-compatible)** | `mistral-openai/mistral-small-latest` | OpenClaw cron digest generation (daily Slack post) |
+| **OpenAI** | GPT-4o-mini (or upgraded ref via `openclaw doctor`) | Fallback option in the broader OpenClaw stack |
OpenClaw is configured to use Mistral via an OpenAI-compatible provider for daily digest generation.
@@ -115,12 +138,12 @@ OpenClaw is configured to use Mistral via an OpenAI-compatible provider for dail
| Area | Status |
|------|--------|
-| **X (Twitter)** | Native X collector is off. Anthropic credits for the original approach are exhausted. Gemini has limited X visibility. **AINews covers X indirectly** via smol.ai Twitter sections. |
+| **X (Twitter)** | **Active** via `twitter-cli` and `lib/twitter_collector.py`. Requires valid `TWITTER_AUTH_TOKEN` and `TWITTER_CT0` in `~/.config/morning-ai/.env`. AINews still adds indirect X coverage from smol.ai. |
| **Reddit** | Direct Reddit collection is geo-restricted from Nigeria. **AINews covers Reddit indirectly** via high-activity threads in smol.ai issues. |
-| **Tavily** | Free tier credits exhausted. Collector code remains but **web search via Tavily is paused** until credits are renewed. |
+| **Tavily** | Free tier credits can be exhausted. Collector code remains but **web search via Tavily is paused** until credits are renewed. |
| **Good AI List** | Requires **Playwright** and **Chromium** installed on the machine. If missing, Good AI List returns zero items but the rest of the pipeline still runs. |
-| **Paths and OS** | Automation is set up for **Windows** (Task Scheduler, batch scripts). Some OpenClaw prompt paths still reference `C:\Users\HP\Documents\MorningAI`. Cross-platform and fully portable paths are pending. |
-| **Config location** | API keys and editorial profile live in `~/.config/morning-ai/` (legacy name from the upstream MorningAI project). |
+| **Paths and OS** | Automation is set up for **Windows** (Task Scheduler, batch scripts). Cross-platform path handling exists in the pipeline; OpenClaw state lives under `~/.openclaw/`. |
+| **Config location** | API keys and editorial profile live in `~/.config/morning-ai/` (legacy name from the upstream MorningAI project). OpenClaw config: `~/.openclaw/openclaw.json`. |
---
@@ -130,12 +153,12 @@ For full setup (Python packages, API keys, Task Scheduler, OpenClaw cron, Slack
Quick checklist for a new team member:
-1. Install Python 3.9+ and optional packages (`mistralai`, `feedparser`, `playwright`, `tavily-python`).
-2. Copy `.env.example` to `~/.config/morning-ai/.env` and add keys (Mistral required, Tavily when renewed, GitHub token optional).
+1. Install Python 3.9+ and optional packages (`mistralai`, `feedparser`, `playwright`, `tavily-python`, `twitter-cli` for X).
+2. Copy `.env.example` to `~/.config/morning-ai/.env` and add keys (Mistral required, Twitter cookies for X, Tavily when renewed, GitHub token optional).
3. Create `~/.config/morning-ai/editorial_profile.md` with team editorial rules.
-4. Configure OpenClaw with Slack and Mistral (see README).
-5. Schedule `scripts/run_pipeline.bat` at 7:45am Lagos time.
-6. Confirm OpenClaw cron at 8:00am reads `digest_input_today.json`.
+4. Configure OpenClaw **2026.7.1** with Slack (disable Telegram if unused), `unfurlLinks` / `unfurlMedia` false, and Mistral (see README).
+5. Schedule OpenClaw gateway start at **7:30am** Lagos and `scripts/run_pipeline.bat` at **7:45am** Lagos time.
+6. Confirm OpenClaw cron at **8:00am** reads `digest_input_today.json`, uses delivery mode **`none`**, and posts title + thread to Slack channel `C0BH9MD221H` via the `message` tool.
**Useful commands:**
@@ -146,8 +169,14 @@ python scripts/run_pipeline.py
# Re-filter only (after rule changes)
scripts\refresh_digest_input.bat
+# Filter with stage breakdown
+python scripts/filter_top_items.py --debug
+
# Sync digest prompt to OpenClaw after editing openclaw_digest_prompt.txt
python scripts/update_openclaw_cron.py
+
+# Gateway status
+openclaw gateway status
```
---
@@ -156,5 +185,7 @@ python scripts/update_openclaw_cron.py
- **Pipeline logs:** `logs/pipeline.log`
- **What was already sent:** `logs/delivered_items.json`
+- **Paper scores today:** `logs/paper_scores_today.json`
+- **Rejected items today:** `logs/rejected_items_today.json`
- **Digest input for today:** `digest_input_today.json` (regenerated each run, not committed to git)
- **Developer details:** [README.md](README.md)
diff --git a/ai_agents/devable_research_agent/lib/env.py b/ai_agents/devable_research_agent/lib/env.py
index c5b6bcf..d0c9013 100644
--- a/ai_agents/devable_research_agent/lib/env.py
+++ b/ai_agents/devable_research_agent/lib/env.py
@@ -39,7 +39,9 @@ def get_config() -> Dict[str, Any]:
config.update(project_claude_env)
config.update(project_env)
config.update(local_env)
- config.update({k: v for k, v in os.environ.items() if k.startswith(("MORNING_AI_", "GITHUB_", "TAVILY_", "OPENAI_", "MISTRAL_", "ANTHROPIC_"))})
+ config.update({k: v for k, v in os.environ.items() if k.startswith((
+ "MORNING_AI_", "GITHUB_", "TAVILY_", "OPENAI_", "MISTRAL_", "ANTHROPIC_", "TWITTER_",
+ ))})
return config
@@ -60,4 +62,5 @@ def get_available_sources(config: Dict[str, Any]) -> Dict[str, bool]:
"tavily": bool(get_key(config, "TAVILY_API_KEY")),
"goodailist": True,
"ainews": True,
+ "x": bool(get_key(config, "TWITTER_AUTH_TOKEN") and get_key(config, "TWITTER_CT0")),
}
diff --git a/ai_agents/devable_research_agent/lib/goodailist_scraper.py b/ai_agents/devable_research_agent/lib/goodailist_scraper.py
index c064e07..dc7167a 100644
--- a/ai_agents/devable_research_agent/lib/goodailist_scraper.py
+++ b/ai_agents/devable_research_agent/lib/goodailist_scraper.py
@@ -1,329 +1,766 @@
"""Good AI List scraper for devable-research-agent.
+
+
Scrapes trending open-source AI repos from https://goodailist.com/repos using
+
Playwright (JavaScript-rendered table). Extracts repo name, description,
+
GitHub URL, star counts, and weekly star momentum.
+
+
Requires ``playwright`` and a Chromium install (``playwright install chromium``).
+
"""
+
+
import hashlib
+
import math
+
+import os
+
import re
+
+from datetime import datetime, timedelta, timezone
+
+from pathlib import Path
+
from typing import Any, Dict, List, Optional
+
+
try:
+
from playwright.sync_api import sync_playwright
+
_HAS_PLAYWRIGHT = True
+
except ImportError:
+
sync_playwright = None # type: ignore[misc, assignment]
+
_HAS_PLAYWRIGHT = False
+
+
from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_REPO
+
from .util import log, parse_date
+
+
GOOD_AI_LIST_URL = "https://goodailist.com/repos"
+
DEBUG_HTML_PATH = "goodailist_debug.html"
+
AI_ENGINEERING_CATEGORY = "AI Engineering"
+
DEPTH_LIMITS = {"quick": 25, "default": 50, "deep": 100}
+
PAGE_TIMEOUT_MS = 90_000
+
TABLE_READY_SELECTOR = "#repos-table tbody tr td.repo-cell a[href*='github.com']"
+TZ_CN = timezone(timedelta(hours=8))
+
+
+
_EXTRACT_ROWS_JS = """
+
() => {
+
const parseIntSafe = (text) => {
+
const n = parseInt(String(text || '').replace(/,/g, ''), 10);
+
return Number.isFinite(n) ? n : 0;
+
};
+
const parseMomentum = (text) => {
+
const lines = String(text || '').split('\\n').map((s) => s.trim()).filter(Boolean);
+
const deltaRaw = lines[0] || '';
+
const pctRaw = lines[1] || '';
+
const delta = parseIntSafe(deltaRaw.replace(/[^0-9-]/g, ''));
+
const pct = parseFloat(String(pctRaw).replace('%', '')) || 0;
+
return { delta, pct };
+
};
+
+
const rows = [];
+
for (const tr of document.querySelectorAll('#repos-table tbody tr')) {
+
const repoCell = tr.querySelector('td.repo-cell');
+
const link = repoCell?.querySelector('a[href*="github.com"]');
+
if (!link) continue;
+
+
const owner = (link.querySelector('.repo-owner')?.textContent || '').trim();
+
const name = (link.querySelector('.repo-name')?.textContent || '').trim();
+
const repoName = (link.getAttribute('title') || '').trim()
+
|| (owner && name ? `${owner}/${name}` : '');
+
if (!repoName.includes('/')) continue;
+
+
const rank = parseIntSafe(tr.querySelector('td.dim')?.textContent || '');
+
+
const starsCell = repoCell?.nextElementSibling;
+
const stars = parseIntSafe(starsCell?.textContent || '');
+
+
const day1Cell = starsCell?.nextElementSibling;
+
const day1 = parseMomentum(day1Cell?.innerText || '');
+
const day7Cell = day1Cell?.nextElementSibling;
+
const weekly = parseMomentum(day7Cell?.innerText || '');
+
+
const forksCell = day7Cell?.nextElementSibling;
+
const forks = parseIntSafe(forksCell?.textContent || '');
+
+
const description = (tr.querySelector('.desc-cell')?.textContent || '').trim();
+
const category = (tr.querySelector('.category-link')?.textContent || '').trim();
+
const subcategory = [...tr.querySelectorAll('.subcat-link')]
+
.map((el) => el.textContent.trim())
+
.filter(Boolean)
+
.join(', ');
+
+
const isoDates = [...tr.querySelectorAll('td.dim')]
+
.map((td) => td.textContent.trim())
+
.filter((value) => /^\\d{4}-\\d{2}-\\d{2}$/.test(value));
+
const created = isoDates[0] || '';
+
const updated = isoDates[1] || isoDates[0] || '';
+
+
rows.push({
+
repo_name: repoName,
+
url: link.href,
+
rank,
+
stars,
+
daily_stars: day1.delta,
+
daily_pct: day1.pct,
+
weekly_stars: weekly.delta,
+
weekly_pct: weekly.pct,
+
forks,
+
description,
+
category,
+
subcategory,
+
created,
+
updated,
+
});
+
}
+
return rows;
+
}
+
"""
+
+
_log = lambda msg: log("GoodAIList", msg, tty_only=True)
+
+
+
+def _pipeline_log_path() -> Path:
+
+ root = Path(os.environ.get("DEVABLE_PROJECT_ROOT", ".")).resolve()
+
+ return root / "logs" / "pipeline.log"
+
+
+
+
+
+def _pipeline_log(message: str) -> None:
+
+ path = _pipeline_log_path()
+
+ path.parent.mkdir(parents=True, exist_ok=True)
+
+ timestamp = datetime.now(TZ_CN).strftime("%Y-%m-%d %H:%M:%S")
+
+ with path.open("a", encoding="utf-8") as handle:
+
+ handle.write(f"[{timestamp}] {message}\n")
+
+
+
+
+
def _repo_id(repo_name: str) -> str:
+
slug = re.sub(r"[^a-zA-Z0-9]+", "-", repo_name).strip("-").lower()
+
if slug:
+
return f"REPO-{slug}"
+
digest = hashlib.md5(repo_name.encode("utf-8")).hexdigest()[:12]
+
return f"REPO-{digest}"
+
+
+
def _apply_ai_engineering_new_only_filters(page) -> None:
+
"""Filter Good AI List to AI Engineering category and NEW repos only."""
+
page.goto(GOOD_AI_LIST_URL, wait_until="networkidle", timeout=PAGE_TIMEOUT_MS)
+
page.wait_for_selector(TABLE_READY_SELECTOR, timeout=PAGE_TIMEOUT_MS)
+
+
page.locator("#category-filter-btn").click()
+
page.locator("#category-filter-menu").wait_for(state="visible", timeout=PAGE_TIMEOUT_MS)
+
+
for checkbox in page.locator("#category-filter-menu input[type=checkbox]").all():
+
checkbox_id = checkbox.get_attribute("id") or ""
+
want_checked = checkbox_id == f"cat-{AI_ENGINEERING_CATEGORY}"
+
if checkbox.is_checked() != want_checked:
+
checkbox.set_checked(want_checked)
+
+
page.locator("#category-filter-btn").click()
+
+
new_only = page.locator("#repos-new-only")
+
if not new_only.is_checked():
+
new_only.check()
+
+
page.wait_for_load_state("networkidle")
+
page.wait_for_selector(TABLE_READY_SELECTOR, timeout=PAGE_TIMEOUT_MS)
+
+
+
def _build_entity_lookup(
+
github_sources: Dict[str, Dict[str, Any]],
+
) -> tuple:
+
org_to_entity: Dict[str, str] = {}
+
repo_to_entity: Dict[str, str] = {}
+
for entity_name, sources in github_sources.items():
+
for org in sources.get("orgs", []):
+
org_to_entity[org.lower()] = entity_name
+
for repo in sources.get("repos", []):
+
repo_to_entity[repo.lower()] = entity_name
+
return org_to_entity, repo_to_entity
+
+
+
def _match_entity(
+
repo_name: str,
+
org_to_entity: Dict[str, str],
+
repo_to_entity: Dict[str, str],
+
) -> Optional[str]:
+
key = repo_name.lower()
+
if key in repo_to_entity:
+
return repo_to_entity[key]
+
owner = key.split("/")[0] if "/" in key else ""
+
return org_to_entity.get(owner)
+
+
+
def _compute_relevance(rank: int, weekly_stars: int, weekly_pct: float, category: str) -> float:
+
rank_score = max(0.3, 1.0 - max(0, rank - 1) * 0.008)
+
momentum = min(1.0, math.log1p(max(0, weekly_stars)) / 9.0 + max(0.0, weekly_pct) / 250.0)
+
relevance = min(1.0, rank_score * 0.45 + momentum * 0.45 + 0.1)
+
if "ai engineering" in (category or "").lower():
+
relevance = min(1.0, relevance + 0.05)
+
return round(relevance, 2)
+
+
+
def dump_page_html(path: str = DEBUG_HTML_PATH) -> int:
+
"""Navigate to Good AI List and save rendered HTML for DOM debugging."""
+
if not _HAS_PLAYWRIGHT:
+
raise RuntimeError("playwright not installed β€” run: pip install playwright")
+
+
with sync_playwright() as p:
+
browser = p.chromium.launch(headless=True)
+
try:
+
page = browser.new_page()
+
_apply_ai_engineering_new_only_filters(page)
+
html = page.content()
+
with open(path, "w", encoding="utf-8") as handle:
+
handle.write(html)
+
finally:
+
browser.close()
+
return len(html)
-def scrape_rows(depth: str = "default", debug_html_path: Optional[str] = None) -> List[Dict[str, Any]]:
- """Scrape AI Engineering NEW repos from Good AI List."""
- if not _HAS_PLAYWRIGHT:
- raise RuntimeError("playwright not installed β€” run: pip install playwright")
+
+
+
+def _scrape_rows_once(depth: str, debug_html_path: Optional[str]) -> List[Dict[str, Any]]:
limit = DEPTH_LIMITS.get(depth, DEPTH_LIMITS["default"])
with sync_playwright() as p:
+
browser = p.chromium.launch(headless=True)
+
try:
+
page = browser.new_page()
+
_apply_ai_engineering_new_only_filters(page)
+
if debug_html_path:
+
with open(debug_html_path, "w", encoding="utf-8") as handle:
+
handle.write(page.content())
+
rows = page.evaluate(_EXTRACT_ROWS_JS)
+
finally:
+
browser.close()
+
+
if not isinstance(rows, list):
+
return []
+
+
filtered = [
+
row for row in rows
+
if (row.get("category") or "").strip().lower() == "ai engineering"
+
]
+
_log(
+
f"Scraped {len(rows)} rows after filters; "
+
f"{len(filtered)} AI Engineering repos"
+
)
+
return filtered[:limit]
+
+
+
+def scrape_rows(depth: str = "default", debug_html_path: Optional[str] = None) -> List[Dict[str, Any]]:
+
+ """Scrape AI Engineering NEW repos from Good AI List (with one retry)."""
+
+ if not _HAS_PLAYWRIGHT:
+
+ raise RuntimeError("playwright not installed β€” run: pip install playwright")
+
+
+
+ last_error: Optional[Exception] = None
+
+ for attempt in range(2):
+
+ try:
+
+ rows = _scrape_rows_once(depth, debug_html_path)
+
+ if rows:
+
+ return rows
+
+ if attempt == 0:
+
+ _log("Good AI List returned 0 items on first attempt β€” retrying once")
+
+ continue
+
+ _pipeline_log(
+
+ "Good AI List returned 0 items - check Playwright and Chromium installation"
+
+ )
+
+ return []
+
+ except Exception as exc:
+
+ last_error = exc
+
+ if attempt == 0:
+
+ _log(f"Good AI List scrape failed (attempt 1): {exc} β€” retrying once")
+
+ continue
+
+ raise exc
+
+
+
+ if last_error:
+
+ raise last_error
+
+ _pipeline_log(
+
+ "Good AI List returned 0 items - check Playwright and Chromium installation"
+
+ )
+
+ return []
+
+
+
+
+
def _row_to_item(
+
row: Dict[str, Any],
+
entity: str,
+
to_date: str,
+
) -> Optional[TrackerItem]:
+
repo_name = (row.get("repo_name") or "").strip()
+
url = (row.get("url") or "").strip()
+
description = (row.get("description") or "").strip()
+
if not repo_name or not url:
+
return None
+
+
updated = parse_date(row.get("updated")) or to_date
+
weekly_stars = int(row.get("weekly_stars") or 0)
+
weekly_pct = float(row.get("weekly_pct") or 0)
+
stars = int(row.get("stars") or 0)
+
forks = int(row.get("forks") or 0)
+
rank = int(row.get("rank") or 0)
+
category = row.get("category") or ""
+
+
summary = description[:300] if description else f"Trending repo with {stars:,} stars"
+
if weekly_stars:
+
summary = f"{summary} (+{weekly_stars:,} stars this week, {weekly_pct:+.1f}%)".strip()
+
+
return TrackerItem(
+
id=_repo_id(repo_name),
+
title=repo_name,
+
summary=summary[:300],
+
entity=entity,
+
source=SOURCE_REPO,
+
source_url=url,
+
source_label="Good AI List",
+
date=updated,
+
date_confidence="high" if updated else "med",
+
raw_text=description,
+
engagement=Engagement(stars=stars, forks=forks, total=max(0, weekly_stars)),
+
relevance=_compute_relevance(rank, weekly_stars, weekly_pct, category),
+
)
+
+
+
def collect(
+
github_sources: Dict[str, Dict[str, Any]],
+
from_date: str,
+
to_date: str,
+
depth: str = "default",
+
) -> CollectionResult:
+
"""Scrape NEW AI Engineering repos from Good AI List.
+
+
Args:
+
github_sources: Entity registry used to match scraped repos to tracked entities
+
from_date: Start date YYYY-MM-DD (unused for NEW-only scrape)
+
to_date: End date YYYY-MM-DD
+
depth: quick | default | deep β€” controls how many top repos to keep
+
+
Returns:
+
CollectionResult with source=repo. Never raises.
+
"""
+
result = CollectionResult(source=SOURCE_REPO)
+
result.entities_checked = 1
+
+
if not _HAS_PLAYWRIGHT:
+
result.errors.append("playwright not installed β€” run: pip install playwright")
+
+ _pipeline_log(
+
+ "Good AI List returned 0 items - check Playwright and Chromium installation"
+
+ )
+
return result
+
+
try:
+
rows = scrape_rows(depth)
+
except Exception as e:
+
result.errors.append(f"Good AI List scrape failed: {e}")
+
_log(f"Scrape failed: {e}")
+
+ _pipeline_log(
+
+ "Good AI List returned 0 items - check Playwright and Chromium installation"
+
+ )
+
return result
+
+
if not rows:
+
result.errors.append("Good AI List scrape returned no AI Engineering NEW repos")
+
+ _pipeline_log(
+
+ "Good AI List returned 0 items - check Playwright and Chromium installation"
+
+ )
+
return result
+
+
org_to_entity, repo_to_entity = _build_entity_lookup(github_sources)
+
all_items: List[TrackerItem] = []
+
seen_urls: set = set()
+
matched_entities: set = set()
+
+
for row in rows:
+
repo_name = row.get("repo_name", "")
+
url = row.get("url", "")
+
if url in seen_urls:
+
continue
+
+
matched = _match_entity(repo_name, org_to_entity, repo_to_entity)
+
entity = matched or "Good AI List Trending"
+
+
item = _row_to_item(row, entity, to_date)
+
if not item:
+
continue
+
+
seen_urls.add(url)
+
all_items.append(item)
+
if matched:
+
matched_entities.add(matched)
+
+
result.items = all_items
+
result.entities_with_updates = 1 if all_items else 0
+
_log(
+
f"Collected {len(all_items)} AI Engineering NEW repos from Good AI List "
+
f"({len(matched_entities)} matched tracked entities)"
+
)
+
return result
+
diff --git a/ai_agents/devable_research_agent/lib/twitter_collector.py b/ai_agents/devable_research_agent/lib/twitter_collector.py
new file mode 100644
index 0000000..5a5d613
--- /dev/null
+++ b/ai_agents/devable_research_agent/lib/twitter_collector.py
@@ -0,0 +1,472 @@
+"""Twitter/X collector for devable-research-agent.
+
+Uses the ``twitter-cli`` binary (subprocess) with cookie auth from
+``TWITTER_AUTH_TOKEN`` and ``TWITTER_CT0``. Replaces the old Anthropic-based
+``x_agent.py`` approach.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import subprocess
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Set, Tuple
+
+from . import entities
+from .env import load_env_file
+from .schema import CollectionResult, Engagement, SOURCE_X, TrackerItem
+from .util import log, parse_date
+
+SOURCE_LABEL = "Twitter/X"
+MIN_VIEWS = 50
+TITLE_LIMIT = 120
+SEARCH_LIMIT = 20
+USER_POSTS_LIMIT = 10
+CLI_TIMEOUT = 120
+
+SEARCH_QUERIES = [
+ "open source LLM release",
+ "new AI agent framework released",
+ "open source model weights",
+ "new inference engine open source",
+]
+
+TEAM_ACCOUNTS = [
+ "askalphaxiv",
+ "huggingpapers",
+ "dair_ai",
+ "ArtificialAnlys",
+]
+
+_log = lambda msg: log("Twitter", msg, tty_only=True)
+
+_RT_PREFIX_RE = re.compile(r"^\s*RT\s+@", re.IGNORECASE)
+
+
+def _tweet_id(raw_id: Any) -> str:
+ return f"X-{raw_id}"
+
+
+def _load_twitter_credentials(
+ auth_token: Optional[str] = None,
+ ct0: Optional[str] = None,
+) -> Tuple[Optional[str], Optional[str]]:
+ """Load Twitter cookie credentials from args, env, or morning-ai config."""
+ token = auth_token or os.environ.get("TWITTER_AUTH_TOKEN")
+ cookie_ct0 = ct0 or os.environ.get("TWITTER_CT0")
+
+ if token and cookie_ct0:
+ return token, cookie_ct0
+
+ merged: Dict[str, str] = {}
+ merged.update(load_env_file(str(Path.home() / ".config" / "morning-ai" / ".env")))
+ merged.update(load_env_file(".env"))
+ merged.update(load_env_file(".env.local"))
+
+ token = token or merged.get("TWITTER_AUTH_TOKEN")
+ cookie_ct0 = cookie_ct0 or merged.get("TWITTER_CT0")
+ return (token or None), (cookie_ct0 or None)
+
+
+def _twitter_cli_env(auth_token: str, ct0: str) -> Dict[str, str]:
+ env = os.environ.copy()
+ env["TWITTER_AUTH_TOKEN"] = auth_token
+ env["TWITTER_CT0"] = ct0
+ return env
+
+
+def _run_twitter_cli(args: List[str], env: Dict[str, str]) -> Tuple[Optional[Any], Optional[str]]:
+ """Run twitter-cli and parse JSON stdout."""
+ binary = shutil.which("twitter")
+ if not binary:
+ return None, "twitter-cli not found on PATH (install twitter-cli / Agent-Reach)"
+
+ cmd = [binary, *args, "--json"]
+ try:
+ proc = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=CLI_TIMEOUT,
+ env=env,
+ check=False,
+ )
+ except subprocess.TimeoutExpired:
+ return None, f"timeout after {CLI_TIMEOUT}s: {' '.join(args[:3])}"
+ except OSError as exc:
+ return None, f"failed to run twitter-cli: {exc}"
+
+ stdout = (proc.stdout or "").strip()
+ stderr = (proc.stderr or "").strip()
+ if not stdout:
+ detail = stderr or f"exit code {proc.returncode}"
+ return None, f"empty twitter-cli output ({detail})"
+
+ try:
+ payload = json.loads(stdout)
+ except json.JSONDecodeError as exc:
+ snippet = stdout[:200].replace("\n", " ")
+ return None, f"invalid JSON from twitter-cli: {exc}; snippet={snippet!r}"
+
+ if isinstance(payload, dict) and payload.get("ok") is False:
+ err = payload.get("error") or {}
+ code = err.get("code") or "unknown"
+ message = err.get("message") or str(err)
+ return None, f"{code}: {message}"
+
+ return payload, None
+
+
+def _extract_tweets(payload: Any) -> List[Dict[str, Any]]:
+ """Normalize twitter-cli JSON into a list of tweet dicts."""
+ if isinstance(payload, list):
+ return [row for row in payload if isinstance(row, dict)]
+ if not isinstance(payload, dict):
+ return []
+
+ for key in ("tweets", "data", "results", "items"):
+ value = payload.get(key)
+ if isinstance(value, list):
+ return [row for row in value if isinstance(row, dict)]
+ return []
+
+
+def _tweet_text(tweet: Dict[str, Any]) -> str:
+ return str(tweet.get("text") or tweet.get("fullText") or "").strip()
+
+
+def _tweet_author(tweet: Dict[str, Any]) -> str:
+ author = tweet.get("author") or {}
+ if isinstance(author, dict):
+ for key in ("screenName", "screen_name", "username", "userName"):
+ handle = author.get(key)
+ if handle:
+ return str(handle).lstrip("@")
+ for key in ("screenName", "screen_name", "username"):
+ handle = tweet.get(key)
+ if handle:
+ return str(handle).lstrip("@")
+ return ""
+
+
+def _tweet_metrics(tweet: Dict[str, Any]) -> Dict[str, int]:
+ metrics = tweet.get("metrics") or {}
+ if not isinstance(metrics, dict):
+ metrics = {}
+ views = metrics.get("views") or tweet.get("views") or 0
+ likes = metrics.get("likes") or tweet.get("likes") or 0
+ retweets = metrics.get("retweets") or tweet.get("retweets") or 0
+ replies = metrics.get("replies") or tweet.get("replies") or 0
+ return {
+ "views": int(views or 0),
+ "likes": int(likes or 0),
+ "retweets": int(retweets or 0),
+ "replies": int(replies or 0),
+ }
+
+
+def _tweet_created_iso(tweet: Dict[str, Any]) -> str:
+ for key in ("createdAtISO", "created_at", "createdAt", "date"):
+ value = tweet.get(key)
+ if value:
+ return str(value)
+ return ""
+
+
+def _tweet_date(iso_value: str, from_date: str, to_date: str) -> Optional[str]:
+ if not iso_value:
+ return None
+ try:
+ normalized = iso_value.replace("Z", "+00:00")
+ dt = datetime.fromisoformat(normalized)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ date_str = dt.strftime("%Y-%m-%d")
+ except ValueError:
+ date_str = parse_date(iso_value)
+ if not date_str:
+ return None
+ if from_date and date_str < from_date:
+ return None
+ if to_date and date_str > to_date:
+ return None
+ return date_str
+
+
+def _is_retweet(tweet: Dict[str, Any], text: str) -> bool:
+ if tweet.get("isRetweet") or tweet.get("retweeted"):
+ return True
+ return bool(_RT_PREFIX_RE.match(text))
+
+
+def _is_english(text: str) -> bool:
+ if not text.strip():
+ return False
+ letters = [c for c in text if c.isalpha()]
+ if not letters:
+ return True
+ non_latin = sum(1 for c in letters if ord(c) > 127)
+ return (non_latin / len(letters)) < 0.2
+
+
+def _compute_relevance(views: int, likes: int) -> float:
+ view_score = min(1.0, views / 10_000)
+ like_score = min(1.0, likes / 500)
+ relevance = min(1.0, view_score * 0.45 + like_score * 0.45 + 0.1)
+ return round(relevance, 2)
+
+
+def _tweet_url(tweet: Dict[str, Any], screen_name: str) -> str:
+ tweet_id = tweet.get("id") or tweet.get("id_str")
+ if tweet_id and screen_name:
+ return f"https://x.com/{screen_name}/status/{tweet_id}"
+ urls = tweet.get("urls") or []
+ if isinstance(urls, list):
+ for entry in urls:
+ if isinstance(entry, str) and entry.startswith("http"):
+ return entry
+ if isinstance(entry, dict):
+ expanded = entry.get("expanded_url") or entry.get("url")
+ if expanded:
+ return str(expanded)
+ return ""
+
+
+def _kol_handles(x_handles_kol: Optional[Dict[str, List[str]]] = None) -> List[str]:
+ registry = x_handles_kol if x_handles_kol is not None else entities.X_HANDLES_KOL
+ handles: List[str] = []
+ seen: Set[str] = set()
+ for handle_list in registry.values():
+ for handle in handle_list:
+ normalized = str(handle).lstrip("@").lower()
+ if normalized and normalized not in seen:
+ seen.add(normalized)
+ handles.append(normalized)
+ for handle in TEAM_ACCOUNTS:
+ normalized = handle.lstrip("@").lower()
+ if normalized not in seen:
+ seen.add(normalized)
+ handles.append(normalized)
+ return handles
+
+
+def _entity_for_handle(handle: str, x_handles_kol: Dict[str, List[str]]) -> str:
+ needle = handle.lower()
+ for entity_name, handles in x_handles_kol.items():
+ for raw in handles:
+ if str(raw).lstrip("@").lower() == needle:
+ return entity_name
+ if needle in {h.lower() for h in TEAM_ACCOUNTS}:
+ return handle
+ return handle
+
+
+def _tweet_to_item(
+ tweet: Dict[str, Any],
+ *,
+ entity: str,
+ from_date: str,
+ to_date: str,
+) -> Optional[TrackerItem]:
+ text = _tweet_text(tweet)
+ if not text:
+ return None
+ if _is_retweet(tweet, text):
+ return None
+ if not _is_english(text):
+ return None
+
+ metrics = _tweet_metrics(tweet)
+ if metrics["views"] < MIN_VIEWS:
+ return None
+
+ created_iso = _tweet_created_iso(tweet)
+ date_str = _tweet_date(created_iso, from_date, to_date)
+ if not date_str:
+ return None
+
+ screen_name = _tweet_author(tweet)
+ source_url = _tweet_url(tweet, screen_name)
+ if not source_url:
+ return None
+
+ title = text if len(text) <= TITLE_LIMIT else text[: TITLE_LIMIT - 3].rstrip() + "..."
+ engagement = Engagement(
+ likes=metrics["likes"],
+ reposts=metrics["retweets"],
+ replies=metrics["replies"],
+ views=metrics["views"],
+ total=metrics["likes"] + metrics["retweets"] + metrics["replies"],
+ )
+
+ return TrackerItem(
+ id=_tweet_id(tweet.get("id") or tweet.get("id_str") or source_url),
+ title=title,
+ summary=text,
+ entity=entity,
+ content_type="",
+ source=SOURCE_X,
+ source_url=source_url,
+ source_label=SOURCE_LABEL,
+ date=date_str,
+ date_confidence="high" if created_iso else "med",
+ raw_text=text,
+ engagement=engagement,
+ relevance=_compute_relevance(metrics["views"], metrics["likes"]),
+ )
+
+
+def _search_tweets(
+ query: str,
+ from_date: str,
+ to_date: str,
+ env: Dict[str, str],
+) -> Tuple[List[TrackerItem], Optional[str]]:
+ args = [
+ "search",
+ query,
+ "-t",
+ "latest",
+ "-n",
+ str(SEARCH_LIMIT),
+ "--lang",
+ "en",
+ "--exclude",
+ "retweets",
+ ]
+ if from_date:
+ args.extend(["--since", from_date])
+ if to_date:
+ args.extend(["--until", to_date])
+
+ payload, error = _run_twitter_cli(args, env)
+ if error:
+ return [], f"search {query!r}: {error}"
+
+ items: List[TrackerItem] = []
+ for tweet in _extract_tweets(payload):
+ item = _tweet_to_item(
+ tweet,
+ entity="Twitter Search",
+ from_date=from_date,
+ to_date=to_date,
+ )
+ if item:
+ items.append(item)
+ _log(f"Search {query!r}: {len(items)} items")
+ return items, None
+
+
+def _user_posts(
+ handle: str,
+ entity: str,
+ from_date: str,
+ to_date: str,
+ env: Dict[str, str],
+) -> Tuple[List[TrackerItem], Optional[str]]:
+ args = ["user-posts", handle.lstrip("@"), "-n", str(USER_POSTS_LIMIT)]
+ payload, error = _run_twitter_cli(args, env)
+ if error:
+ return [], f"user-posts @{handle}: {error}"
+
+ items: List[TrackerItem] = []
+ for tweet in _extract_tweets(payload):
+ item = _tweet_to_item(
+ tweet,
+ entity=entity,
+ from_date=from_date,
+ to_date=to_date,
+ )
+ if item:
+ items.append(item)
+ _log(f"@{handle}: {len(items)} items")
+ return items, None
+
+
+def collect(
+ _github_sources: Any,
+ from_date: str,
+ to_date: str,
+ depth: str = "default",
+ *,
+ auth_token: Optional[str] = None,
+ ct0: Optional[str] = None,
+ x_handles_kol: Optional[Dict[str, List[str]]] = None,
+) -> CollectionResult:
+ """Collect tweets via twitter-cli search + KOL/team timelines.
+
+ Args:
+ _github_sources: Unused (kept for collect.py / test API parity).
+ from_date: Window start YYYY-MM-DD.
+ to_date: Window end YYYY-MM-DD.
+ depth: quick | default | deep (reserved; limits fixed for now).
+ auth_token: Optional TWITTER_AUTH_TOKEN override.
+ ct0: Optional TWITTER_CT0 override.
+ x_handles_kol: Optional KOL handle registry override.
+ """
+ del _github_sources, depth # depth reserved for future tuning
+
+ result = CollectionResult(source=SOURCE_X)
+ token, cookie_ct0 = _load_twitter_credentials(auth_token, ct0)
+ if not token or not cookie_ct0:
+ result.errors.append(
+ "TWITTER_AUTH_TOKEN and TWITTER_CT0 not configured "
+ "(set in ~/.config/morning-ai/.env or environment)"
+ )
+ return result
+
+ env = _twitter_cli_env(token, cookie_ct0)
+ kol_registry = x_handles_kol if x_handles_kol is not None else entities.X_HANDLES_KOL
+ handles = _kol_handles(kol_registry)
+ result.entities_checked = len(SEARCH_QUERIES) + len(handles)
+
+ all_items: List[TrackerItem] = []
+ seen_urls: Set[str] = set()
+ entities_with_updates: Set[str] = set()
+ tasks: List[Tuple[str, str, Optional[str]]] = []
+ for query in SEARCH_QUERIES:
+ tasks.append(("search", query, None))
+ for handle in handles:
+ tasks.append(("user", handle, _entity_for_handle(handle, kol_registry)))
+
+ max_workers = min(8, max(1, len(tasks)))
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
+ futures = {}
+ for kind, key, entity in tasks:
+ if kind == "search":
+ futures[pool.submit(_search_tweets, key, from_date, to_date, env)] = (
+ "search",
+ key,
+ )
+ else:
+ futures[pool.submit(_user_posts, key, entity or key, from_date, to_date, env)] = (
+ "user",
+ key,
+ )
+
+ for future in as_completed(futures):
+ kind, key = futures[future]
+ try:
+ items, error = future.result()
+ except Exception as exc:
+ result.errors.append(f"{kind} {key}: {exc}")
+ continue
+ if error:
+ result.errors.append(error)
+ continue
+ for item in items:
+ if item.source_url in seen_urls:
+ continue
+ seen_urls.add(item.source_url)
+ all_items.append(item)
+ entities_with_updates.add(item.entity)
+
+ result.items = all_items
+ result.entities_with_updates = len(entities_with_updates)
+ _log(f"Collected {len(all_items)} Twitter items ({len(result.errors)} errors)")
+ return result
diff --git a/ai_agents/devable_research_agent/lib/x_agent.py b/ai_agents/devable_research_agent/lib/x_agent.py
new file mode 100644
index 0000000..633c9ef
--- /dev/null
+++ b/ai_agents/devable_research_agent/lib/x_agent.py
@@ -0,0 +1,5 @@
+"""Deprecated Anthropic-based X collector.
+
+Replaced by ``lib.twitter_collector`` (twitter-cli subprocess).
+This file is kept for reference; the pipeline does not import it.
+"""
diff --git a/ai_agents/devable_research_agent/scripts/filter_top_items.py b/ai_agents/devable_research_agent/scripts/filter_top_items.py
index f3c73d2..8def3a1 100644
--- a/ai_agents/devable_research_agent/scripts/filter_top_items.py
+++ b/ai_agents/devable_research_agent/scripts/filter_top_items.py
@@ -7,14 +7,17 @@ Applies category diversity quotas so the digest is not dominated by a single sou
"""
import argparse
+import copy
+import hashlib
import json
import os
import re
import sys
+from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional, Tuple
+from typing import Any, Callable, Dict, List, Optional, Set, Tuple
try:
from mistralai.client import Mistral
@@ -24,13 +27,24 @@ except ImportError:
_HAS_MISTRAL = False
MORNING_AI_ENV_FILE = Path.home() / ".config" / "morning-ai" / ".env"
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
+PROJECT_ROOT = Path(
+ os.environ.get("DEVABLE_PROJECT_ROOT", "")
+).resolve() if os.environ.get("DEVABLE_PROJECT_ROOT") else Path(__file__).resolve().parent.parent
DELIVERED_ITEMS_PATH = PROJECT_ROOT / "logs" / "delivered_items.json"
+PIPELINE_LOG_PATH = PROJECT_ROOT / "logs" / "pipeline.log"
+PAPER_SCORES_PATH = PROJECT_ROOT / "logs" / "paper_scores_today.json"
+PAPER_SCORE_CACHE_PATH = PROJECT_ROOT / "logs" / "paper_score_cache.json"
+REJECTED_ITEMS_PATH = PROJECT_ROOT / "logs" / "rejected_items_today.json"
+FILTER_DEBUG_TRACE_PATH = PROJECT_ROOT / "logs" / "filter_debug_trace.txt"
+PRIORITY_REPOS_PATH = PROJECT_ROOT / "entities" / "custom" / "priority-repos.md"
DEFAULT_DELIVERED_LOOKBACK_DAYS = 7
GITHUB_REPO_DELIVERED_LOOKBACK_DAYS = 14
+GITHUB_TRENDING_DELIVERED_LOOKBACK_DAYS = 3
+AINEWS_DELIVERED_LOOKBACK_DAYS = 3
+HN_SHOW_LAUNCH_DELIVERED_LOOKBACK_DAYS = 3
REPO_FREQUENCY_CAP = 2
REPO_FREQUENCY_LOOKBACK_DAYS = 30
-VERIFY_MEMORY_LOOKBACK_DAYS = 14
+VERIFY_MEMORY_LOOKBACK_DAYS = 7
TZ_CN = timezone(timedelta(hours=8))
# Per-source date cutoffs for stale-item filtering
@@ -48,7 +62,9 @@ DEFAULT_DATE_CUTOFF_HOURS = 48
PAPER_LLM_MODEL = "mistral-small-latest"
VERIFY_LLM_MODEL = "mistral-small-latest"
-MIN_PAPER_LLM_SCORE = 5
+DESCRIPTION_LLM_MODEL = "mistral-small-latest"
+MIN_PAPER_LLM_SCORE = 4
+MIN_PAPER_HYBRID_IMPORTANCE = 4.5
FAILED_PAPER_LLM_SCORE = 3
PAPER_LLM_MAX_WORKERS = 8
@@ -81,25 +97,45 @@ Here are the items selected for today's digest:
Here are items delivered in the last 14 days (memory spine):
{memory_spine_json}
-Your job: remove any item from today's list that is:
-1. The same repo, tool, or paper that already appeared in the last 14 days (even if the URL is slightly different)
-2. The same story covered by a different source
-3. A minor update to something already delivered recently
+Your job: remove any item from today's list ONLY when:
+1. It has the exact same source_url as an item in the memory spine, OR
+2. It has the same entity AND same content_type as an item in the memory spine
-Return only the filtered list as a JSON array with the same structure. Be strict. Remove duplicates ruthlessly."""
+Do NOT remove AINews items (source_label: AINews) unless the source_url is an exact duplicate.
+Do NOT remove items for similar topics, paraphrased titles, or related stories.
+
+Return only the filtered list as a JSON array with the same structure."""
+
+_DESCRIPTION_LLM_SYSTEM = (
+ "You write one-line technical descriptions for an AI engineering digest. "
+ "Reply with ONLY the description text β€” no quotes, no preamble."
+)
+
+_DESCRIPTION_LLM_USER_TEMPLATE = """Write ONE technical sentence (max 12 words) describing what changed and why it matters to AI engineers who build with LLMs and agents.
+
+Title: {title}
+Summary: {summary}
+Source: {source}
+
+Reply with only the description."""
+
+_PRIORITY_REPOS_CACHE: Set[str] = set()
# Per-category min/max quotas for digest diversity
QUOTA_LIMITS = {
- "paper": {"min": 1, "max": 4},
- "github": {"min": 2, "max": 5},
- "web": {"min": 1, "max": 2},
- "x": {"min": 1, "max": 2},
- "hackernews": {"min": 0, "max": 2},
+ "paper": {"min": 2, "max": 4},
+ "github": {"min": 2, "max": 8},
+ "web": {"min": 1, "max": 3},
+ "ainews": {"min": 2, "max": 4},
+ "x": {"min": 1, "max": 4},
+ "hackernews": {"min": 1, "max": 4},
"huggingface": {"min": 0, "max": 2},
- "good_ai_list": {"min": 8, "max": 12},
+ "good_ai_list": {"min": 3, "max": 6},
}
-GOOD_AI_LIST_IMPORTANCE_BOOST = 2.0
+GOOD_AI_LIST_IMPORTANCE_BOOST = 0.5
+# Previously-delivered Good AI List repos may not fill quota slots (fresh repos only).
+GOOD_AI_LIST_MAX_REDELIVERED = 0
_paper_llm_scores: Dict[str, int] = {}
_MISTRAL_CLIENT: "Mistral | None" = None
@@ -183,6 +219,9 @@ _SDK_SYNC_KEYWORDS = [
"command_lifecycle",
"duration_api_ms",
"stream-json",
+ "timedoutafterms",
+ "bashtooloutput",
+ "auto-backgrounded",
]
# Skip fix-heavy patch releases only when Added/Improved bullets lack major capability.
@@ -247,6 +286,7 @@ _GITHUB_TRENDING_AI_KEYWORDS = [
"prompt",
"skill",
"mcp",
+ "codex",
"open source ai",
"machine learning",
"deep learning",
@@ -267,8 +307,25 @@ _REPO_BLOCKLIST = {
"synthetic-sciences/openscience",
"heygen-com/hyperframes",
"isjiamu/gzh-design-skill",
+ "mdx-tom/gpt-5.6-instruct",
+ "zhishile/codex-auth-helper",
+ "jia-ethan/codex-keysmith",
}
+# Jailbreak packs, auth/session exporters β€” not AI engineering tooling.
+_REPO_NON_ENGINEERING_KEYWORDS = [
+ "jailbreak",
+ "η ΄η”²",
+ "auth.json",
+ "session export",
+ "export your logged-in",
+ "codex登陆",
+ "auth helper",
+ "codex-keysmith",
+ "codex keysmith",
+ "破甲提瀺词",
+]
+
# Skip repos whose primary purpose is cloning, generic scraping, or standalone browser automation.
_REPO_WEBSITE_CLONER_KEYWORDS = [
"website cloner",
@@ -460,6 +517,20 @@ _HN_INCLUDE_KEYWORDS = [
"skill",
"evaluation",
"evals",
+ "api",
+ "sdk",
+ "coding",
+ "model",
+]
+
+_HN_ENGINEERING_TITLE_TERMS = [
+ "agent",
+ "api",
+ "sdk",
+ "coding",
+ "release",
+ "benchmark",
+ "model",
]
_HN_CLOSED_COMMERCIAL = [
@@ -484,24 +555,120 @@ _GITHUB_REPO_RE = re.compile(
r"github\.com/([^/?#]+)/([^/?#]+)",
re.IGNORECASE,
)
+_GITHUB_SLUG_RE = re.compile(r"^([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)$")
+
+_X_QUALITY_KEYWORDS = [
+ "model",
+ "agent",
+ "llm",
+ "open source",
+ "release",
+ "benchmark",
+ "inference",
+ "tool",
+ "framework",
+ "paper",
+ "arxiv",
+ "weights",
+ "fine-tune",
+ "fine tune",
+ "dataset",
+ "api",
+ "sdk",
+ "github",
+ "repo",
+ "training",
+ "reasoning",
+ "embedding",
+ "rag",
+ "mcp",
+ "coding",
+ "engineering",
+]
+_X_MIN_VIEWS = 200
+_X_MIN_LIKES = 5
+
+
+def _github_release_tag(item: Dict) -> str:
+ """Extract semver/tag from a GitHub release URL or title."""
+ url = item.get("source_url", "") or ""
+ match = re.search(r"/releases/tag/([^/?#]+)", url, re.IGNORECASE)
+ if match:
+ return match.group(1).lower().lstrip("v")
+ title = (item.get("title") or "").strip()
+ match = re.search(r"@([\d.]+(?:[-\w.+]+)?)\s*$", title)
+ if match:
+ return match.group(1).lower()
+ match = re.search(r"\s(v?\d+\.\d+(?:\.\d+)?(?:[-\w.+]+)?)\s*$", title, re.IGNORECASE)
+ if match:
+ return match.group(1).lower().lstrip("v")
+ return ""
+
+
+def _is_github_release(item: Dict) -> bool:
+ return item.get("source") == "github" and not _is_github_trending(item)
+
+
+def _is_hn_show_or_launch(item: Dict) -> bool:
+ if item.get("source") != "hackernews":
+ return False
+ title = (item.get("title") or "").strip().lower()
+ return title.startswith("show hn:") or title.startswith("launch hn:")
+
+
+def _delivered_dedup_key(item: Dict) -> str:
+ """Canonical dedup key for delivered-log matching."""
+ if _is_good_ai_list(item) or item.get("source") == "arxiv":
+ return _normalize_source_url(item.get("source_url", ""))
+
+ if _is_github_trending(item):
+ repo_key = _github_repo_key(item)
+ if repo_key:
+ return f"github-trending:{repo_key}"
+ return _normalize_source_url(item.get("source_url", ""))
+
+ if _is_github_release(item):
+ repo_key = _github_repo_key(item)
+ tag = _github_release_tag(item)
+ if repo_key and tag:
+ return f"github-release:{repo_key}@{tag}"
+ if repo_key:
+ return f"https://github.com/{repo_key}"
+
+ normalized = _normalize_source_url(item.get("source_url", ""))
+ if normalized:
+ return normalized
+ return (item.get("source_url") or "").split("?")[0].rstrip("/").lower()
def _github_repo_key(item_or_url: Any) -> str:
"""Return canonical owner/repo slug for GitHub dedup, or empty string."""
if isinstance(item_or_url, dict):
+ stored = (item_or_url.get("repo_key") or "").strip().lower()
+ if stored and "/" in stored and " " not in stored:
+ return stored
source = item_or_url.get("source", "")
url = item_or_url.get("source_url", "")
title = item_or_url.get("title", "")
if source not in ("github", "repo") and "github.com/" not in url.lower():
+ slug_match = _GITHUB_SLUG_RE.match((title or "").strip())
+ if slug_match:
+ return f"{slug_match.group(1).lower()}/{slug_match.group(2).lower()}"
return ""
for text in (url, title):
match = _GITHUB_REPO_RE.search(text or "")
if match:
return f"{match.group(1).lower()}/{match.group(2).lower()}"
+ slug_match = _GITHUB_SLUG_RE.match((text or "").strip())
+ if slug_match:
+ return f"{slug_match.group(1).lower()}/{slug_match.group(2).lower()}"
return ""
match = _GITHUB_REPO_RE.search(str(item_or_url or ""))
if match:
return f"{match.group(1).lower()}/{match.group(2).lower()}"
+ slug_match = _GITHUB_SLUG_RE.match(str(item_or_url or "").strip())
+ if slug_match:
+ return f"{slug_match.group(1).lower()}/{slug_match.group(2).lower()}"
return ""
@@ -572,13 +739,49 @@ def filter_stale_items(items: List[Dict]) -> Tuple[List[Dict], int, Dict[str, in
def _delivered_lookback_days(item: Dict) -> int:
- """URL dedup window: 14 days for GitHub and Good AI List, 7 for others."""
+ """URL dedup window: 14d GAL/releases, 3d Trending/AINews/Show HN, 7d default."""
+ if _is_good_ai_list(item):
+ return GITHUB_REPO_DELIVERED_LOOKBACK_DAYS
+ if _is_github_trending(item):
+ return GITHUB_TRENDING_DELIVERED_LOOKBACK_DAYS
+ if _is_ainews(item):
+ return AINEWS_DELIVERED_LOOKBACK_DAYS
+ if _is_hn_show_or_launch(item):
+ return HN_SHOW_LAUNCH_DELIVERED_LOOKBACK_DAYS
source = item.get("source", "")
- if source == "github" or source == "repo":
+ if source in ("github", "repo"):
return GITHUB_REPO_DELIVERED_LOOKBACK_DAYS
return DEFAULT_DELIVERED_LOOKBACK_DAYS
+def _pipeline_log(message: str) -> None:
+ PIPELINE_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
+ timestamp = datetime.now(TZ_CN).strftime("%Y-%m-%d %H:%M:%S")
+ with PIPELINE_LOG_PATH.open("a", encoding="utf-8") as handle:
+ handle.write(f"[{timestamp}] {message}\n")
+
+
+def _load_priority_repos(path: Path = PRIORITY_REPOS_PATH) -> Set[str]:
+ """Load owner/repo slugs exempt from the frequency cap."""
+ global _PRIORITY_REPOS_CACHE
+ if _PRIORITY_REPOS_CACHE:
+ return _PRIORITY_REPOS_CACHE
+ repos: Set[str] = set()
+ if not path.exists():
+ return repos
+ for line in path.read_text(encoding="utf-8").splitlines():
+ match = _GITHUB_REPO_RE.search(line)
+ if match:
+ repos.add(f"{match.group(1).lower()}/{match.group(2).lower()}")
+ _PRIORITY_REPOS_CACHE = repos
+ return repos
+
+
+def _is_priority_repo(item: Dict) -> bool:
+ repo_key = _github_repo_key(item)
+ return bool(repo_key and repo_key in _load_priority_repos())
+
+
def _topic_summary(title: str, summary: str = "") -> str:
"""Derive a short 3-word topic label for the memory spine."""
stop = {
@@ -610,6 +813,11 @@ def _load_delivered_store(path: Path = DELIVERED_ITEMS_PATH) -> Tuple[List[Dict]
frequency = data.get("frequency", {})
if not isinstance(frequency, dict):
frequency = {}
+ frequency = {
+ str(repo_key).lower(): record
+ for repo_key, record in frequency.items()
+ if isinstance(record, dict)
+ }
if not frequency and entries:
frequency = _derive_frequency_from_entries(entries)
return entries, frequency
@@ -640,6 +848,10 @@ def _derive_frequency_from_entries(entries: List[Dict]) -> Dict[str, Dict]:
if entry.get("date", "") < cutoff:
continue
repo_key = _github_repo_key(entry)
+ if not repo_key:
+ stored = (entry.get("repo_key") or "").strip().lower()
+ if stored and "/" in stored:
+ repo_key = stored
if not repo_key:
continue
record = counts.setdefault(
@@ -685,6 +897,8 @@ def _repo_delivery_count(item: Dict) -> int:
def _is_frequency_capped(item: Dict) -> bool:
"""Block repos delivered REPO_FREQUENCY_CAP+ times in the last 30 days."""
+ if _is_priority_repo(item):
+ return False
repo_key = _frequency_key_for_item(item)
if not repo_key:
return False
@@ -698,6 +912,9 @@ def filter_frequency_capped(items: List[Dict]) -> Tuple[List[Dict], int, List[st
capped_titles: List[str] = []
counts = _load_repo_delivery_counts()
for item in items:
+ if _is_priority_repo(item):
+ kept.append(item)
+ continue
repo_key = _frequency_key_for_item(item)
if repo_key and counts.get(repo_key, 0) >= REPO_FREQUENCY_CAP:
skipped += 1
@@ -744,6 +961,7 @@ def _load_memory_spine(lookback_days: int = VERIFY_MEMORY_LOOKBACK_DAYS) -> List
"date": entry.get("date", ""),
"title": entry.get("title", ""),
"entity": entry.get("entity", ""),
+ "content_type": entry.get("content_type", ""),
"topic": entry.get("topic", ""),
})
return spine
@@ -791,21 +1009,23 @@ def _recent_delivery_entry(item: Dict) -> Optional[Dict]:
return None
now = datetime.now(TZ_CN)
- entry_by_url: Dict[str, Dict] = {}
+ entry_by_key: Dict[str, Dict] = {}
entry_by_repo_key: Dict[str, Dict] = {}
for entry in entries:
- normalized = _normalize_source_url(entry.get("source_url", ""))
- if normalized:
- entry_by_url[normalized] = entry
+ key = _delivered_dedup_key(entry)
+ if key:
+ entry_by_key[key] = entry
repo_key = _github_repo_key(entry)
if repo_key:
entry_by_repo_key[repo_key] = entry
- normalized = _normalize_source_url(item.get("source_url", ""))
- repo_key = _github_repo_key(item)
- entry = entry_by_url.get(normalized) if normalized else None
- if entry is None and repo_key:
- entry = entry_by_repo_key.get(repo_key)
+ dedup_key = _delivered_dedup_key(item)
+ entry = entry_by_key.get(dedup_key) if dedup_key else None
+ if entry is None and _is_github_trending(item):
+ repo_key = _github_repo_key(item)
+ if repo_key:
+ entry = entry_by_repo_key.get(repo_key)
+
if not entry:
return None
@@ -822,22 +1042,23 @@ def _was_recently_delivered(item: Dict) -> bool:
def filter_already_delivered(items: List[Dict], delivered_urls: set) -> Tuple[List[Dict], int]:
- """Skip items whose source_url or GitHub repo was already posted within the lookback window.
+ """Skip items whose dedup key was already posted within the lookback window.
- Good AI List repos are kept in the candidate pool; freshness is applied at selection time.
- arXiv papers are kept for the same reason so the paper minimum quota can be met.
+ Good AI List repos use the same 14-day block as GitHub releases (no redelivery).
+ arXiv papers are kept so the paper minimum quota can be met when fresh papers are scarce.
+ GitHub releases dedup by repo+semver; GitHub Trending dedups by bare repo slug.
"""
entries = _load_delivered_entries()
if not entries and not delivered_urls:
return items, 0
now = datetime.now(TZ_CN)
- entry_by_url: Dict[str, Dict] = {}
+ entry_by_key: Dict[str, Dict] = {}
entry_by_repo_key: Dict[str, Dict] = {}
for entry in entries:
- normalized = _normalize_source_url(entry.get("source_url", ""))
- if normalized:
- entry_by_url[normalized] = entry
+ key = _delivered_dedup_key(entry)
+ if key:
+ entry_by_key[key] = entry
repo_key = _github_repo_key(entry)
if repo_key:
entry_by_repo_key[repo_key] = entry
@@ -845,20 +1066,16 @@ def filter_already_delivered(items: List[Dict], delivered_urls: set) -> Tuple[Li
kept: List[Dict] = []
skipped = 0
for item in items:
- if _is_good_ai_list(item):
- kept.append(item)
- continue
if item.get("source") == "arxiv":
kept.append(item)
continue
- normalized = _normalize_source_url(item.get("source_url", ""))
- repo_key = _github_repo_key(item)
- entry = None
- if normalized:
- entry = entry_by_url.get(normalized)
- if entry is None and repo_key:
- entry = entry_by_repo_key.get(repo_key)
+ dedup_key = _delivered_dedup_key(item)
+ entry = entry_by_key.get(dedup_key) if dedup_key else None
+ if entry is None and _is_github_trending(item):
+ repo_key = _github_repo_key(item)
+ if repo_key:
+ entry = entry_by_repo_key.get(repo_key)
if entry:
lookback = _delivered_lookback_days(item)
@@ -866,9 +1083,17 @@ def filter_already_delivered(items: List[Dict], delivered_urls: set) -> Tuple[Li
if entry.get("date", "") >= cutoff:
skipped += 1
continue
- elif normalized and normalized in delivered_urls:
+ elif _is_github_release(item):
+ pass
+ elif dedup_key and dedup_key in delivered_urls:
skipped += 1
continue
+ elif _is_github_trending(item):
+ repo_key = _github_repo_key(item)
+ bare_repo = f"https://github.com/{repo_key}" if repo_key else ""
+ if bare_repo and bare_repo in delivered_urls:
+ skipped += 1
+ continue
kept.append(item)
return kept, skipped
@@ -893,8 +1118,12 @@ def _append_delivered_items(
repo_key = _frequency_key_for_item(item)
prev_count = 0
- if repo_key and repo_key in frequency:
- prev_count = int(frequency[repo_key].get("delivery_count", 0))
+ if repo_key:
+ derived = _derive_frequency_from_entries(entries)
+ prev_count = max(
+ int(frequency.get(repo_key, {}).get("delivery_count", 0)),
+ int(derived.get(repo_key, {}).get("delivery_count", 0)),
+ )
new_count = prev_count + 1 if repo_key else 1
entries.append({
@@ -902,6 +1131,7 @@ def _append_delivered_items(
"date": delivery_date,
"title": title,
"entity": (item.get("entity") or "").strip(),
+ "content_type": (item.get("content_type") or "").strip(),
"topic": _topic_summary(title, item.get("summary") or ""),
"delivery_count": new_count,
"repo_key": repo_key or "",
@@ -989,6 +1219,65 @@ def _paper_cache_key(item: Dict) -> str:
return f"{title}|{summary}"
+_ARXIV_ID_RE = re.compile(r"arxiv\.org/abs/([0-9]+\.[0-9]+)(?:v\d+)?", re.IGNORECASE)
+
+
+def _arxiv_id(item: Dict) -> str:
+ """Return canonical arXiv ID (without version suffix) for cache lookup."""
+ url = item.get("source_url", "") or ""
+ match = _ARXIV_ID_RE.search(url)
+ if match:
+ return match.group(1)
+ item_id = item.get("id", "") or ""
+ if item_id.startswith("ARXIV-"):
+ return item_id.replace("ARXIV-", "").split("v")[0]
+ return ""
+
+
+def _paper_prompt_version_hash() -> str:
+ payload = _PAPER_LLM_SYSTEM + _PAPER_LLM_USER_TEMPLATE + PAPER_LLM_MODEL
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+def _load_paper_score_cache(prompt_hash: str) -> Dict[str, int]:
+ if not PAPER_SCORE_CACHE_PATH.exists():
+ return {}
+ try:
+ data = json.loads(PAPER_SCORE_CACHE_PATH.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return {}
+ if data.get("prompt_hash") != prompt_hash:
+ return {}
+ entries = data.get("entries", {})
+ scores: Dict[str, int] = {}
+ for arxiv_id, record in entries.items():
+ if isinstance(record, dict):
+ scores[arxiv_id] = int(record.get("score", FAILED_PAPER_LLM_SCORE))
+ else:
+ scores[arxiv_id] = int(record)
+ return scores
+
+
+def _save_paper_score_cache(prompt_hash: str, scores: Dict[str, int]) -> None:
+ PAPER_SCORE_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ existing: Dict[str, Dict] = {}
+ if PAPER_SCORE_CACHE_PATH.exists():
+ try:
+ data = json.loads(PAPER_SCORE_CACHE_PATH.read_text(encoding="utf-8"))
+ if data.get("prompt_hash") == prompt_hash:
+ existing = data.get("entries", {})
+ except (json.JSONDecodeError, OSError):
+ existing = {}
+ scored_at = datetime.now(TZ_CN).isoformat()
+ for arxiv_id, score in scores.items():
+ existing[arxiv_id] = {"score": score, "scored_at": scored_at}
+ payload = {"prompt_hash": prompt_hash, "entries": existing}
+ PAPER_SCORE_CACHE_PATH.write_text(
+ json.dumps(payload, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+
def _parse_llm_paper_score(response_text: str) -> int:
match = re.search(r"[1-5]", (response_text or "").strip())
if not match:
@@ -1026,18 +1315,39 @@ def _score_single_paper(item: Dict, api_key: str) -> int:
def score_papers_with_llm(items: List[Dict]) -> None:
- """Score arXiv papers concurrently via Mistral and cache results."""
+ """Score arXiv papers via Mistral; reuse disk cache keyed by arXiv ID + prompt hash."""
global _paper_llm_scores
api_key = _load_mistral_api_key()
papers = [item for item in items if item.get("source") == "arxiv"]
+ prompt_hash = _paper_prompt_version_hash()
+ disk_cache = _load_paper_score_cache(prompt_hash)
+ cache_hits = 0
+
unique_papers: Dict[str, Dict] = {}
for paper in papers:
- key = _paper_cache_key(paper)
- if key not in _paper_llm_scores:
- unique_papers.setdefault(key, paper)
+ cache_key = _paper_cache_key(paper)
+ if cache_key in _paper_llm_scores:
+ continue
+ arxiv_id = _arxiv_id(paper)
+ if arxiv_id and arxiv_id in disk_cache:
+ _paper_llm_scores[cache_key] = disk_cache[arxiv_id]
+ cache_hits += 1
+ continue
+ unique_papers.setdefault(cache_key, paper)
+
+ if cache_hits:
+ print(f"Paper score cache hits: {cache_hits}/{len(papers)} (prompt {prompt_hash})")
if not unique_papers:
+ if papers:
+ qualifying = sum(1 for item in papers if _is_qualifying_paper(item))
+ print(
+ f"Paper LLM scoring complete: {qualifying}/{len(papers)} qualifying "
+ f"(hybrid threshold {MIN_PAPER_LLM_SCORE}+ or score 3 w/ "
+ f"importance>={MIN_PAPER_HYBRID_IMPORTANCE})"
+ )
+ _save_paper_scores_debug(papers)
return
if not _HAS_MISTRAL:
@@ -1052,21 +1362,63 @@ def score_papers_with_llm(items: List[Dict]) -> None:
_paper_llm_scores[key] = FAILED_PAPER_LLM_SCORE
return
- print(f"Scoring {len(unique_papers)} papers with {PAPER_LLM_MODEL}...")
+ print(f"Scoring {len(unique_papers)} uncached papers with {PAPER_LLM_MODEL}...")
+ new_scores: Dict[str, int] = {}
with ThreadPoolExecutor(max_workers=PAPER_LLM_MAX_WORKERS) as executor:
futures = {
- executor.submit(_score_single_paper, paper, api_key): cache_key
+ executor.submit(_score_single_paper, paper, api_key): (cache_key, paper)
for cache_key, paper in unique_papers.items()
}
for future in as_completed(futures):
- cache_key = futures[future]
+ cache_key, paper = futures[future]
try:
- _paper_llm_scores[cache_key] = future.result()
+ score = future.result()
except Exception:
- _paper_llm_scores[cache_key] = FAILED_PAPER_LLM_SCORE
+ score = FAILED_PAPER_LLM_SCORE
+ _paper_llm_scores[cache_key] = score
+ arxiv_id = _arxiv_id(paper)
+ if arxiv_id:
+ new_scores[arxiv_id] = score
+
+ if new_scores:
+ merged = dict(disk_cache)
+ merged.update(new_scores)
+ _save_paper_score_cache(prompt_hash, merged)
+
+ qualifying = sum(1 for item in papers if _is_qualifying_paper(item))
+ print(
+ f"Paper LLM scoring complete: {qualifying}/{len(papers)} qualifying "
+ f"(hybrid threshold {MIN_PAPER_LLM_SCORE}+ or score 3 w/ "
+ f"importance>={MIN_PAPER_HYBRID_IMPORTANCE})"
+ )
+ _save_paper_scores_debug(papers)
- qualifying = sum(1 for score in _paper_llm_scores.values() if score >= MIN_PAPER_LLM_SCORE)
- print(f"Paper LLM scoring complete: {qualifying}/{len(_paper_llm_scores)} scored >= {MIN_PAPER_LLM_SCORE}")
+
+def _save_paper_scores_debug(papers: List[Dict]) -> None:
+ """Write per-paper Mistral scores to logs/paper_scores_today.json."""
+ records = []
+ for paper in papers:
+ score = paper_llm_score(paper)
+ records.append({
+ "title": paper.get("title", ""),
+ "score": score,
+ "qualified": _is_qualifying_paper(paper),
+ "dropped": not _is_qualifying_paper(paper),
+ "source_url": paper.get("source_url", ""),
+ "arxiv_id": _arxiv_id(paper),
+ })
+ PAPER_SCORES_PATH.parent.mkdir(parents=True, exist_ok=True)
+ with PAPER_SCORES_PATH.open("w", encoding="utf-8") as handle:
+ json.dump(
+ {
+ "generated_at": datetime.now(TZ_CN).isoformat(),
+ "papers": records,
+ },
+ handle,
+ ensure_ascii=False,
+ indent=2,
+ )
+ print(f"Paper score debug log saved to: {PAPER_SCORES_PATH}")
def _parse_json_array_from_llm(text: str) -> List[Dict]:
@@ -1134,6 +1486,220 @@ def _verify_digest_with_mistral(
return verified
+def _memory_spine_match_keys(
+ memory_spine: List[Dict],
+) -> Tuple[Set[str], Set[Tuple[str, str]], Set[str]]:
+ """Build URL, (entity, content_type), and repo-key sets from the memory spine."""
+ urls: Set[str] = set()
+ entity_types: Set[Tuple[str, str]] = set()
+ repo_keys: Set[str] = set()
+ for entry in memory_spine:
+ url = _normalize_source_url(entry.get("source_url", ""))
+ if url:
+ urls.add(url)
+ entity = (entry.get("entity") or "").strip()
+ content_type = (entry.get("content_type") or "").strip()
+ if entity and content_type:
+ entity_types.add((entity, content_type))
+ repo_key = _github_repo_key(entry)
+ if repo_key:
+ repo_keys.add(repo_key)
+ return urls, entity_types, repo_keys
+
+
+def _editorial_verify_items(
+ candidates: List[Dict],
+ memory_spine: List[Dict],
+ exempt_keys: Optional[Set[str]] = None,
+) -> List[Dict]:
+ """Rule-based editorial verify with source-specific dedup rules."""
+ if not memory_spine:
+ return candidates
+ exempt = exempt_keys or set()
+ spine_urls, spine_entity_types, spine_repo_keys = _memory_spine_match_keys(memory_spine)
+ verified: List[Dict] = []
+ for item in candidates:
+ if _item_key(item) in exempt:
+ verified.append(item)
+ continue
+
+ source = item.get("source", "")
+ url = _normalize_source_url(item.get("source_url", ""))
+
+ if _is_ainews(item):
+ if url and url in spine_urls:
+ continue
+ verified.append(item)
+ continue
+
+ if source in ("github", "repo"):
+ repo_key = _github_repo_key(item)
+ if url and url in spine_urls:
+ continue
+ if repo_key and repo_key in spine_repo_keys:
+ continue
+ verified.append(item)
+ continue
+
+ if source in ("arxiv", "web"):
+ if url and url in spine_urls:
+ continue
+ entity = (item.get("entity") or "").strip()
+ content_type = (item.get("content_type") or "").strip()
+ if entity and content_type and (entity, content_type) in spine_entity_types:
+ continue
+ verified.append(item)
+ continue
+
+ if url and url in spine_urls:
+ continue
+ verified.append(item)
+ return verified
+
+
+def _generate_single_description(item: Dict, api_key: str) -> str:
+ try:
+ response = _mistral_client(api_key).chat.complete(
+ model=DESCRIPTION_LLM_MODEL,
+ messages=[
+ {"role": "system", "content": _DESCRIPTION_LLM_SYSTEM},
+ {
+ "role": "user",
+ "content": _DESCRIPTION_LLM_USER_TEMPLATE.format(
+ title=item.get("title", "") or "",
+ summary=(item.get("summary") or "")[:300],
+ source=item.get("source", "") or "",
+ ),
+ },
+ ],
+ temperature=0,
+ max_tokens=40,
+ )
+ text = (response.choices[0].message.content or "").strip()
+ text = text.strip('"').strip("'")
+ words = text.split()
+ if len(words) > 12:
+ text = " ".join(words[:12])
+ return text
+ except Exception:
+ summary = (item.get("summary") or "").strip()
+ words = summary.split()
+ return " ".join(words[:12]) if words else item.get("title", "")
+
+
+def _generate_digest_descriptions(items: List[Dict], api_key: Optional[str]) -> None:
+ """Pre-write one-line digest descriptions on each selected item."""
+ if not items:
+ return
+ if not api_key or not _HAS_MISTRAL:
+ for item in items:
+ summary = (item.get("summary") or "").strip()
+ words = summary.split()
+ item["digest_description"] = " ".join(words[:12]) if words else item.get("title", "")
+ return
+
+ print(f"Generating digest descriptions for {len(items)} items...")
+ with ThreadPoolExecutor(max_workers=PAPER_LLM_MAX_WORKERS) as executor:
+ futures = {
+ executor.submit(_generate_single_description, item, api_key): item
+ for item in items
+ }
+ for future in as_completed(futures):
+ item = futures[future]
+ try:
+ item["digest_description"] = future.result()
+ except Exception:
+ summary = (item.get("summary") or "").strip()
+ words = summary.split()
+ item["digest_description"] = " ".join(words[:12]) if words else item.get("title", "")
+
+
+def _rejection_reason(
+ item: Dict,
+ *,
+ filtered_items: List[Dict],
+ top_items: List[Dict],
+ verified_items: List[Dict],
+) -> str:
+ """Return why an item did not appear in the final digest."""
+ key = _item_key(item)
+ if key in {_item_key(row) for row in verified_items}:
+ return ""
+
+ if key in {_item_key(row) for row in top_items}:
+ return "editorial verify dedup"
+
+ _, stale_skipped, _ = filter_stale_items([item])
+ if stale_skipped:
+ return "stale date filter"
+
+ if _is_skipped_repo_content(item) or _is_skipped_github_trending(item):
+ return "repo skip policy"
+
+ if _is_frequency_capped(item):
+ count = _repo_delivery_count(item)
+ return f"frequency cap ({count}/{REPO_FREQUENCY_CAP} in {REPO_FREQUENCY_LOOKBACK_DAYS}d)"
+
+ if _is_maintenance_repo_release(item):
+ return "maintenance/plugin filter"
+
+ if item.get("source") == "arxiv" and not _is_qualifying_paper(item):
+ return (
+ f"paper LLM score {paper_llm_score(item)} below hybrid threshold "
+ f"({MIN_PAPER_LLM_SCORE}+ or 3 w/ >={MIN_PAPER_HYBRID_IMPORTANCE} importance)"
+ )
+
+ if not _is_eligible_for_digest(item):
+ return "failed eligibility"
+
+ if key not in {_item_key(row) for row in filtered_items}:
+ return "delivered-log dedup"
+
+ return "not selected (quota/ranking)"
+
+
+def _save_rejected_items(
+ raw_items: List[Dict],
+ *,
+ filtered_items: List[Dict],
+ top_items: List[Dict],
+ verified_items: List[Dict],
+) -> None:
+ """Save debug log of items not included in the final digest."""
+ verified_keys = {_item_key(item) for item in verified_items}
+ rejected = []
+ for item in raw_items:
+ key = _item_key(item)
+ if key in verified_keys:
+ continue
+ reason = _rejection_reason(
+ item,
+ filtered_items=filtered_items,
+ top_items=top_items,
+ verified_items=verified_items,
+ )
+ rejected.append({
+ "title": item.get("title", ""),
+ "source": item.get("source", ""),
+ "source_url": item.get("source_url", ""),
+ "importance": item.get("importance", 0),
+ "rejection_reason": reason or "unknown",
+ })
+ REJECTED_ITEMS_PATH.parent.mkdir(parents=True, exist_ok=True)
+ with REJECTED_ITEMS_PATH.open("w", encoding="utf-8") as handle:
+ json.dump(
+ {
+ "generated_at": datetime.now(TZ_CN).isoformat(),
+ "rejected_count": len(rejected),
+ "items": rejected,
+ },
+ handle,
+ ensure_ascii=False,
+ indent=2,
+ )
+ print(f"Rejected items debug log saved to: {REJECTED_ITEMS_PATH} ({len(rejected)} items)")
+
+
def _restore_quota_minimums(candidates: List[Dict], verified: List[Dict]) -> List[Dict]:
"""Re-add quota-minimum items removed by LLM verify (e.g. X signals deduped as same story)."""
verified_keys = {_item_key(item) for item in verified}
@@ -1165,7 +1731,7 @@ def _restore_quota_minimums(candidates: List[Dict], verified: List[Dict]) -> Lis
restored += 1
if restored:
- print(f"Restored {restored} quota-minimum item(s) after LLM verify")
+ print(f"Restored {restored} quota-minimum item(s) after editorial verify")
return sorted(result, key=lambda x: x.get("importance", 0), reverse=True)
@@ -1191,7 +1757,10 @@ def paper_llm_score(item: Dict) -> int:
def _is_qualifying_paper(item: Dict) -> bool:
if item.get("source") != "arxiv":
return False
- return paper_llm_score(item) >= MIN_PAPER_LLM_SCORE
+ score = paper_llm_score(item)
+ if score >= MIN_PAPER_LLM_SCORE:
+ return True
+ return score == FAILED_PAPER_LLM_SCORE and item.get("importance", 0) >= MIN_PAPER_HYBRID_IMPORTANCE
def _is_qualifying_web(item: Dict) -> bool:
@@ -1265,7 +1834,7 @@ def _changelog_bullets(text: str) -> List[str]:
def _is_claude_agent_sdk_sync_release(item: Dict) -> bool:
- """SDK releases that only sync bundled CLI or add internal wiring frames."""
+ """SDK releases that only sync bundled CLI, internal wiring, or minor telemetry fields."""
repo_key = _github_repo_key(item)
if not repo_key or not repo_key.startswith("anthropics/claude-agent-sdk"):
return False
@@ -1279,6 +1848,14 @@ def _is_claude_agent_sdk_sync_release(item: Dict) -> bool:
if not substantive or len(substantive) > 3:
return False
+ for bullet in substantive:
+ lower = bullet.lower()
+ if any(keyword in lower for keyword in _MAJOR_RELEASE_CAPABILITY_KEYWORDS):
+ return False
+
+ if all(bullet.lower().startswith("added") for bullet in substantive):
+ return True
+
return all(
bullet.lower().startswith("added")
and any(keyword in bullet.lower() for keyword in _SDK_SYNC_KEYWORDS)
@@ -1347,6 +1924,23 @@ def _is_github_trending(item: Dict) -> bool:
return "trending" in (item.get("source_label") or "").lower()
+def _github_trending_has_empty_description(item: Dict) -> bool:
+ """OSS Insight trending rows often ship without summary/raw_text."""
+ return not (item.get("summary") or "").strip() and not (item.get("raw_text") or "").strip()
+
+
+def _github_trending_slug_text(item: Dict) -> str:
+ repo_key = _github_repo_key(item)
+ title = item.get("title", "") or ""
+ return f"{title} {repo_key}".lower()
+
+
+def _is_trending_ai_from_slug(item: Dict) -> bool:
+ """AI signal from repo slug + title when description is empty."""
+ text = _github_trending_slug_text(item)
+ return any(keyword in text for keyword in _GITHUB_TRENDING_AI_KEYWORDS)
+
+
def _is_curated_repo_source(item: Dict) -> bool:
"""True for GitHub Trending and Good AI List repo entries."""
if item.get("source") == "repo" and _is_good_ai_list(item):
@@ -1364,6 +1958,8 @@ def _is_skipped_repo_content(item: Dict) -> bool:
return True
text = _github_text(item).lower()
+ if any(keyword in text for keyword in _REPO_NON_ENGINEERING_KEYWORDS):
+ return True
if any(keyword in text for keyword in _REPO_WEBSITE_CLONER_KEYWORDS):
return True
@@ -1439,6 +2035,8 @@ def _is_maintenance_repo_release(item: Dict) -> bool:
is_trending_style = is_github and _is_github_trending(item)
if is_trending_style:
+ if _github_trending_has_empty_description(item):
+ return not _is_trending_ai_from_slug(item)
return _is_short_low_signal_summary(summary)
if is_github and not is_trending_style:
@@ -1461,13 +2059,66 @@ def _is_qualifying_hackernews(item: Dict) -> bool:
if item.get("source") != "hackernews":
return False
text = f"{item.get('title', '')} {item.get('summary', '')}".lower()
+ title = (item.get("title") or "").lower()
if not any(keyword in text for keyword in _HN_INCLUDE_KEYWORDS):
return False
if any(term in text for term in _HN_CLOSED_COMMERCIAL):
+ if any(term in title for term in _HN_ENGINEERING_TITLE_TERMS):
+ return True
return any(signal in text for signal in _HN_OPEN_SIGNAL)
return True
+def _is_qualifying_ainews(item: Dict) -> bool:
+ if not _is_ainews(item) or _is_ainews_x(item):
+ return False
+ return bool((item.get("source_url") or "").strip())
+
+
+def _x_text(item: Dict) -> str:
+ return f"{item.get('title', '')} {item.get('summary', '')} {item.get('raw_text', '')}".lower()
+
+
+def _x_engagement(item: Dict) -> Tuple[int, int]:
+ engagement = item.get("engagement") or {}
+ return int(engagement.get("views") or 0), int(engagement.get("likes") or 0)
+
+
+def _x_quality_rejection_reason(item: Dict) -> Optional[str]:
+ """Return rejection reason for X-bucket items, or None if qualifying."""
+ if item.get("source") != "x" and not _is_ainews_x(item):
+ return None
+ text = _x_text(item)
+ if not any(keyword in text for keyword in _X_QUALITY_KEYWORDS):
+ return "x quality: missing engineering keyword"
+ if item.get("source") == "x":
+ views, likes = _x_engagement(item)
+ if views < _X_MIN_VIEWS and likes < _X_MIN_LIKES:
+ return f"x quality: low engagement ({views} views, {likes} likes)"
+ return None
+
+
+def _is_qualifying_x(item: Dict) -> bool:
+ if item.get("source") != "x" and not _is_ainews_x(item):
+ return False
+ return _x_quality_rejection_reason(item) is None
+
+
+def filter_x_quality(items: List[Dict]) -> Tuple[List[Dict], int, List[str]]:
+ """Remove X-bucket items that fail engineering keyword or engagement checks."""
+ kept: List[Dict] = []
+ skipped = 0
+ rejected_titles: List[str] = []
+ for item in items:
+ reason = _x_quality_rejection_reason(item)
+ if reason:
+ skipped += 1
+ rejected_titles.append(item.get("title") or reason)
+ continue
+ kept.append(item)
+ return kept, skipped, rejected_titles
+
+
def _is_qualifying_github(item: Dict) -> bool:
if item.get("source") != "github":
return True
@@ -1476,6 +2127,8 @@ def _is_qualifying_github(item: Dict) -> bool:
if _is_maintenance_repo_release(item):
return False
if _is_github_trending(item):
+ if _github_trending_has_empty_description(item):
+ return _is_trending_ai_from_slug(item)
return _is_ai_engineering_repo_text(_github_text(item))
return True
@@ -1491,6 +2144,8 @@ def _is_eligible_for_digest(item: Dict) -> bool:
if source == "arxiv":
return _is_qualifying_paper(item)
if source == "web":
+ if _is_ainews(item):
+ return _is_qualifying_ainews(item)
return _is_qualifying_web(item)
if source == "huggingface":
return _is_qualifying_huggingface(item)
@@ -1500,6 +2155,8 @@ def _is_eligible_for_digest(item: Dict) -> bool:
return _is_qualifying_good_ai_list(item)
if source == "hackernews":
return _is_qualifying_hackernews(item)
+ if source == "x" or _is_ainews_x(item):
+ return _is_qualifying_x(item)
return True
@@ -1519,7 +2176,7 @@ def _digest_category(item: Dict) -> str:
if _is_ainews_x(item):
return "Community (X via AINews)"
if _is_ainews(item):
- return "Web (AINews)"
+ return "AINews"
return "Web (Tavily)"
if source == "github":
if "Trending" in label:
@@ -1540,6 +2197,8 @@ def _quota_bucket(item: Dict) -> str:
return "good_ai_list"
if _is_ainews_x(item):
return "x"
+ if _is_ainews(item):
+ return "ainews"
source = item.get("source", "")
return {
"arxiv": "paper",
@@ -1557,13 +2216,19 @@ def _bucket_predicate(bucket: str) -> Callable[[Dict], bool]:
if bucket == "github":
return lambda item: item.get("source") == "github" and _is_qualifying_github(item)
if bucket == "web":
- return _is_qualifying_web
+ return lambda item: (
+ item.get("source") == "web"
+ and not _is_ainews(item)
+ and _is_qualifying_web(item)
+ )
+ if bucket == "ainews":
+ return _is_qualifying_ainews
if bucket == "huggingface":
return _is_qualifying_huggingface
if bucket == "good_ai_list":
return _is_qualifying_good_ai_list
if bucket == "x":
- return lambda item: item.get("source") == "x" or _is_ainews_x(item)
+ return lambda item: _is_qualifying_x(item)
if bucket == "hackernews":
return _is_qualifying_hackernews
return lambda item: False
@@ -1595,30 +2260,45 @@ def _good_ai_list_sort_key(item: Dict) -> Tuple[int, float]:
return (delivered_rank, -item.get("importance", 0))
+def _good_ai_list_redelivery_allowed(item: Dict, redelivered_count: int) -> bool:
+ """Good AI List repos delivered within lookback may not fill quota slots."""
+ if not _was_recently_delivered(item):
+ return True
+ return redelivered_count < GOOD_AI_LIST_MAX_REDELIVERED
+
+
def _good_ai_list_candidates(items: List[Dict]) -> List[Dict]:
"""Qualifying Good AI List repos sorted by freshness then score."""
- qualifying = [item for item in items if _is_qualifying_good_ai_list(item)]
+ qualifying = [
+ item for item in items
+ if _is_qualifying_good_ai_list(item) and not _was_recently_delivered(item)
+ ]
return sorted(qualifying, key=_good_ai_list_sort_key)
-def select_diverse_items(items: List[Dict], top_n: int = 10) -> List[Dict]:
+def select_diverse_items(items: List[Dict], top_n: int = 10) -> Tuple[List[Dict], Set[str]]:
"""Select top items with per-category min/max quotas.
- Minimums (when qualifying items exist) β€” filled before any overflow:
- - Papers: 1, Good AI List: 8, GitHub repos: 2, Web/Tavily: 1, X: 1
- - HuggingFace: 0
+ Minimums (when qualifying items exist):
+ - Papers: 2, Good AI List: 3, GitHub: 2, AINews: 2, Web/Tavily: 1
+ - HN: 1, X: 1, HuggingFace: 0
Maximums enforced throughout selection:
- - Papers: 4, GitHub repos: 5, Web/Tavily: 2, X: 2, HN: 2
- - HuggingFace: 2, Good AI List: 12
-
- Minimum quota phase runs paper first, then other buckets; overflow only after.
+ - Papers: 4, GitHub: 4, AINews: 4, Web/Tavily: 3, HN: 2, X: 2
+ - HuggingFace: 2, Good AI List: 6 (fresh repos only; no redelivery within 14d)
"""
sorted_items = sorted(items, key=lambda x: x.get("importance", 0), reverse=True)
paper_candidates = _paper_candidates(items)
gal_candidates = _good_ai_list_candidates(items)
+ gal_redelivered_selected = 0
+ ainews_candidates = sorted(
+ [item for item in items if _is_qualifying_ainews(item)],
+ key=lambda x: x.get("importance", 0),
+ reverse=True,
+ )
selected: List[Dict] = []
selected_keys: set = set()
+ quota_minimum_keys: Set[str] = set()
bucket_counts: Dict[str, int] = {}
def _try_add(item: Dict) -> bool:
@@ -1633,7 +2313,16 @@ def select_diverse_items(items: List[Dict], top_n: int = 10) -> List[Dict]:
bucket_counts[bucket] = bucket_counts.get(bucket, 0) + 1
return True
- for bucket in ("paper", "good_ai_list", "github", "web", "x", "huggingface"):
+ for bucket in (
+ "paper",
+ "good_ai_list",
+ "github",
+ "ainews",
+ "web",
+ "hackernews",
+ "x",
+ "huggingface",
+ ):
minimum = QUOTA_LIMITS[bucket]["min"]
if minimum <= 0:
continue
@@ -1650,14 +2339,34 @@ def select_diverse_items(items: List[Dict], top_n: int = 10) -> List[Dict]:
break
if not predicate(item):
continue
+ if bucket == "good_ai_list" and not _good_ai_list_redelivery_allowed(
+ item, gal_redelivered_selected
+ ):
+ continue
if _try_add(item):
+ if bucket == "good_ai_list" and _was_recently_delivered(item):
+ gal_redelivered_selected += 1
+ quota_minimum_keys.add(_item_key(item))
picked += 1
+ for item in ainews_candidates:
+ if len(selected) >= top_n:
+ break
+ key = _item_key(item)
+ if key in selected_keys:
+ continue
+ _try_add(item)
+
for item in sorted_items:
if len(selected) >= top_n:
break
key = _item_key(item)
- if key in selected_keys or _is_good_ai_list(item) or item.get("source") == "arxiv":
+ if (
+ key in selected_keys
+ or _is_good_ai_list(item)
+ or _is_ainews(item)
+ or item.get("source") == "arxiv"
+ ):
continue
if not _is_eligible_for_digest(item):
continue
@@ -1677,9 +2386,13 @@ def select_diverse_items(items: List[Dict], top_n: int = 10) -> List[Dict]:
key = _item_key(item)
if key in selected_keys:
continue
- _try_add(item)
+ if not _good_ai_list_redelivery_allowed(item, gal_redelivered_selected):
+ continue
+ if _try_add(item):
+ if _was_recently_delivered(item):
+ gal_redelivered_selected += 1
- return selected
+ return selected, quota_minimum_keys
def _boost_good_ai_list_scores(items: List[Dict]) -> None:
@@ -1724,6 +2437,9 @@ def _good_ai_list_item_status(
if not _is_qualifying_good_ai_list(item):
return "excluded: failed eligibility", base_score
+ if _was_recently_delivered(item):
+ return "excluded: delivered-log dedup (14d)", base_score
+
if key not in filtered_keys:
return "excluded: removed before selection", boosted_score
@@ -1731,8 +2447,6 @@ def _good_ai_list_item_status(
freshness = "previously delivered" if _was_recently_delivered(item) else "fresh"
return f"SELECTED ({freshness})", boosted_score
- if _was_recently_delivered(item):
- return "eligible: previously delivered (lower priority)", boosted_score
return "eligible: fresh (priority)", boosted_score
@@ -1796,8 +2510,401 @@ def _print_good_ai_list_selection_breakdown(selected_items: List[Dict]) -> None:
print(f" [{item.get('importance', 0):.1f}] {item.get('title', '')} (last: {delivered_on})")
-def filter_top_items(input_path: str, output_path: str, top_n: int = 20):
+def _audit_line(audit: bool, message: str) -> None:
+ if audit:
+ print(f"AUDIT: {message}")
+
+
+def _source_counts(items: List[Dict]) -> Counter:
+ return Counter(item.get("source") or "unknown" for item in items)
+
+
+def _stage_removal_report(label: str, before: List[Dict], after: List[Dict]) -> str:
+ before_c = _source_counts(before)
+ after_c = _source_counts(after)
+ lines = [
+ f"### {label}: {len(before)} -> {len(after)} (removed {len(before) - len(after)})",
+ f" {'source':<14} {'before':>7} {'after':>7} {'removed':>7}",
+ ]
+ for src in sorted(set(before_c) | set(after_c)):
+ b, a = before_c.get(src, 0), after_c.get(src, 0)
+ lines.append(f" {src:<14} {b:>7} {a:>7} {b - a:>7}")
+ return "\n".join(lines)
+
+
+def _count_bucket_qualifying(items: List[Dict]) -> Dict[str, int]:
+ counts: Dict[str, int] = {}
+ for bucket in QUOTA_LIMITS:
+ predicate = _bucket_predicate(bucket)
+ counts[bucket] = sum(1 for item in items if predicate(item))
+ return counts
+
+
+def _count_ineligible_by_reason(items: List[Dict]) -> Dict[str, Counter]:
+ """Per-source ineligibility reasons after frequency cap."""
+ by_source: Dict[str, Counter] = {}
+ for item in items:
+ if _is_eligible_for_digest(item):
+ continue
+ source = item.get("source") or "unknown"
+ if source == "arxiv":
+ score = paper_llm_score(item)
+ reason = f"paper score {score}"
+ elif _is_maintenance_repo_release(item):
+ reason = "maintenance/plugin"
+ elif _is_skipped_repo_content(item) or _is_skipped_github_trending(item):
+ reason = "repo skip policy"
+ elif source == "web":
+ reason = "web/ainews filter"
+ elif source == "huggingface":
+ reason = "hf keyword filter"
+ elif source == "hackernews":
+ reason = "hn keyword filter"
+ elif source == "x" or _is_ainews_x(item):
+ reason = _x_quality_rejection_reason(item) or "x quality filter"
+ else:
+ reason = "other eligibility"
+ by_source.setdefault(source, Counter())[reason] += 1
+ return by_source
+
+
+def _paper_score_distribution(items: List[Dict]) -> Tuple[Dict[int, int], int]:
+ """Score histogram (1-5) and qualifying count for arxiv items."""
+ dist: Dict[int, int] = {score: 0 for score in range(1, 6)}
+ dist[FAILED_PAPER_LLM_SCORE] = 0
+ qualifying = 0
+ for item in items:
+ if item.get("source") != "arxiv":
+ continue
+ score = paper_llm_score(item)
+ dist[score] = dist.get(score, 0) + 1
+ if _is_qualifying_paper(item):
+ qualifying += 1
+ return dist, qualifying
+
+
+def _bucket_fill_after_selection(items: List[Dict], top_n: int) -> Tuple[Dict[str, int], int, Set[str]]:
+ selected, quota_keys = select_diverse_items(items, top_n)
+ filled: Dict[str, int] = {}
+ for item in selected:
+ bucket = _quota_bucket(item)
+ filled[bucket] = filled.get(bucket, 0) + 1
+ return filled, len(selected), quota_keys
+
+
+def run_filter_debug_trace(raw_items: List[Dict], top_n: int = 30) -> str:
+ """Run pipeline stages and return a full per-source debug trace."""
+ _load_morning_ai_env()
+ lines: List[str] = [
+ "=" * 72,
+ f"FILTER DEBUG TRACE β€” top_n={top_n}, items_in={len(raw_items)}",
+ f"generated {datetime.now(TZ_CN).strftime('%Y-%m-%d %H:%M:%S')} UTC+8",
+ "=" * 72,
+ "",
+ "## 1. RAW INPUT BY SOURCE (before any filtering)",
+ ]
+ raw_c = _source_counts(raw_items)
+ lines.append(f" total: {len(raw_items)}")
+ for src, count in sorted(raw_c.items()):
+ lines.append(f" {src}: {count}")
+
+ items = list(raw_items)
+ score_papers_with_llm(items)
+
+ papers = [i for i in items if i.get("source") == "arxiv"]
+ dist, paper_qual = _paper_score_distribution(items)
+ lines.extend([
+ "",
+ "## 2. PAPER LLM SCORING (all arxiv in raw input)",
+ f" arxiv total: {len(papers)}",
+ f" qualifying (hybrid): {paper_qual}",
+ " score distribution:",
+ ])
+ for score in sorted(dist):
+ if dist[score]:
+ label = "score-3 (hybrid eligible if importance>=4.5)" if score == FAILED_PAPER_LLM_SCORE else f"score {score}"
+ lines.append(f" {label}: {dist[score]}")
+
+ stage_before = items
+ items, _, _ = filter_stale_items(items)
+ lines.extend(["", "## 3. PER-SOURCE SURVIVAL BY STAGE", "", _stage_removal_report("Date filter", stage_before, items)])
+
+ recent_delivered = _load_recent_delivered_urls()
+ stage_before = items
+ items, _ = filter_already_delivered(items, recent_delivered)
+ lines.extend(["", _stage_removal_report("Delivered-log dedup", stage_before, items)])
+
+ stage_before = items
+ items, _, _ = filter_frequency_capped(items)
+ lines.extend(["", _stage_removal_report("Frequency cap", stage_before, items)])
+
+ stage_before = items
+ items, _, _ = filter_x_quality(items)
+ lines.extend(["", _stage_removal_report("X quality filter", stage_before, items)])
+
+ post_freq = list(items)
+ eligible = [i for i in post_freq if _is_eligible_for_digest(i)]
+ ineligible = len(post_freq) - len(eligible)
+ lines.extend([
+ "",
+ f"### Eligibility (maintenance + source rules): {len(post_freq)} -> {len(eligible)} eligible ({ineligible} ineligible)",
+ f" {'source':<14} {'pool':>7} {'eligible':>9} {'blocked':>8}",
+ ])
+ pool_c = _source_counts(post_freq)
+ elig_c = _source_counts(eligible)
+ for src in sorted(pool_c):
+ pool_n = pool_c[src]
+ elig_n = elig_c.get(src, 0)
+ lines.append(f" {src:<14} {pool_n:>7} {elig_n:>9} {pool_n - elig_n:>8}")
+
+ inelig_by_source = _count_ineligible_by_reason(post_freq)
+ if inelig_by_source:
+ lines.append("")
+ lines.append(" Ineligibility reasons by source:")
+ for src in sorted(inelig_by_source):
+ for reason, count in inelig_by_source[src].most_common():
+ lines.append(f" {src}: {count} x {reason}")
+
+ hn_pool = [i for i in post_freq if i.get("source") == "hackernews"]
+ hn_elig = sum(1 for i in hn_pool if _is_qualifying_hackernews(i))
+ lines.extend([
+ "",
+ f"### HN keyword filter: {len(hn_pool)} in pool -> {hn_elig} qualifying",
+ ])
+
+ _boost_good_ai_list_scores(post_freq)
+ bucket_available = _count_bucket_qualifying(post_freq)
+ filled, selected_count, quota_keys = _bucket_fill_after_selection(post_freq, top_n)
+
+ lines.extend([
+ "",
+ "## 4. QUOTA BUCKET ANALYSIS",
+ f" target top_n: {top_n}",
+ f" {'bucket':<14} {'min':>4} {'max':>4} {'available':>10} {'filled':>7} {'gap_min':>8}",
+ ])
+ min_unfilled = 0
+ max_exhausted = 0
+ for bucket, limits in QUOTA_LIMITS.items():
+ avail = bucket_available.get(bucket, 0)
+ fill = filled.get(bucket, 0)
+ gap_min = max(0, limits["min"] - fill)
+ if gap_min and avail < limits["min"]:
+ min_unfilled += gap_min
+ if fill >= limits["max"] and selected_count < top_n:
+ max_exhausted += 1
+ lines.append(
+ f" {bucket:<14} {limits['min']:>4} {limits['max']:>4} {avail:>10} {fill:>7} {gap_min:>8}"
+ )
+
+ lines.extend([
+ "",
+ f" quota selection result: {selected_count} / {top_n} slots filled",
+ f" quota-minimum keys (verify-exempt): {len(quota_keys)}",
+ ])
+
+ selected, _ = select_diverse_items(post_freq, top_n)
+ memory_spine = _load_memory_spine(VERIFY_MEMORY_LOOKBACK_DAYS)
+ verified = _editorial_verify_items(selected, memory_spine, exempt_keys=quota_keys)
+ removed = len(selected) - len(verified)
+ lines.extend([
+ "",
+ "## 5. EDITORIAL VERIFY",
+ f" memory spine entries: {len(memory_spine)}",
+ f" before verify: {len(selected)}",
+ f" after verify: {len(verified)} (removed {removed}, {len(quota_keys)} exempt)",
+ ])
+ if removed:
+ removed_keys = {_item_key(i) for i in selected} - {_item_key(i) for i in verified}
+ lines.append(" removed items:")
+ for item in selected:
+ if _item_key(item) in removed_keys:
+ lines.append(f" [{_digest_category(item)}] {item.get('title', '')[:80]}")
+
+ lines.extend([
+ "",
+ "## 6. ROOT CAUSE SUMMARY",
+ ])
+
+ shortfall_quota = top_n - selected_count
+ shortfall_final = top_n - len(verified)
+ eligible_total = len(eligible)
+
+ causes: List[str] = []
+ if shortfall_quota > 0:
+ causes.append(
+ f"Quota selection filled only {selected_count}/{top_n} "
+ f"({shortfall_quota} unfilled) β€” eligible pool has {eligible_total} items"
+ )
+ for bucket, limits in QUOTA_LIMITS.items():
+ avail = bucket_available.get(bucket, 0)
+ if limits["min"] > 0 and avail < limits["min"]:
+ causes.append(f"Bucket '{bucket}' needs min {limits['min']} but only {avail} qualify")
+ zero_buckets = [b for b, c in bucket_available.items() if c == 0 and QUOTA_LIMITS[b]["min"] > 0]
+ if zero_buckets:
+ causes.append(f"Buckets with zero qualifying items: {', '.join(zero_buckets)}")
+ if removed > 0:
+ causes.append(f"Editorial verify removed {removed} items ({len(selected)} -> {len(verified)})")
+
+ ainews_avail = bucket_available.get("ainews", 0)
+ ainews_fill = filled.get("ainews", 0)
+ ainews_max = QUOTA_LIMITS["ainews"]["max"]
+ if ainews_fill < ainews_max and ainews_avail > ainews_fill:
+ causes.append(
+ f"AINews fill gap: {ainews_avail} qualify but only {ainews_fill}/{ainews_max} selected "
+ f"(no overflow pass beyond quota minimum)"
+ )
+
+ if not causes:
+ causes.append("Pipeline reached top_n; no major bottleneck detected.")
+
+ for cause in causes:
+ lines.append(f" - {cause}")
+
+ lines.extend([
+ "",
+ f"FINAL: {len(verified)} items in digest (target {top_n}, shortfall {shortfall_final})",
+ "=" * 72,
+ ])
+ return "\n".join(lines)
+
+
+def preview_digest_assessment(item: Dict) -> str:
+ """Predict why a raw collection item would or would not reach the digest."""
+ fresh, stale_skipped, _ = filter_stale_items([item])
+ if stale_skipped:
+ return "would drop: stale date filter"
+
+ if _is_frequency_capped(item):
+ count = _repo_delivery_count(item)
+ return f"would drop: frequency cap ({count}/{REPO_FREQUENCY_CAP} in {REPO_FREQUENCY_LOOKBACK_DAYS}d)"
+
+ if _is_maintenance_repo_release(item):
+ return "would drop: maintenance/plugin filter"
+
+ if _is_skipped_repo_content(item) or _is_skipped_github_trending(item):
+ return "would drop: repo skip policy"
+
+ if item.get("source") == "arxiv":
+ score = paper_llm_score(item)
+ if not _is_qualifying_paper(item):
+ if score < MIN_PAPER_LLM_SCORE and score != FAILED_PAPER_LLM_SCORE:
+ return f"would drop: paper LLM score {score} < {MIN_PAPER_LLM_SCORE}"
+ if score == FAILED_PAPER_LLM_SCORE and item.get("importance", 0) < MIN_PAPER_HYBRID_IMPORTANCE:
+ return (
+ f"would drop: paper LLM score 3 with importance "
+ f"{item.get('importance', 0):.1f} < {MIN_PAPER_HYBRID_IMPORTANCE}"
+ )
+ return f"would drop: paper LLM score {score} below threshold"
+ if _was_recently_delivered(item):
+ return f"eligible paper (score {score}); may compete if quota needs minimum"
+ return f"strong paper candidate (LLM score {score})"
+
+ recent = _load_recent_delivered_urls()
+ kept, dedup_skipped = filter_already_delivered([item], recent)
+ if dedup_skipped and item.get("source") not in ("arxiv",):
+ lookback = _delivered_lookback_days(item)
+ return f"would drop: delivered-log dedup ({lookback}d window)"
+
+ if not _is_eligible_for_digest(item):
+ return "would drop: failed source eligibility rules"
+
+ if _is_good_ai_list(item):
+ return "strong Good AI List candidate (fresh, boosted in ranking)"
+
+ if _was_recently_delivered(item):
+ return "eligible but previously delivered; lower selection priority"
+
+ return "eligible candidate; competes on importance + quota limits"
+
+
+def _audit_eligibility_breakdown(items: List[Dict]) -> Dict[str, int]:
+ """Count ineligibility reasons in the post-dedup candidate pool."""
+ counts: Dict[str, int] = {}
+ for item in items:
+ if _is_eligible_for_digest(item):
+ continue
+ source = item.get("source", "")
+ if source == "arxiv":
+ reason = (
+ f"paper LLM score {paper_llm_score(item)} below hybrid threshold "
+ f"({MIN_PAPER_LLM_SCORE}+ or 3 w/ >={MIN_PAPER_HYBRID_IMPORTANCE} importance)"
+ )
+ elif _is_maintenance_repo_release(item):
+ reason = "maintenance/plugin filter"
+ elif _is_skipped_repo_content(item) or _is_skipped_github_trending(item):
+ reason = "repo skip policy"
+ elif source == "web":
+ reason = "web relevance filter"
+ elif source == "huggingface":
+ reason = "huggingface keyword filter"
+ elif source == "hackernews":
+ reason = "hackernews relevance filter"
+ else:
+ reason = "failed eligibility"
+ counts[reason] = counts.get(reason, 0) + 1
+ return counts
+
+
+def analyze_collection(input_path: str, top_per_source: int = 10) -> None:
+ """Print per-source collection audit with top-N items and digest predictions."""
+ input_file = Path(input_path)
+ if not input_file.exists():
+ print(f"Error: Input file not found: {input_path}")
+ sys.exit(1)
+
+ with input_file.open("r", encoding="utf-8") as handle:
+ data = json.load(handle)
+
+ items = data.get("items", [])
+ if not items:
+ print("No items found in data file")
+ sys.exit(1)
+
+ _load_morning_ai_env()
+ score_papers_with_llm(items)
+
+ by_source: Dict[str, List[Dict]] = {}
+ for item in items:
+ source = item.get("source", "unknown")
+ by_source.setdefault(source, []).append(item)
+
+ print("=" * 72)
+ print(f"COLLECTION AUDIT: {input_file.name} ({len(items)} items, date={data.get('date', '?')})")
+ print("=" * 72)
+
+ for source in sorted(by_source):
+ source_items = sorted(by_source[source], key=lambda row: -row.get("importance", 0))
+ print(f"\n## SOURCE: {source} ({len(source_items)} items)")
+ print("-" * 72)
+ for rank, item in enumerate(source_items[:top_per_source], start=1):
+ label = item.get("source_label", "")
+ assessment = preview_digest_assessment(item)
+ title = (item.get("title") or "No title")[:90]
+ print(
+ f" {rank:2}. [{item.get('importance', 0):.1f}] {title}\n"
+ f" label={label or '-'} | {assessment}"
+ )
+ if len(source_items) > top_per_source:
+ print(f" ... and {len(source_items) - top_per_source} more items")
+
+ stats = data.get("stats", {}).get("by_source", {})
+ if stats:
+ print("\n## RAW COLLECTOR COUNTS (from stats.by_source)")
+ for source in sorted(stats):
+ info = stats[source]
+ print(f" {source}: {info.get('items', 0)} items")
+
+
+def filter_top_items(
+ input_path: str,
+ output_path: str,
+ top_n: int = 30,
+ audit: bool = False,
+ debug: bool = False,
+):
"""Read the full collection JSON and output diverse top-N scored items."""
+ if debug:
+ audit = True
input_file = Path(input_path)
if not input_file.exists():
@@ -1807,22 +2914,51 @@ def filter_top_items(input_path: str, output_path: str, top_n: int = 20):
with open(input_file, "r", encoding="utf-8") as f:
data = json.load(f)
- items = data.get("items", [])
+ raw_items = data.get("items", [])
+ items = list(raw_items)
if not items:
print("No items found in data file")
sys.exit(1)
+ if debug:
+ trace = run_filter_debug_trace(copy.deepcopy(raw_items), top_n)
+ FILTER_DEBUG_TRACE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ FILTER_DEBUG_TRACE_PATH.write_text(trace + "\n", encoding="utf-8")
+ print(f"Debug trace saved to: {FILTER_DEBUG_TRACE_PATH}\n")
+
print(f"Total items before filtering: {len(items)}")
+ _audit_line(audit, f"stage 0 input items: {len(items)}")
+ if audit:
+ raw_c = _source_counts(items)
+ print(f"AUDIT: raw by source β€” {dict(sorted(raw_c.items()))}")
_load_morning_ai_env()
score_papers_with_llm(items)
+ papers = [item for item in items if item.get("source") == "arxiv"]
+ paper_below = sum(1 for item in papers if not _is_qualifying_paper(item))
+ paper_qualifying = sum(1 for item in papers if _is_qualifying_paper(item))
+ if audit:
+ print(
+ f"AUDIT: paper LLM scoring β€” {len(papers)} arxiv items, "
+ f"{paper_qualifying} qualifying (hybrid), "
+ f"{paper_below} below threshold"
+ )
+
+ pre_date_count = len(items)
items, stale_count, source_counts = filter_stale_items(items)
+ _audit_line(
+ audit,
+ f"stage 1 date filter β€” {pre_date_count} -> {len(items)} "
+ f"(removed {stale_count} stale)",
+ )
print(f"Skipped {stale_count} stale items (source-specific date cutoffs)")
print("Items per source after date filter:")
for source in sorted(source_counts):
print(f" {source}: {source_counts[source]}")
+ if audit:
+ print(f"AUDIT: after date filter by source β€” {dict(sorted(source_counts.items()))}")
recent_delivered = _load_recent_delivered_urls()
match_total, match_url, match_repo = _count_delivered_candidate_matches(items)
@@ -1830,18 +2966,27 @@ def filter_top_items(input_path: str, output_path: str, top_n: int = 20):
f"Delivered-log matches among candidates before selection: "
f"{match_total} total ({match_url} by URL, {match_repo} by GitHub repo key)"
)
+ pre_dedup_count = len(items)
items, dedup_count = filter_already_delivered(items, recent_delivered)
- gal_redeliverable = sum(
- 1 for item in items if _is_good_ai_list(item) and _was_recently_delivered(item)
+ _audit_line(
+ audit,
+ f"stage 2 delivered-log dedup β€” {pre_dedup_count} -> {len(items)} "
+ f"(removed {dedup_count})",
+ )
+ if audit:
+ print(f"AUDIT: after dedup by source β€” {dict(sorted(_source_counts(items).items()))}")
+ gal_redelivered_blocked = sum(
+ 1 for item in raw_items
+ if _is_good_ai_list(item) and _was_recently_delivered(item)
)
paper_redeliverable = sum(
1 for item in items
if item.get("source") == "arxiv" and _was_recently_delivered(item)
)
- if gal_redeliverable:
+ if gal_redelivered_blocked:
print(
- f"Good AI List: retained {gal_redeliverable} previously-delivered repos "
- f"for freshness-priority selection"
+ f"Good AI List: blocked {gal_redelivered_blocked} previously-delivered repos "
+ f"(within {GITHUB_REPO_DELIVERED_LOOKBACK_DAYS}d lookback)"
)
if paper_redeliverable:
print(
@@ -1850,10 +2995,26 @@ def filter_top_items(input_path: str, output_path: str, top_n: int = 20):
)
print(
f"Skipped {dedup_count} already-delivered items "
- f"(GitHub/Good AI List: {GITHUB_REPO_DELIVERED_LOOKBACK_DAYS}d, others: {DEFAULT_DELIVERED_LOOKBACK_DAYS}d)"
+ f"(Good AI List: {GITHUB_REPO_DELIVERED_LOOKBACK_DAYS}d, "
+ f"GitHub releases: {GITHUB_REPO_DELIVERED_LOOKBACK_DAYS}d repo+semver, "
+ f"GitHub Trending: {GITHUB_TRENDING_DELIVERED_LOOKBACK_DAYS}d, "
+ f"AINews: {AINEWS_DELIVERED_LOOKBACK_DAYS}d, "
+ f"HN Show/Launch: {HN_SHOW_LAUNCH_DELIVERED_LOOKBACK_DAYS}d, "
+ f"others: {DEFAULT_DELIVERED_LOOKBACK_DAYS}d)"
)
+ pre_freq_count = len(items)
items, freq_skipped, freq_capped = filter_frequency_capped(items)
+ _audit_line(
+ audit,
+ f"stage 3 frequency cap β€” {pre_freq_count} -> {len(items)} "
+ f"(removed {freq_skipped})",
+ )
+ if audit and freq_capped:
+ for title in sorted(set(freq_capped)):
+ print(f"AUDIT: frequency-capped: {title}")
+ if audit:
+ print(f"AUDIT: after frequency cap by source β€” {dict(sorted(_source_counts(items).items()))}")
if freq_skipped:
print(
f"Skipped {freq_skipped} repos at frequency cap "
@@ -1862,44 +3023,97 @@ def filter_top_items(input_path: str, output_path: str, top_n: int = 20):
for title in sorted(set(freq_capped)):
print(f" - {title}")
+ pre_x_quality_count = len(items)
+ items, x_quality_skipped, x_quality_rejected = filter_x_quality(items)
+ _audit_line(
+ audit,
+ f"stage 3b x quality filter β€” {pre_x_quality_count} -> {len(items)} "
+ f"(removed {x_quality_skipped})",
+ )
+ if x_quality_skipped:
+ print(f"Skipped {x_quality_skipped} X items (engineering keyword / engagement filter):")
+ for title in sorted(set(x_quality_rejected)):
+ print(f" - {title[:80]}")
+ if audit and x_quality_rejected:
+ for title in sorted(set(x_quality_rejected)):
+ print(f"AUDIT: x-quality-rejected: {title[:80]}")
+
+ if audit:
+ eligibility = _audit_eligibility_breakdown(items)
+ eligible_count = sum(1 for item in items if _is_eligible_for_digest(item))
+ print(
+ f"AUDIT: stage 4 eligibility in remaining pool β€” "
+ f"{eligible_count} eligible, {len(items) - eligible_count} ineligible"
+ )
+ print(f"AUDIT: eligible by source β€” {dict(sorted(_source_counts([i for i in items if _is_eligible_for_digest(i)]).items()))}")
+ bucket_avail = _count_bucket_qualifying(items)
+ print("AUDIT: qualifying per quota bucket β€” " + ", ".join(
+ f"{b}={bucket_avail[b]}" for b in QUOTA_LIMITS
+ ))
+ for reason, count in sorted(eligibility.items(), key=lambda row: -row[1]):
+ print(f"AUDIT: ineligible: {count} x {reason}")
+
_boost_good_ai_list_scores(items)
- top_items = select_diverse_items(items, top_n)
+ top_items, quota_minimum_keys = select_diverse_items(items, top_n)
+ if quota_minimum_keys:
+ print(f"Quota-minimum items protected from editorial verify: {len(quota_minimum_keys)}")
+ _audit_line(
+ audit,
+ f"stage 5 quota selection β€” selected {len(top_items)} of top {top_n} requested",
+ )
+ if audit:
+ filled: Dict[str, int] = {}
+ for item in top_items:
+ b = _quota_bucket(item)
+ filled[b] = filled.get(b, 0) + 1
+ print("AUDIT: quota bucket fill β€” " + ", ".join(
+ f"{b}={filled.get(b, 0)}/{QUOTA_LIMITS[b]['max']}" for b in QUOTA_LIMITS
+ ))
_print_good_ai_list_audit(data.get("items", []), items, top_items)
- _print_top_items_list(f"Top {len(top_items)} items BEFORE LLM verify:", top_items)
+ _print_top_items_list(f"Top {len(top_items)} items BEFORE editorial verify:", top_items)
memory_spine = _load_memory_spine(VERIFY_MEMORY_LOOKBACK_DAYS)
verified_items = top_items
verify_api_key = _load_mistral_api_key()
- if memory_spine and verify_api_key and _HAS_MISTRAL:
- print(f"Running Mistral editorial verify against {len(memory_spine)} memory-spine entries...")
- try:
- verified_items = _verify_digest_with_mistral(top_items, memory_spine, verify_api_key)
- verified_items = _restore_quota_minimums(top_items, verified_items)
- removed = len(top_items) - len(verified_items)
- print(f"LLM verifier removed {removed} item(s)")
- except Exception as exc:
- print(f"Warning: LLM verify failed ({exc}); using unverified selection")
- verified_items = top_items
- elif memory_spine and not verify_api_key:
- print("Warning: MISTRAL_API_KEY not set; skipping LLM verify step")
+ pre_verify_count = len(top_items)
+ if memory_spine:
+ print(f"Running editorial verify against {len(memory_spine)} memory-spine entries...")
+ verified_items = _editorial_verify_items(
+ top_items,
+ memory_spine,
+ exempt_keys=quota_minimum_keys,
+ )
+ removed = pre_verify_count - len(verified_items)
+ _audit_line(
+ audit,
+ f"stage 6 editorial verify β€” {pre_verify_count} -> {len(verified_items)} "
+ f"(removed {removed}, {len(quota_minimum_keys)} exempt)",
+ )
+ print(f"Editorial verify removed {removed} item(s)")
else:
- print("No memory spine entries; skipping LLM verify step")
+ print("No memory spine entries; skipping editorial verify step")
+ _audit_line(audit, "stage 6 editorial verify β€” skipped (empty memory spine)")
+
+ _audit_line(audit, f"stage 7 final digest count: {len(verified_items)}")
- _print_top_items_list(f"Top {len(verified_items)} items AFTER LLM verify:", verified_items)
+ _print_top_items_list(f"Top {len(verified_items)} items AFTER editorial verify:", verified_items)
+
+ _generate_digest_descriptions(verified_items, verify_api_key)
print("Category counts:")
for category, count in sorted(_category_counts(verified_items).items()):
print(f" {category}: {count}")
+ generated_at = datetime.now(timezone.utc).isoformat()
output_data = {
"date": data.get("date", datetime.now().strftime("%Y-%m-%d")),
- "generated_at": data.get("generated_at", ""),
+ "generated_at": generated_at,
"items": verified_items,
"stats": {
- "total_collected": len(items),
+ "total_collected": len(raw_items),
"total_in_digest": len(verified_items),
"before_verify": len(top_items),
"removed_by_verify": len(top_items) - len(verified_items),
@@ -1915,10 +3129,19 @@ def filter_top_items(input_path: str, output_path: str, top_n: int = 20):
delivery_date = output_data["date"]
_append_delivered_items(verified_items, delivery_date)
+ _save_rejected_items(
+ raw_items,
+ filtered_items=items,
+ top_items=top_items,
+ verified_items=verified_items,
+ )
print(f"Filtered digest input saved to: {output_path}")
print(f"File size: {output_file.stat().st_size / 1024:.1f}KB")
+ if debug and FILTER_DEBUG_TRACE_PATH.exists():
+ print("\n" + FILTER_DEBUG_TRACE_PATH.read_text(encoding="utf-8"))
+
def _category_counts(items: List[Dict]) -> Dict[str, int]:
counts: Dict[str, int] = {}
@@ -1930,12 +3153,37 @@ def _category_counts(items: List[Dict]) -> Dict[str, int]:
def main():
parser = argparse.ArgumentParser(description="Filter top scored items for digest generation")
- parser.add_argument("input", help="Path to the full collection JSON file")
- parser.add_argument("output", help="Path to save the filtered output JSON")
- parser.add_argument("--top", type=int, default=20, help="Number of top items to keep (default: 20)")
+ parser.add_argument("input", nargs="?", help="Path to the full collection JSON file")
+ parser.add_argument("output", nargs="?", help="Path to save the filtered output JSON")
+ parser.add_argument("--top", type=int, default=30, help="Number of top items to keep (default: 30)")
+ parser.add_argument(
+ "--audit",
+ action="store_true",
+ help="Print stage-by-stage removal counts during filtering",
+ )
+ parser.add_argument(
+ "--debug",
+ action="store_true",
+ help="Full per-source stage trace + quota analysis (implies --audit); saves to logs/filter_debug_trace.txt",
+ )
+ parser.add_argument(
+ "--analyze-input",
+ action="store_true",
+ help="Audit raw collection JSON per source (no filter output written)",
+ )
args = parser.parse_args()
- filter_top_items(args.input, args.output, args.top)
+ if args.analyze_input:
+ if not args.input:
+ print("Error: --analyze-input requires an input JSON path", file=sys.stderr)
+ sys.exit(1)
+ analyze_collection(args.input)
+ return
+
+ if not args.input or not args.output:
+ parser.error("input and output paths are required unless --analyze-input is set")
+
+ filter_top_items(args.input, args.output, args.top, audit=args.audit, debug=args.debug)
if __name__ == "__main__":
diff --git a/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txt b/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txt
index ad9c019..44cba22 100644
--- a/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txt
+++ b/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txt
@@ -1,179 +1,460 @@
You are the AI Engineering Research Agent digest writer.
-YOUR ONLY JOB THIS RUN: read pre-filtered collection data and output a curated Slack digest.
+
+
+YOUR ONLY JOB THIS RUN: read pre-filtered collection data and deliver a curated Slack digest.
+
+
+
Do NOT run Python scripts, shell commands, data collection, or filtering. The Windows Task Scheduler pipeline already ran at 7:45am Lagos time and produced the input file.
+
+
CRITICAL - HOW SLACK DELIVERY WORKS:
-OpenClaw cron automatically posts your FINAL assistant reply to Slack channel C0BFZF1LGCE.
-You do NOT post to Slack yourself. Do NOT use sessions_send, Slack tools, write, or exec for delivery.
-Your last message in this turn must BE the digest - nothing before it, nothing after it.
+
+OpenClaw cron delivery mode is `none` - your final assistant reply is NOT posted to Slack.
+
+You MUST deliver the digest yourself using the OpenClaw `message` tool in two steps:
+
+Step 1 - Post title only (top-level channel message):
+ Call the `message` tool with:
+ action="send"
+ channel="slack"
+ target="channel:C0BH9MD221H"
+ message="πŸ“° AI Engineering Digest - {DATE}"
+ Save the returned `messageId` from the tool result.
+
+Step 2 - Post all section content as a thread reply:
+ Call the `message` tool with:
+ action="send"
+ channel="slack"
+ target="channel:C0BH9MD221H"
+ threadId=<messageId from step 1>
+ message=<all section blocks - do NOT repeat the title line>
+
+Your final assistant reply after both message tool calls must be a brief internal confirmation only (e.g. "Digest posted to Slack."). It is NOT delivered to Slack.
+
+
FORBIDDEN ACTIONS (will break delivery):
-- sessions_send / message / slack_* tools (channel IDs are not session keys)
+
+- sessions_send (channel IDs are not session keys)
+
+- slack_* tools other than the unified `message` tool
+
- write or exec to save digest to a file (no digest_for_slack.txt, no digest_output_today.md)
+
- web_fetch on local file paths (use read tool for local files only)
+
- Overwriting digest_input_today.json or editorial_profile.md
-- Any preamble, apology, or "saved to file" fallback if posting fails - there is no manual post step
+
+- Any preamble, apology, or "saved to file" fallback if posting fails - always use the message tool
+
+
---
+
+
STEP 1 - READ INPUT (required)
+
+
Use the read tool ONCE on:
-C:\Users\HP\Documents\MorningAI\digest_input_today.json
-It contains pre-scored items (fields: title, summary, entity, content_type, source, source_url, source_label, date, importance, relevance).
-If the file does not exist or has zero items, your final reply must be exactly:
-"No qualifying AI engineering updates today - digest_input_today.json missing or empty. Check Windows Task Scheduler pipeline."
+{DEVABLE_PROJECT_ROOT}/digest_input_today.json
+
+
+
+It contains pre-scored items with fields: title, digest_description, summary, entity, content_type, source, source_url, source_label, date, importance, relevance.
+
+
+
+If the file does not exist or has zero items:
+ Step 1 message: "πŸ“° AI Engineering Digest - {DATE}" (use today's date)
+ Step 2 thread message (exactly): "No qualifying AI engineering updates today - digest_input_today.json missing or empty. Check Windows Task Scheduler pipeline."
+ Then reply with a brief internal confirmation only.
+
+
+
+If `generated_at` in the JSON is older than 24 hours:
+ Step 1 message: "πŸ“° AI Engineering Digest - {DATE}" (use today's date)
+ Step 2 thread message (exactly): "digest_input_today.json is stale - run scripts/run_pipeline.bat (or filter_top_items.py) before posting today's digest."
+ Then reply with a brief internal confirmation only.
+
-If `generated_at` in the JSON is older than 24 hours, your final reply must be exactly:
-"digest_input_today.json is stale - run scripts/run_pipeline.bat (or filter_top_items.py) before posting today's digest."
---
+
+
STEP 2 - APPLY EDITORIAL STANDARDS (required)
+
+
+CRITICAL - PRE-FILTERED INPUT:
+
+Every item in digest_input_today.json has already passed the Windows pipeline filter
+(quality gates, diversity quotas, dedup, and editorial verify). Do NOT re-filter or
+drop items from the JSON. Your job is categorization and Slack formatting only.
+
+If an item has a valid source_url, it MUST appear in exactly one Slack section below.
+Do not exclude items for being low importance, hype, or opinion β€” the pipeline already
+decided inclusion.
+
+
+
Follow the inclusion/exclusion rules in:
-C:\Users\HP\.config\morning-ai\editorial_profile.md
+
+
+{DEVABLE_PROJECT_ROOT}/../.config/morning-ai/editorial_profile.md
+
+
+
+If that path is unavailable, read ~/.config/morning-ai/editorial_profile.md with the read tool.
+
+
(Read it with the read tool if needed - do not rewrite the file.)
+
+
Audience: AI engineers who build with LLMs, agents, and open-source tools. They ship products, not news commentary.
+(The INCLUDE/EXCLUDE lists below were already applied by the pipeline filter.
+Do not use them to drop items from digest_input_today.json β€” use them only as
+guidance when writing or shortening digest_description text.)
+
+
+
INCLUDE only items where a builder could act, build with, or learn something concrete today:
+
- Open-weight model releases with runnable weights or meaningful benchmark gains
+
- New agent frameworks, inference/serving tools, eval/observability tooling with real capability
+
- arXiv papers with practical engineering application (agents, reasoning, tool use, efficiency)
+
- GitHub repos with clear engineering value and strong weekly momentum
+
- HuggingFace models/datasets that enable new build or fine-tuning workflows
+
- AINews signals (`source_label: AINews`) with concrete builder relevance
+
+
EXCLUDE always (even if high importance score):
+
- Maintenance releases, bug fixes, dependency bumps, CI/licensing-only changes
+
- Releases whose summary is effectively "various updates and bug fixes"
+
- Opinion pieces, hype, AI commentary with no new technical substance
+
- Social applications of AI, medical/policy papers with no builder application
+
- Consumer AI apps unless they expose a significant new builder capability
+
- Generic IDE/tooling updates without AI-specific capability
+
- Finance/trading repos (stock, trading, forex, crypto trading, investment) - not AI engineering
+
- Devable Research Agent plugin repos (devable-research-agent skill, last30days, tracking-list skill)
+
- Offensive-security cheat-sheet launchers (cybersecurity cheat-sheet, penetration testing, "just install and start hacking")
+
+
Each included item MUST answer: "What changed, and why does it matter to a builder?" - not just what it is.
+
+
---
+
+
STEP 3 - SELECT AND CATEGORIZE
+
+
Rules:
-- Use ONLY items from digest_input_today.json that pass editorial standards
-- Every item MUST have a valid source_url - drop items without one
-- Prefer items from the last 24-48 hours when date is available
+
+- Include ALL items from digest_input_today.json β€” do not apply additional editorial filtering
+
+- Every item MUST have a valid source_url - drop items without one (should not happen)
+
+- Prefer items from the last 24-48 hours when date is available (informational only; do not drop older items already in the JSON)
+
- Include all qualifying items - no fixed total cap and no fixed per-section cap
+
- Skip sections with no qualifying items entirely (do not show empty headers)
+- You MUST render every non-empty section that has items in the JSON (Top Papers, Trending Repos, What's Trending on X, etc.) β€” never post only one section when the JSON has multiple sources
+
+
+
Map each qualifying item to exactly one section:
+
+
| Section | Include when |
+
|---------|----------------|
+
| Top Papers | source: arxiv |
+
| Trending Repos | source: repo or github (Good AI List, GitHub releases, GitHub Trending) |
+
| What's Trending on X | source: x; OR AINews with source_url on x.com or twitter.com |
+
| What Happened on Reddit | source: reddit; OR AINews with source_url on reddit.com |
+
| New Model Drops | content_type: model; source: huggingface; OR model release announcements (new weights, benchmarks, API model launches) even from AINews or web |
+
| New Tools | content_type: product; source: web with source_label: Tavily; HN tool launches; frameworks, SDKs, inference engines, agent tooling |
+
+
AINews routing (strict - check source_url first, then content):
+
1. reddit.com in source_url -> What Happened on Reddit
+
2. x.com or twitter.com in source_url -> What's Trending on X
+
3. Model release, weight drop, benchmark launch, or new model API -> New Model Drops (NOT New Tools)
+
4. Framework, SDK, agent tool, inference stack, dev utility -> New Tools
-If zero items qualify after editorial filtering, your final reply must be exactly:
-"No qualifying AI engineering updates today."
+
+
+If zero items qualify after editorial filtering:
+ Step 1 message: "πŸ“° AI Engineering Digest - {DATE}"
+ Step 2 thread message (exactly): "No qualifying AI engineering updates today."
+ Then reply with a brief internal confirmation only.
+
+
---
-STEP 4 - OUTPUT (your final reply IS the Slack message)
+
+
+STEP 4 - BUILD SLACK CONTENT
+
+
+
+TITLE (Step 1 message only):
+
+ πŸ“° AI Engineering Digest - {DATE}
+
+
+
+THREAD BODY (Step 2 message - all sections, NO title line):
+
+
OUTPUT RULE - STRICT, NO EXCEPTIONS:
-Do NOT include any preamble, commentary, confirmation messages, or closing statements.
-Output ONLY the digest content itself.
-Forbidden: "This output has adhered...", "I will now post...", "Here's your digest",
+
+Do NOT include the title line in the thread body.
+
+Do NOT include any preamble, commentary, confirmation messages, or closing statements in the thread body.
+
+Output ONLY the section content itself.
+
+Forbidden in thread body: "This output has adhered...", "I will now post...", "Here's your digest",
+
"Please copy and paste...", "saved to a text file", "Download Digest", run logs, apologies, or any meta text.
-The digest starts with the date header and ends with the last item link. Nothing else.
+
+The thread body starts with the first section header and ends with the last item link. Nothing else.
+
+
SLACK LINK FORMAT - MANDATORY ON EVERY ITEM LINE:
+
Every item line MUST end with Slack angle-bracket syntax: <https://full-source-url|link>
+
NEVER output bare URLs like https://example.com - they trigger Slack unfurl preview cards.
+
BAD: - Paper title - description here - https://arxiv.org/abs/1234
+
GOOD: - Paper title - description here - <https://arxiv.org/abs/1234|link>
+
The label after the pipe is always the literal word "link" (lowercase).
+
+
ITEM LINE RULE (strict):
+
Each item is ONE line only, exactly three parts:
+
Title - one specific sentence (max 12 words) - <URL|link>
+
+
+Use digest_description from the JSON as the middle segment whenever present.
+
+Only fall back to summary if digest_description is missing.
+
+Do NOT rewrite digest_description unless it exceeds 12 words β€” then shorten it.
+
+
+
Nothing more. No second sentence. No line breaks inside an item. No trailing text after the link.
+
+
+FEW-SHOT EXAMPLES (good vs bad item lines):
+
+
+
+GOOD repo line:
+
+- vllm-project/vllm - High-throughput LLM serving with paged KV cache - <https://github.com/vllm-project/vllm|link>
+
+
+
+BAD repo line (marketing fluff, no technical substance):
+
+- vllm-project/vllm - Revolutionizing AI inference for modern enterprises - <https://github.com/vllm-project/vllm|link>
+
+
+
+GOOD paper line:
+
+- AgentTrace - Runtime substrate for reversible agent execution with Git-like traces - <https://arxiv.org/abs/2401.00001|link>
+
+
+
+BAD paper line (bare URL triggers Slack unfurl card):
+
+- AgentTrace - Runtime substrate for reversible agent execution - https://arxiv.org/abs/2401.00001
+
+
+
+GOOD X signal line:
+
+- MCP tool-use benchmark thread - Engineers comparing agent tool-call reliability across frameworks - <https://x.com/user/status/123|link>
+
+
+
+BAD X signal line (vague, not actionable for builders):
+
+- MCP tool-use benchmark thread - Interesting AI discussion happening on X today - <https://x.com/user/status/123|link>
+
+
+
URL format (Slack - prevents unfurling):
+
- Use Slack's angle-bracket link syntax: <https://full-url|link>
+
- The visible label is always the literal word "link" (lowercase)
+
- Do NOT use bare URLs, markdown links, or any text after the closing >
+
+
Description rules:
+
+- Prefer digest_description verbatim when present
+
- Must be specific and technical - state what it does, not marketing fluff
+
- BAD: "adapts to user needs", "enhances productivity", "flexible AI agent", "revolutionizing video production"
+
- GOOD: "Runtime substrate for reversible agent execution with Git-like traces"
+
- GOOD: "Four-tier local memory pipeline for agent context without external deps"
-- GOOD: "Semantic firewall auditing token flows before privileged agent sinks"
+
- Count words in the middle segment; if over 12 words, shorten it
-Use this EXACT format - blank line between sections, ASCII separators only:
-πŸ“° AI Engineering Digest - {DATE}
+
+Use this EXACT format for the thread body - blank line between sections, ASCII separators only:
+
+
πŸ“„ Top Papers
+
- Paper title - specific technical one-liner max 12 words - <https://example.com|link>
+
+
πŸ“¦ Trending Repos
+
- Repo name - specific technical one-liner max 12 words - <https://example.com|link>
+
+
🐦 What's Trending on X
+
- Signal title - specific technical one-liner max 12 words - <https://example.com|link>
+
+
πŸ’¬ What Happened on Reddit
+
- Thread title - specific technical one-liner max 12 words - <https://example.com|link>
+
+
πŸ€— New Model Drops
+
- Model name - specific technical one-liner max 12 words - <https://example.com|link>
+
+
πŸ›  New Tools
+
- Tool name - specific technical one-liner max 12 words - <https://example.com|link>
+
+
Formatting rules:
+
- Replace {DATE} with the digest date from the JSON (YYYY-MM-DD)
+
- Include ONLY sections that have at least one qualifying item
+
- Put ONE blank line between each section block (after the last item of a section, before the next section header)
+
- Use ASCII hyphen-minus (-) for bullets; NEVER use bullet character or other unicode list markers
+
- Use ASCII " - " (space-hyphen-space) as the field separator; NEVER use em dash or en dash in item lines
+
- End each line with source_url in Slack link format ONLY: <full-url|link>
+
- NEVER use bare https:// URLs anywhere in the digest
+
- The <url|link> token must be the final token on the line - no characters after the closing >
+
- Do NOT show importance scores, star counts, or vanity metrics unless the surge itself is the news
-- No blank preamble before the header; no footer after the last item
+
+- No blank preamble before the first section header; no footer after the last item
+
+
---
-STEP 5 - DONE
-After reading the input file, output the digest directly as your final reply.
-Do not call any more tools after you have the data you need.
-OpenClaw will deliver that reply to Slack automatically.
-BEFORE YOU REPLY - verify every item line ends with <https://...|link> not a bare URL.
+STEP 5 - DELIVER AND CONFIRM
+
+
+
+After building the title and thread body:
+
+1. Call the `message` tool to post the title (Step 1).
+
+2. Call the `message` tool again with threadId from step 1 to post all sections (Step 2).
+
+3. Reply with a brief internal confirmation only (e.g. "Digest posted to Slack: title + thread."). This reply is NOT posted to Slack.
+
+
+
+BEFORE POSTING - verify every item line ends with <https://...|link> not a bare URL.
+
Example conversion: source_url https://github.com/foo/bar becomes <https://github.com/foo/bar|link>
+
If any line ends with https:// you have failed - rewrite those lines before sending.
diff --git a/ai_agents/devable_research_agent/scripts/openclaw_gateway_task.xml b/ai_agents/devable_research_agent/scripts/openclaw_gateway_task.xml
new file mode 100644
index 0000000..243c909
--- /dev/null
+++ b/ai_agents/devable_research_agent/scripts/openclaw_gateway_task.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="UTF-16"?>
+<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
+ <RegistrationInfo>
+ <Description>Start OpenClaw gateway daily at 7:30am Lagos for MorningAI digest pipeline</Description>
+ <Author>DESKTOP-JGAKOUJ\HP</Author>
+ </RegistrationInfo>
+ <Triggers>
+ <CalendarTrigger>
+ <StartBoundary>2026-07-15T07:30:00</StartBoundary>
+ <Enabled>true</Enabled>
+ <ScheduleByDay>
+ <DaysInterval>1</DaysInterval>
+ </ScheduleByDay>
+ </CalendarTrigger>
+ </Triggers>
+ <Principals>
+ <Principal id="Author">
+ <UserId>DESKTOP-JGAKOUJ\HP</UserId>
+ <LogonType>InteractiveToken</LogonType>
+ <RunLevel>LeastPrivilege</RunLevel>
+ </Principal>
+ </Principals>
+ <Settings>
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
+ <AllowHardTerminate>true</AllowHardTerminate>
+ <StartWhenAvailable>true</StartWhenAvailable>
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
+ <IdleSettings>
+ <StopOnIdleEnd>false</StopOnIdleEnd>
+ <RestartOnIdle>false</RestartOnIdle>
+ </IdleSettings>
+ <AllowStartOnDemand>true</AllowStartOnDemand>
+ <Enabled>true</Enabled>
+ <Hidden>false</Hidden>
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
+ <WakeToRun>false</WakeToRun>
+ <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
+ <Priority>7</Priority>
+ </Settings>
+ <Actions Context="Author">
+ <Exec>
+ <Command>C:\Users\HP\AppData\Roaming\npm\openclaw.cmd</Command>
+ <Arguments>gateway start</Arguments>
+ <WorkingDirectory>C:\Users\HP\Documents\MorningAI</WorkingDirectory>
+ </Exec>
+ </Actions>
+</Task>
diff --git a/ai_agents/devable_research_agent/scripts/refresh_digest_input.bat b/ai_agents/devable_research_agent/scripts/refresh_digest_input.bat
index 547ae30..e98bd1e 100644
--- a/ai_agents/devable_research_agent/scripts/refresh_digest_input.bat
+++ b/ai_agents/devable_research_agent/scripts/refresh_digest_input.bat
@@ -11,8 +11,8 @@ if not exist data_today.json (
exit /b 1
)
-py -3 scripts\filter_top_items.py data_today.json digest_input_today.json --top 20
+py -3 scripts\filter_top_items.py data_today.json digest_input_today.json --top 30
if errorlevel 1 (
- python scripts\filter_top_items.py data_today.json digest_input_today.json --top 20
+ python scripts\filter_top_items.py data_today.json digest_input_today.json --top 30
)
exit /b %ERRORLEVEL%
diff --git a/ai_agents/devable_research_agent/scripts/run_pipeline.bat b/ai_agents/devable_research_agent/scripts/run_pipeline.bat
index ea6c398..f614c9b 100644
--- a/ai_agents/devable_research_agent/scripts/run_pipeline.bat
+++ b/ai_agents/devable_research_agent/scripts/run_pipeline.bat
@@ -5,6 +5,7 @@ REM AI Research Agent β€” daily data collection (Task Scheduler entry point)
REM Runs at 7:45am Lagos time; OpenClaw reads digest_input_today.json at 8am.
set "PROJECT_ROOT=%~dp0.."
+set "DEVABLE_PROJECT_ROOT=%PROJECT_ROOT%"
cd /d "%PROJECT_ROOT%" || (
echo ERROR: Could not change to project directory: %PROJECT_ROOT%
exit /b 1
diff --git a/ai_agents/devable_research_agent/scripts/run_pipeline.py b/ai_agents/devable_research_agent/scripts/run_pipeline.py
index 0972ad6..2973bbb 100644
--- a/ai_agents/devable_research_agent/scripts/run_pipeline.py
+++ b/ai_agents/devable_research_agent/scripts/run_pipeline.py
@@ -1,137 +1,488 @@
#!/usr/bin/env python3
+
"""Daily data collection pipeline for the AI Research Agent.
+
+
Runs Devable Research Agent collectors, filters top items for digest generation, and logs
+
output to logs/pipeline.log. Designed to be invoked by Windows Task Scheduler
+
at 7:45am β€” OpenClaw reads digest_input_today.json at 8am for the Slack digest.
+
"""
+
+
import argparse
+
+import json
+
+import os
+
import subprocess
+
import sys
-from datetime import datetime
+
+from datetime import datetime, timedelta, timezone
+
from pathlib import Path
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
+from typing import Optional
+
+
+
+PROJECT_ROOT = Path(
+
+ os.environ.get("DEVABLE_PROJECT_ROOT", "")
+
+).resolve() if os.environ.get("DEVABLE_PROJECT_ROOT") else Path(__file__).resolve().parent.parent
+
COLLECT_SCRIPT = PROJECT_ROOT / "skills" / "tracking-list" / "scripts" / "collect.py"
+
FILTER_SCRIPT = PROJECT_ROOT / "scripts" / "filter_top_items.py"
+
DATA_FILE = PROJECT_ROOT / "data_today.json"
+
DIGEST_FILE = PROJECT_ROOT / "digest_input_today.json"
+
LOG_FILE = PROJECT_ROOT / "logs" / "pipeline.log"
+TZ_LAGOS = timezone(timedelta(hours=1))
+
+
+
+
def _log(message: str) -> None:
+
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+ timestamp = datetime.now(TZ_LAGOS).strftime("%Y-%m-%d %H:%M:%S")
+
line = f"[{timestamp}] {message}"
+
with LOG_FILE.open("a", encoding="utf-8") as handle:
+
handle.write(line + "\n")
+
print(line)
+
+
+
def _run_step(name: str, cmd: list) -> bool:
+
_log(f"START {name}")
+
_log(f"CMD {' '.join(cmd)}")
+
try:
+
result = subprocess.run(
+
cmd,
+
cwd=PROJECT_ROOT,
+
capture_output=True,
+
text=True,
+
encoding="utf-8",
+
errors="replace",
+
+ env={**os.environ, "DEVABLE_PROJECT_ROOT": str(PROJECT_ROOT)},
+
)
+
except Exception as exc:
+
_log(f"ERROR {name} failed to launch: {exc}")
+
return False
+
+
if result.stdout:
+
for line in result.stdout.splitlines():
+
_log(f" {line}")
+
if result.stderr:
+
for line in result.stderr.splitlines():
+
_log(f" {line}")
+
+
if result.returncode != 0:
+
_log(f"ERROR {name} exited with code {result.returncode}")
+
return False
+
+
_log(f"DONE {name}")
+
+ return True
+
+
+
+
+
+def _parse_generated_at(value: str) -> Optional[datetime]:
+
+ if not value:
+
+ return None
+
+ text = value.strip()
+
+ if text.endswith("Z"):
+
+ text = text[:-1] + "+00:00"
+
+ try:
+
+ parsed = datetime.fromisoformat(text)
+
+ except ValueError:
+
+ return None
+
+ if parsed.tzinfo is None:
+
+ parsed = parsed.replace(tzinfo=timezone.utc)
+
+ return parsed
+
+
+
+
+
+def _validate_digest_input() -> bool:
+
+ """Ensure digest_input_today.json exists and is fresh (today Lagos or within 24h)."""
+
+ if not DIGEST_FILE.exists():
+
+ _log(
+
+ "ERROR digest_input_today.json missing after filter step β€” "
+
+ "OpenClaw cron will fail. Pipeline aborted."
+
+ )
+
+ return False
+
+
+
+ try:
+
+ data = json.loads(DIGEST_FILE.read_text(encoding="utf-8"))
+
+ except (json.JSONDecodeError, OSError) as exc:
+
+ _log(f"ERROR digest_input_today.json unreadable: {exc}")
+
+ return False
+
+
+
+ items = data.get("items") or []
+
+ if not items:
+
+ _log("ERROR digest_input_today.json has zero items β€” pipeline aborted.")
+
+ return False
+
+
+
+ generated_at = _parse_generated_at(data.get("generated_at", ""))
+
+ now_lagos = datetime.now(TZ_LAGOS)
+
+ today_lagos = now_lagos.date()
+
+
+
+ if generated_at is None:
+
+ _log(
+
+ "ERROR digest_input_today.json missing or invalid generated_at β€” "
+
+ "run filter_top_items.py before OpenClaw cron."
+
+ )
+
+ return False
+
+
+
+ generated_lagos = generated_at.astimezone(TZ_LAGOS)
+
+ age = now_lagos - generated_lagos
+
+ if generated_lagos.date() != today_lagos and age > timedelta(hours=24):
+
+ _log(
+
+ f"ERROR digest_input_today.json is stale "
+
+ f"(generated_at={generated_lagos.isoformat()}, age={age}) β€” pipeline aborted."
+
+ )
+
+ return False
+
+
+
return True
-def run_pipeline(date_str: str, depth: str = "default", top_n: int = 20) -> int:
+
+
+
+def _write_status_line(data_path: Path, digest_path: Path) -> None:
+
+ """Append one-line pipeline status summary to logs/pipeline.log."""
+
+ try:
+
+ data = json.loads(data_path.read_text(encoding="utf-8"))
+
+ digest = json.loads(digest_path.read_text(encoding="utf-8"))
+
+ except (json.JSONDecodeError, OSError) as exc:
+
+ _log(f"WARNING could not write status line: {exc}")
+
+ return
+
+
+
+ by_source = data.get("stats", {}).get("by_source", {})
+
+ if not by_source:
+
+ counts: dict = {}
+
+ for item in data.get("items", []):
+
+ source = item.get("source", "unknown")
+
+ counts[source] = counts.get(source, 0) + 1
+
+ source_summary = ", ".join(f"{k}={v}" for k, v in sorted(counts.items()))
+
+ else:
+
+ source_summary = ", ".join(
+
+ f"{name}={info.get('items', 0)}"
+
+ for name, info in sorted(by_source.items())
+
+ )
+
+
+
+ digest_count = len(digest.get("items", []))
+
+ categories = digest.get("stats", {}).get("by_category", {})
+
+ if not categories and digest.get("items"):
+
+ if str(FILTER_SCRIPT) not in sys.path:
+
+ sys.path.insert(0, str(PROJECT_ROOT / "scripts"))
+
+ try:
+
+ from filter_top_items import _category_counts
+
+
+
+ categories = _category_counts(digest.get("items", []))
+
+ except Exception:
+
+ categories = {}
+
+
+
+ category_summary = ", ".join(f"{k}={v}" for k, v in sorted(categories.items()))
+
+ timestamp = datetime.now(TZ_LAGOS).strftime("%Y-%m-%d %H:%M:%S")
+
+ _log(
+
+ f"STATUS {timestamp} | collected: {source_summary} | "
+
+ f"digest_items={digest_count} | categories: {category_summary}"
+
+ )
+
+
+
+
+
+def run_pipeline(date_str: str, depth: str = "default", top_n: int = 30) -> int:
+
"""Run collection and filtering. Returns process exit code."""
+
_log("=" * 60)
+
_log(f"Pipeline run started (date={date_str}, depth={depth}, top={top_n})")
+
+
if not COLLECT_SCRIPT.exists():
+
_log(f"ERROR collect script not found: {COLLECT_SCRIPT}")
+
return 1
+
if not FILTER_SCRIPT.exists():
+
_log(f"ERROR filter script not found: {FILTER_SCRIPT}")
+
return 1
+
+
collect_cmd = [
+
sys.executable,
+
str(COLLECT_SCRIPT),
+
"--date", date_str,
+
"--depth", depth,
+
"--no-cache",
+
"--output", str(DATA_FILE),
+
]
+
if not _run_step("collect", collect_cmd):
+
_log("Pipeline aborted: collection failed")
+
return 1
+
+
if not DATA_FILE.exists():
+
_log(f"ERROR expected output missing: {DATA_FILE}")
+
return 1
+
+
filter_cmd = [
+
sys.executable,
+
str(FILTER_SCRIPT),
+
str(DATA_FILE),
+
str(DIGEST_FILE),
+
"--top", str(top_n),
+
]
+
if not _run_step("filter", filter_cmd):
+
_log("Pipeline aborted: filtering failed")
+
return 1
- if not DIGEST_FILE.exists():
- _log(f"ERROR expected output missing: {DIGEST_FILE}")
+
+
+ if not _validate_digest_input():
+
return 1
+
+
data_kb = DATA_FILE.stat().st_size / 1024
+
digest_kb = DIGEST_FILE.stat().st_size / 1024
+
_log(f"Pipeline complete: {DATA_FILE.name} ({data_kb:.1f}KB), {DIGEST_FILE.name} ({digest_kb:.1f}KB)")
+
+ _write_status_line(DATA_FILE, DIGEST_FILE)
+
return 0
+
+
+
def main() -> None:
+
parser = argparse.ArgumentParser(description="Run Devable Research Agent daily collection pipeline")
+
parser.add_argument(
+
"--date",
- default=datetime.now().strftime("%Y-%m-%d"),
- help="Target collection date YYYY-MM-DD (default: today)",
+
+ default=datetime.now(TZ_LAGOS).strftime("%Y-%m-%d"),
+
+ help="Target collection date YYYY-MM-DD (default: today Lagos)",
+
)
+
parser.add_argument(
+
"--depth",
+
default="default",
+
choices=["quick", "default", "deep"],
+
help="Collector depth (default: default)",
+
)
+
parser.add_argument(
+
"--top",
+
type=int,
- default=20,
- help="Number of top items for digest input (default: 20)",
+
+ default=30,
+
+ help="Number of top items for digest input (default: 30)",
+
)
+
args = parser.parse_args()
+
+
raise SystemExit(run_pipeline(args.date, args.depth, args.top))
+
+
+
if __name__ == "__main__":
+
main()
+
diff --git a/ai_agents/devable_research_agent/scripts/start_openclaw_gateway.bat b/ai_agents/devable_research_agent/scripts/start_openclaw_gateway.bat
new file mode 100644
index 0000000..e29b351
--- /dev/null
+++ b/ai_agents/devable_research_agent/scripts/start_openclaw_gateway.bat
@@ -0,0 +1,24 @@
+@echo off
+setlocal EnableExtensions
+
+REM Start OpenClaw gateway if not already listening (scheduled at 7:30am Lagos).
+set "GATEWAY_PORT=18789"
+set "GATEWAY_CMD=%USERPROFILE%\.openclaw\gateway.cmd"
+set "LOG_DIR=%USERPROFILE%\.openclaw"
+set "LOG_FILE=%LOG_DIR%\gateway-scheduled-start.log"
+
+if not exist "%GATEWAY_CMD%" (
+ echo [%date% %time%] ERROR gateway.cmd not found: %GATEWAY_CMD%>> "%LOG_FILE%"
+ exit /b 1
+)
+
+powershell -NoProfile -Command ^
+ "try { $r = Invoke-WebRequest -Uri 'http://127.0.0.1:%GATEWAY_PORT%/' -UseBasicParsing -TimeoutSec 3; if ($r.StatusCode -ge 200 -and $r.StatusCode -lt 500) { exit 0 } } catch { exit 1 }"
+if %ERRORLEVEL%==0 (
+ echo [%date% %time%] Gateway already running on port %GATEWAY_PORT%>> "%LOG_FILE%"
+ exit /b 0
+)
+
+echo [%date% %time%] Starting OpenClaw gateway>> "%LOG_FILE%"
+start "" /MIN cmd /c ""%GATEWAY_CMD%" >> "%LOG_FILE%" 2>&1"
+exit /b 0
diff --git a/ai_agents/devable_research_agent/scripts/update_openclaw_cron.py b/ai_agents/devable_research_agent/scripts/update_openclaw_cron.py
index 361b513..3349a6d 100644
--- a/ai_agents/devable_research_agent/scripts/update_openclaw_cron.py
+++ b/ai_agents/devable_research_agent/scripts/update_openclaw_cron.py
@@ -1,11 +1,19 @@
#!/usr/bin/env python3
+
"""Update the OpenClaw AI Research Agent cron job message from the prompt file.
OpenClaw's `cron edit --message` breaks on Windows PowerShell when the prompt
-contains newlines. This script patches the same jobs.json store directly.
+contains newlines. This script patches the same jobs.json store directly when
+available, or falls back to invoking the OpenClaw CLI via Python subprocess.
+
+Delivery mode must be `none` so the agent posts via the message tool (title +
+thread). Set once with:
+ openclaw cron edit 811ed28b-8ef8-45b5-a222-cb7d7150f1e0 --no-deliver --tools read,message
"""
import json
+import os
+import subprocess
import sys
from pathlib import Path
@@ -14,17 +22,24 @@ PROMPT_FILE = Path(__file__).resolve().parent / "openclaw_digest_prompt.txt"
JOBS_FILE = Path.home() / ".openclaw" / "cron" / "jobs.json"
-def main() -> int:
- if not PROMPT_FILE.exists():
- print(f"Error: prompt file not found: {PROMPT_FILE}", file=sys.stderr)
- return 1
+def _project_root() -> Path:
+ env_root = os.environ.get("DEVABLE_PROJECT_ROOT", "").strip()
+ if env_root:
+ return Path(env_root).resolve()
+ return Path(__file__).resolve().parent.parent
+
+
+def _render_prompt() -> str:
+ template = PROMPT_FILE.read_text(encoding="utf-8")
+ root = str(_project_root()).replace("\\", "/")
+ return template.replace("{DEVABLE_PROJECT_ROOT}", root)
+
+
+def _update_via_jobs_file(prompt: str) -> bool:
if not JOBS_FILE.exists():
- print(f"Error: OpenClaw jobs file not found: {JOBS_FILE}", file=sys.stderr)
- return 1
+ return False
- prompt = PROMPT_FILE.read_text(encoding="utf-8")
data = json.loads(JOBS_FILE.read_text(encoding="utf-8"))
-
updated = False
for job in data.get("jobs", []):
if job.get("id") == JOB_ID:
@@ -33,12 +48,56 @@ def main() -> int:
break
if not updated:
- print(f"Error: cron job not found: {JOB_ID}", file=sys.stderr)
- return 1
+ print(f"Error: cron job not found in {JOBS_FILE}: {JOB_ID}", file=sys.stderr)
+ return False
JOBS_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"Updated cron job {JOB_ID} in {JOBS_FILE}")
- return 0
+ return True
+
+
+def _openclaw_node_argv() -> list[str]:
+ node = Path(os.environ.get("NODE", r"C:\Program Files\nodejs\node.exe"))
+ if not node.exists():
+ node = Path("node")
+ openclaw_js = (
+ Path.home() / "AppData" / "Roaming" / "npm" / "node_modules" / "openclaw" / "dist" / "index.js"
+ )
+ if openclaw_js.exists():
+ return [str(node), str(openclaw_js)]
+ return ["openclaw"]
+
+
+def _update_via_cli(prompt: str) -> bool:
+ result = subprocess.run(
+ [*_openclaw_node_argv(), "cron", "edit", JOB_ID, "--message", prompt],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ )
+ if result.returncode != 0:
+ print(result.stderr or result.stdout, file=sys.stderr)
+ return False
+
+ print(f"Updated cron job {JOB_ID} via openclaw CLI")
+ return True
+
+
+def main() -> int:
+ if not PROMPT_FILE.exists():
+ print(f"Error: prompt file not found: {PROMPT_FILE}", file=sys.stderr)
+ return 1
+
+ prompt = _render_prompt()
+ if _update_via_jobs_file(prompt) or _update_via_cli(prompt):
+ return 0
+
+ print(
+ "Error: could not update cron job. Ensure OpenClaw CLI is installed "
+ f"or jobs file exists at {JOBS_FILE}",
+ file=sys.stderr,
+ )
+ return 1
if __name__ == "__main__":
diff --git a/ai_agents/devable_research_agent/skills/tracking-list/scripts/collect.py b/ai_agents/devable_research_agent/skills/tracking-list/scripts/collect.py
index 45c737d..49f75fd 100644
--- a/ai_agents/devable_research_agent/skills/tracking-list/scripts/collect.py
+++ b/ai_agents/devable_research_agent/skills/tracking-list/scripts/collect.py
@@ -104,11 +104,26 @@ def collect_ainews(config: Dict[str, Any], from_date: str, to_date: str, depth:
return ainews_collector.collect(from_date, to_date, depth)
+def collect_x(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:
+ """Collect tweets via twitter-cli (search + KOL timelines)."""
+ from lib import twitter_collector
+
+ return twitter_collector.collect(
+ entities.GITHUB_SOURCES,
+ from_date,
+ to_date,
+ depth,
+ auth_token=env.get_key(config, "TWITTER_AUTH_TOKEN"),
+ ct0=env.get_key(config, "TWITTER_CT0"),
+ )
+
+
# All collectors with their names
COLLECTORS = {
"tavily": collect_tavily,
"goodailist": collect_goodailist,
"ainews": collect_ainews,
+ "x": collect_x,
"hackernews": collect_hackernews,
"github": collect_github,
"huggingface": collect_huggingface,