A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Devable Research Agent - automated AI engineering digest pipeline
Tiioluwani1ee50eb0252d
diff --git a/ai_agents/devable_research_agent/.env.example b/ai_agents/devable_research_agent/.env.examplenew file mode 100644index 0000000..aa45a1f--- /dev/null+++ b/ai_agents/devable_research_agent/.env.example@@ -0,0 +1,43 @@+# Copy to .env or ~/.config/morning-ai/.env and fill in values.++MESSAGE_ENABLED=true+ARXIV_LOOKBACK_DAYS=1++GITHUB_TOKEN=+TAVILY_API_KEY=+MISTRAL_API_KEY=+OPENAI_API_KEY=+GEMINI_API_KEY=+ANTHROPIC_API_KEY=++# Optional: image generation (skills/gen-infographic)+IMAGE_GEN_PROVIDER=+IMAGE_STYLE=+MINIMAX_API_KEY=++# Optional: social copy (skills/gen-social)+SOCIAL_ENABLED=+SOCIAL_PLATFORM=+SOCIAL_STYLE=+SOCIAL_LANG=++# Optional: email delivery (skills/gen-email)+EMAIL_ENABLED=+EMAIL_SMTP_HOST=+EMAIL_SMTP_PORT=+EMAIL_SMTP_TLS=+EMAIL_SMTP_USER=+EMAIL_SMTP_PASSWORD=+EMAIL_FROM=+EMAIL_RECIPIENTS=+EMAIL_RECIPIENTS_FILE=+EMAIL_DRY_RUN=+EMAIL_MIN_SCORE=+EMAIL_MAX_ITEMS=+EMAIL_LANG=+EMAIL_SUBJECT_TEMPLATE=+EMAIL_LIST_UNSUBSCRIBE=+EMAIL_RATE_LIMIT_DELAY=++# Optional: cache override+MORNING_AI_CACHE_DIR=diff --git a/ai_agents/devable_research_agent/.gitignore b/ai_agents/devable_research_agent/.gitignorenew file mode 100644index 0000000..1553907--- /dev/null+++ b/ai_agents/devable_research_agent/.gitignore@@ -0,0 +1,19 @@+__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+notepaddiff --git a/ai_agents/devable_research_agent/README.md b/ai_agents/devable_research_agent/README.mdnew file mode 100644index 0000000..ec82ac9--- /dev/null+++ b/ai_agents/devable_research_agent/README.md@@ -0,0 +1,238 @@+# Devable Research Agent++> Automated daily AI engineering digest that collects signals from arXiv, GitHub, HuggingFace, Good AI List, AINews, and HN then posts a curated digest to Slack via OpenClaw.++## Overview++Devable Research Agent solves the problem of staying current on AI engineering news without manually checking dozens of sources every morning. It runs a unattended 3-step pipeline on a schedule: collect raw signals, filter and rank the best items, then deliver a structured Slack digest.++The pipeline is built for builders who care about papers, repos, model drops, tools, and community signals. Output is tuned for Slack with anti-unfurl link formatting and editorial rules stored outside the repo.++**Who benefits:** AI engineers, ML platform teams, and technical leads who want a daily, curated briefing in Slack without maintaining their own scrapers.++## Features++- **Multi-source collection:** arXiv, GitHub, HuggingFace, Hacker News, Tavily web search, Good AI List, and AINews (smol.ai)+- **Smart filtering:** Category quotas, Mistral paper scoring, frequency caps, and editorial dedup against recent deliveries+- **Slack-ready digest:** OpenClaw cron reads filtered JSON plus editorial profile and posts to your channel+- **Entity-centric tracking:** 80+ curated entities across markdown registries (labs, infra, coding agents, KOLs)+- **Windows automation:** Task Scheduler entry point via batch script; OpenClaw handles delivery at a fixed time++## Tech Stack++**Core:**+- Python 3.9+ (stdlib-first collectors; optional packages for Tavily, AINews RSS, Good AI List, Mistral)+- OpenClaw (cron agent for Slack digest generation and delivery)++**Collectors & APIs:**+- arXiv API, GitHub API, HuggingFace API, Hacker News (Algolia)+- Tavily Search API (`tavily-python`)+- AINews RSS + HTML parsing (`feedparser`)+- Good AI List scraper (`playwright` + Chromium)++**Model providers:**+- **Mistral** (`mistral-small-latest`): paper relevance scoring, editorial verify step, and OpenClaw digest generation+- **Gemini** (planned): native X/Twitter collector when restored++## Prerequisites++Before you begin, ensure you have:++- Python 3.9 or higher+- [OpenClaw](https://github.com/openclaw/openclaw) installed and configured with Slack+- API keys for:+ - [ ] **Mistral** (required for filter scoring and digest)+ - [ ] **Tavily** (required for web search collector)+ - [ ] **GitHub** (optional, higher rate limits for GitHub collector)+- Optional Python packages:+ - `pip install mistralai tavily-python feedparser playwright`+ - `playwright install chromium` (for Good AI List)+- Config directory: `~/.config/morning-ai/` (env file and editorial profile)+- Basic understanding of scheduled tasks (Windows Task Scheduler) or cron on your OS++## Installation++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/devable_research_agent+```++### 2. Create Virtual Environment (Recommended)++```bash+python -m venv venv++# Windows+venv\Scripts\activate++# macOS/Linux+source venv/bin/activate+```++### 3. Install Dependencies++There is no single `requirements.txt`. Install optional packages used by collectors and the filter step:++```bash+pip install mistralai tavily-python feedparser playwright+playwright install chromium+```++### 4. Set Up Environment Variables++Copy the example env file to the global config location (recommended):++```bash+# Windows+mkdir %USERPROFILE%\.config\morning-ai+copy .env.example %USERPROFILE%\.config\morning-ai\.env++# macOS/Linux+mkdir -p ~/.config/morning-ai+cp .env.example ~/.config/morning-ai/.env+```++Edit `~/.config/morning-ai/.env` and add your keys:++```bash+TAVILY_API_KEY=tvly-your-key-here+MISTRAL_API_KEY=your-mistral-key-here+GITHUB_TOKEN=ghp_optional_for_higher_limits+```++Create your editorial rules file:++```bash+# ~/.config/morning-ai/editorial_profile.md+# Describe tone, topics to prioritize, and items to skip.+```++OpenClaw also needs `MISTRAL_API_KEY` in `~/.openclaw/.env` for digest generation.++## Usage++### How It Works (3-Step Pipeline)++```+Step 1 - Collect (7:45am)+ scripts/run_pipeline.py+ -> skills/tracking-list/scripts/collect.py+ -> data_today.json++Step 2 - Filter+ scripts/filter_top_items.py+ -> digest_input_today.json+ -> logs/delivered_items.json (frequency cap log)++Step 3 - Deliver (8:00am)+ OpenClaw cron reads digest_input_today.json+ + ~/.config/morning-ai/editorial_profile.md+ + scripts/openclaw_digest_prompt.txt+ -> Slack channel+```++### Sources Covered++| Source | Module | Notes |+|--------|--------|-------|+| arXiv | `lib/arxiv.py` | Entity-driven queries |+| GitHub | `lib/github.py` | Releases and activity; token optional |+| HuggingFace | `lib/huggingface.py` | Models and datasets |+| Hacker News | `lib/hackernews.py` | Algolia search |+| Tavily | `lib/tavily_collector.py` | Web signals; requires API key |+| Good AI List | `lib/goodailist_scraper.py` | Trending repos; Playwright |+| AINews | `lib/ainews_collector.py` | smol.ai RSS; X and Reddit sections parsed |++### Run Manually++From the project root:++```bash+# Full pipeline (collect + filter)+python scripts/run_pipeline.py++# Collect only+python skills/tracking-list/scripts/collect.py --date 2026-07-10 --depth default --no-cache --output data_today.json++# Re-filter existing data (after rule changes)+python scripts/filter_top_items.py data_today.json digest_input_today.json --top 20++# Or on Windows+scripts\run_pipeline.bat+scripts\refresh_digest_input.bat+```++Sync the OpenClaw digest prompt after editing `scripts/openclaw_digest_prompt.txt`:++```bash+python scripts/update_openclaw_cron.py+```++### Example Output++**`digest_input_today.json` (excerpt):** filtered items with title, summary, source, source_url, importance, and category labels for OpenClaw routing.++**Slack digest sections:**+- Top Papers+- Trending Repos+- What's Trending on X (AINews items with x.com URLs)+- What Happened on Reddit (AINews Reddit threads)+- New Model Drops+- New Tools++## Automation++### Windows Task Scheduler (collection + filter)++1. Schedule `scripts/run_pipeline.bat` daily at **7:45am** (adjust timezone as needed).+2. Update `PROJECT_ROOT` inside `run_pipeline.bat` to your checkout path.+3. Pipeline writes `logs/pipeline.log` for run history.++### OpenClaw Cron (Slack delivery)++1. Configure an OpenClaw cron job to run at **8:00am** (after collection finishes).+2. Job reads `digest_input_today.json` from the project root.+3. Prompt source of truth: `scripts/openclaw_digest_prompt.txt` (sync via `update_openclaw_cron.py`).+4. Model: `mistral-openai/mistral-small-latest` (OpenAI-compatible provider with `supportsStore: false` for Mistral API).++## Known Limitations++- **Reddit collector:** Not included in the minimal pipeline. AINews still surfaces high-activity Reddit threads from smol.ai issues.+- **Native X/Twitter collector:** Removed from the active collector set. X signals currently come from AINews Twitter sections. A dedicated X collector using Gemini is planned for a future release.+- **Good AI List:** Requires Playwright and Chromium. Collection fails gracefully if Playwright is not installed.+- **Hardcoded paths:** `run_pipeline.bat` may need `PROJECT_ROOT` updated for your machine. OpenClaw cron job ID in `update_openclaw_cron.py` is environment-specific.+- **Config path legacy:** Runtime config still uses `~/.config/morning-ai/` from the upstream MorningAI fork.++## Project Structure++```+devable_research_agent/+├── scripts/+│ ├── run_pipeline.py # Orchestrator (collect + filter)+│ ├── run_pipeline.bat # Task Scheduler entry+│ ├── refresh_digest_input.bat # Re-filter only+│ ├── filter_top_items.py # Scoring, quotas, digest input+│ ├── openclaw_digest_prompt.txt+│ └── update_openclaw_cron.py+├── skills/tracking-list/scripts/+│ └── collect.py # Step 1 collector orchestrator+├── lib/ # Collectors, scoring, dedupe, entities+├── entities/ # Tracked entity registries (*.md)+├── logs/+│ └── .gitkeep+├── .env.example+├── .gitignore+└── README.md+```++## How It Works++**Collection:** `collect.py` runs seven collectors concurrently, then classifies, scores, deduplicates, and cross-links items into `data_today.json`.++**Filtering:** `filter_top_items.py` applies date cutoffs, maintenance filters, Mistral paper scoring, category quotas (papers, repos, web, X via AINews, HN), and a Mistral editorial verify pass against `logs/delivered_items.json`. Output is a smaller JSON file for OpenClaw.++**Delivery:** OpenClaw applies `editorial_profile.md` and section routing rules from the prompt file, then posts the formatted digest to Slack with `<url|link>` syntax to avoid unfurl cards.++[Back to Top](#devable-research-agent)diff --git a/ai_agents/devable_research_agent/entities/ai-apps.md b/ai_agents/devable_research_agent/entities/ai-apps.mdnew file mode 100644index 0000000..2f5ebfb--- /dev/null+++ b/ai_agents/devable_research_agent/entities/ai-apps.md@@ -0,0 +1,74 @@+# AI Apps & Platform Entity Registry++Entity registry for AI app-building platforms and consumer AI products.+++---++## Assigned Entity List++### 1. v0 (Vercel)++| Attribute | Info |+|------|------|+| **X Official Account** | [@v0](https://x.com/v0) |+| **Key People** | [@rauchg](https://x.com/rauchg) - Guillermo Rauch, Vercel CEO |+| **Vercel Changelog** | https://vercel.com/changelog |++### 2. bolt.new++| Attribute | Info |+|------|------|+| **X Official Account** | [@boltdotnew](https://x.com/boltdotnew) |+| **Key People** | [@EricSimons](https://x.com/EricSimons) - Eric Simons, StackBlitz CEO |+| **Release Notes** | https://support.bolt.new/release-notes |++### 3. Lovable++| Attribute | Info |+|------|------|+| **X Official Account** | [@Lovable](https://x.com/Lovable) |+| **Key People** | [@antonosika](https://x.com/antonosika) - Anton Osika, CEO |+| **Changelog** | https://lovable.dev/changelog |++### 4. Replit++| Attribute | Info |+|------|------|+| **X Official Account** | [@Replit](https://x.com/Replit) |+| **Key People** | [@amasad](https://x.com/amasad) - Amjad Masad, CEO |+| **Changelog** | https://docs.replit.com/updates |++### 5. Lovart++| Attribute | Info |+|------|------|+| **X Official Account** | [@lovart_ai](https://x.com/lovart_ai) |+| **Key People** | Elena Leung, COO |+| **Changelog** | https://www.lovart.ai/changelog |++### 6. Manus++| Attribute | Info |+|------|------|+| **X Official Account** | [@ManusAI](https://x.com/ManusAI) |+| **Key People** | [@Red_Xiao_](https://x.com/Red_Xiao_) - Red Xiao, CEO |++### 7. Genspark++| Attribute | Info |+|------|------|+| **X Official Account** | [@genspark_ai](https://x.com/genspark_ai) |+| **Key People** | [@ericjing_ai](https://x.com/ericjing_ai) - Eric Jing, CEO |+| **Changelog** | https://www.genspark.ai/docs/ai_slides_changelog |++### 8. Character.ai++| Attribute | Info |+|------|------|+| **X Official Account** | [@character_ai](https://x.com/character_ai) |+| **Official Website** | https://character.ai |+| **Reddit Community** | [r/CharacterAI](https://www.reddit.com/r/CharacterAI/) |++---+diff --git a/ai_agents/devable_research_agent/entities/ai-labs.md b/ai_agents/devable_research_agent/entities/ai-labs.mdnew file mode 100644index 0000000..245a6c5--- /dev/null+++ b/ai_agents/devable_research_agent/entities/ai-labs.md@@ -0,0 +1,246 @@+# AI Labs Entity Registry++Entity registry for major AI labs worldwide, including model releases, product updates, visual models, and academic research.++---++## Assigned Entity List++### Frontier Labs++#### 1. OpenAI (Full Line)++| Attribute | Info |+|------|------|+| **X Official Account** | [@OpenAI](https://x.com/OpenAI), [@ChatGPTapp](https://x.com/ChatGPTapp) |+| **Key People** | [@sama](https://x.com/sama) - Sam Altman, CEO<br>[@markchen90](https://x.com/markchen90) - Mark Chen, SVP Research<br>[@gdb](https://x.com/gdb) - Greg Brockman, Co-founder<br>[@nickturley](https://x.com/nickturley) - Nick Turley, ChatGPT Product Lead |+| **Official Blog** | https://openai.com/blog |+| **Research** | https://openai.com/research |+| **API Changelog** | https://platform.openai.com/docs/changelog |+| **ChatGPT Release Notes** | https://help.openai.com/en/articles/6825453-chatgpt-release-notes |+| **Sora Page** | https://openai.com/sora |+| **GitHub** | https://github.com/openai |+| **arXiv** | https://arxiv.org/search/?query=OpenAI |+| **Covered Products** | GPT series models, ChatGPT product, DALL-E, Sora, Codex CLI |+| **Reddit Keywords** | OpenAI, ChatGPT, GPT-5 |+| **Reddit Community** | [r/OpenAI](https://www.reddit.com/r/OpenAI/), [r/ChatGPT](https://www.reddit.com/r/ChatGPT/) |+| **HN Keywords** | OpenAI |++#### 2. Anthropic (Full Line)++| Attribute | Info |+|------|------|+| **X Official Account** | [@AnthropicAI](https://x.com/AnthropicAI), [@claudeai](https://x.com/claudeai), [@claude_code](https://x.com/claude_code) |+| **Key People** | [@DarioAmodei](https://x.com/DarioAmodei) - Dario Amodei, CEO<br>[@alexalbert__](https://x.com/alexalbert__) - Alex Albert, Claude Relations<br>[@bcherny](https://x.com/bcherny) - Boris Cherny, Claude Code core<br>[@trq212](https://x.com/trq212) - Thariq, Claude Code core |+| **Official Blog** | https://www.anthropic.com/news |+| **Research** | https://www.anthropic.com/research |+| **Release Notes** | https://docs.anthropic.com/en/release-notes/overview, https://support.claude.com/en/articles/12138966-release-notes |+| **Claude Code Changelog** | https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md |+| **NPM Package** | https://www.npmjs.com/package/@anthropic-ai/claude-code |+| **GitHub** | https://github.com/anthropics |+| **arXiv** | https://arxiv.org/search/?query=Anthropic |+| **Covered Products** | Claude series models, Claude Code, Claude Desktop/Web |+| **Reddit Keywords** | Anthropic, Claude |+| **Reddit Community** | [r/ClaudeAI](https://www.reddit.com/r/ClaudeAI/) |+| **HN Keywords** | Anthropic, Claude |++#### 3. Google (Full Line)++| Attribute | Info |+|------|------|+| **X Official Account** | [@GoogleDeepMind](https://x.com/GoogleDeepMind), [@GoogleAI](https://x.com/GoogleAI), [@GoogleAIStudio](https://x.com/GoogleAIStudio), [@googleaidevs](https://x.com/googleaidevs), [@GeminiApp](https://x.com/GeminiApp) |+| **Key People** | [@JeffDean](https://x.com/JeffDean) - Jeff Dean, Chief Scientist<br>[@demishassabis](https://x.com/demishassabis) - Demis Hassabis, DeepMind CEO<br>[@OfficialLoganK](https://x.com/OfficialLoganK) - Logan Kilpatrick, Product Lead |+| **DeepMind Blog** | https://deepmind.google/discover/blog |+| **Research Blog** | https://research.google/blog |+| **Publications** | https://deepmind.google/research/publications |+| **Gemini API Changelog** | https://ai.google.dev/gemini-api/docs/changelog |+| **Gemini Release Notes** | https://gemini.google/release-notes/ |+| **Gemini Updates Blog** | https://blog.google/products/gemini/ |+| **Antigravity Changelog** | https://antigravity.google/changelog |+| **Developer Blog** | https://developers.googleblog.com |+| **GitHub** | https://github.com/google-deepmind |+| **HuggingFace** | https://huggingface.co/google |+| **arXiv** | https://arxiv.org/search/?query=DeepMind |+| **Covered Products** | Gemini series models, Gemini App, AI Studio, Antigravity, Veo |+| **Reddit Keywords** | Gemini, DeepMind |+| **Reddit Community** | [r/Gemini](https://www.reddit.com/r/Gemini/), [r/GoogleGeminiAI](https://www.reddit.com/r/GoogleGeminiAI/) |+| **HN Keywords** | Gemini, DeepMind |++#### 4. Meta AI (Full Line)++| Attribute | Info |+|------|------|+| **X Official Account** | [@AIatMeta](https://x.com/AIatMeta) |+| **Key People** | [@ylecun](https://x.com/ylecun) - Yann LeCun, Chief AI Scientist |+| **Official Blog** | https://ai.meta.com/blog |+| **GitHub** | https://github.com/meta-llama |+| **HuggingFace** | https://huggingface.co/meta-llama |+| **arXiv** | https://arxiv.org/search/?query=Meta+AI+FAIR |+| **Covered Products** | Llama series models, Meta AI Studio |+| **Reddit Keywords** | Llama, Meta AI |+| **Reddit Community** | [r/LocalLLaMA](https://www.reddit.com/r/LocalLLaMA/) |+| **HN Keywords** | Llama, Meta AI |++#### 5. xAI (Full Line)++| Attribute | Info |+|------|------|+| **X Official Account** | [@xai](https://x.com/xai) |+| **Key People** | [@elonmusk](https://x.com/elonmusk) - Elon Musk, Founder |+| **Official Blog** | https://x.ai/blog |+| **GitHub** | https://github.com/xai-org |+| **HuggingFace** | https://huggingface.co/xai-org |+| **Covered Products** | Grok series models |+| **Reddit Keywords** | Grok, xAI |+| **Reddit Community** | [r/Grok](https://www.reddit.com/r/Grok/) |++#### 6. Microsoft (Full Line)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Microsoft](https://x.com/Microsoft), [@MSFTCopilot](https://x.com/MSFTCopilot), [@OpenAtMicrosoft](https://x.com/OpenAtMicrosoft) |+| **AI Blog** | https://blogs.microsoft.com/ai/, https://www.microsoft.com/en-us/ai/blog |+| **GitHub** | https://github.com/microsoft |+| **HuggingFace** | https://huggingface.co/microsoft |+| **arXiv** | https://arxiv.org/search/?query=Microsoft+AI |+| **Covered Products** | Copilot, Phi series models, Azure OpenAI, GitHub Copilot |+| **Reddit Keywords** | Copilot, Phi model |+| **Reddit Community** | [r/MicrosoftCopilot](https://www.reddit.com/r/MicrosoftCopilot/) |+| **HN Keywords** | Copilot, Microsoft AI |++### China AI Labs++#### 7. Alibaba (Qwen)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Alibaba_Qwen](https://x.com/Alibaba_Qwen) |+| **Official Blog** | https://qwenlm.github.io/blog |+| **GitHub** | https://github.com/QwenLM |+| **HuggingFace** | https://huggingface.co/Qwen |+| **arXiv** | https://arxiv.org/search/?query=Qwen |+| **Reddit Keywords** | Qwen |+| **Reddit Community** | [r/Qwen_AI](https://www.reddit.com/r/Qwen_AI/) |++#### 8. DeepSeek++| Attribute | Info |+|------|------|+| **X Official Account** | [@deepseek_ai](https://x.com/deepseek_ai) |+| **Official Website** | https://www.deepseek.com |+| **Changelog** | https://api-docs.deepseek.com/updates |+| **GitHub** | https://github.com/deepseek-ai |+| **HuggingFace** | https://huggingface.co/deepseek-ai |+| **arXiv** | https://arxiv.org/search/?query=DeepSeek |+| **Reddit Keywords** | DeepSeek |+| **Reddit Community** | [r/DeepSeek](https://www.reddit.com/r/DeepSeek/) |+| **HN Keywords** | DeepSeek |++#### 9. ByteDance (Doubao)++| Attribute | Info |+|------|------|+| **X Official Account** | [@doubaoAi](https://x.com/doubaoAi) |+| **Volcengine** | https://www.volcengine.com/product/doubao |+| **GitHub** | https://github.com/bytedance |+| **HuggingFace** | https://huggingface.co/bytedance |+| **Covered Products** | Doubao, Coze |++#### 10. Zhipu AI (GLM)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Zai_org](https://x.com/Zai_org) |+| **Official Website** | https://www.zhipuai.cn |+| **Changelog** | https://docs.bigmodel.cn/cn/update/new-releases |+| **GitHub** | https://github.com/THUDM |+| **HuggingFace** | https://huggingface.co/THUDM |+| **arXiv** | https://arxiv.org/search/?query=GLM |++#### 11. Moonshot AI (Kimi)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Kimi_Moonshot](https://x.com/Kimi_Moonshot) |+| **Official Website** | https://www.moonshot.cn |+| **Changelog** | https://platform.moonshot.cn/blog/posts/changelog |+| **Kimi Product** | https://kimi.ai |+| **GitHub** | https://github.com/MoonshotAI |++#### 12. MiniMax / Hailuo++| Attribute | Info |+|------|------|+| **X Official Account** | [@MiniMax_AI](https://x.com/MiniMax_AI), [@MiniMaxAI](https://x.com/MiniMaxAI) |+| **Changelog** | https://platform.minimaxi.com/docs/release-notes/models |+| **GitHub** | https://github.com/MiniMax-AI |+| **HuggingFace** | https://huggingface.co/MiniMaxAI |+| **Hailuo Product** | https://hailuoai.com |+| **Covered Products** | MiniMax Models, Hailuo Video |+| **Reddit Keywords** | MiniMax, Hailuo |+| **Reddit Community** | [r/HailuoAiOfficial](https://www.reddit.com/r/HailuoAiOfficial/) |++#### 13. Kuaishou (Kling)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Kling_ai](https://x.com/Kling_ai), [@AiKling](https://x.com/AiKling) |+| **Official Website** | https://klingai.com |++#### 14. Shanghai AI Lab (InternLM)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Shanghai_AI_Lab](https://x.com/Shanghai_AI_Lab) |+| **GitHub** | https://github.com/InternLM |+| **HuggingFace** | https://huggingface.co/internlm |+| **arXiv** | arXiv InternLM/InternVL related papers |++#### 15. Meituan (LongCat)++| Attribute | Info |+|------|------|+| **X Official Account** | [@Meituan_LongCat](https://x.com/Meituan_LongCat) |+| **Tech Blog** | https://tech.meituan.com/tags/longcat.html |+| **GitHub** | https://github.com/orgs/meituan-longcat/repositories |+| **HuggingFace** | https://huggingface.co/meituan-longcat |++#### 16. 01.AI (Yi Series)++| Attribute | Info |+|------|------|+| **X Official Account** | [@01ai_yi](https://x.com/01ai_yi) |+| **GitHub** | https://github.com/01-ai |+| **HuggingFace** | https://huggingface.co/01-ai |++#### 17. Baichuan AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@Baichuan_AI](https://x.com/Baichuan_AI) |+| **GitHub** | https://github.com/baichuan-inc |+| **HuggingFace** | https://huggingface.co/baichuan-inc |++#### 18. StepFun++| Attribute | Info |+|------|------|+| **X Official Account** | [@StepFunAI](https://x.com/StepFunAI) |+| **Official Website** | https://www.stepfun.com |++#### 19. Tencent Hunyuan++| Attribute | Info |+|------|------|+| **X Official Account** | [@TencentHunyuan](https://x.com/TencentHunyuan), [@TXhunyuan](https://x.com/TXhunyuan) |+| **Official Website** | https://hunyuan.tencent.com |+| **Research** | https://hunyuan.tencent.com/research |+| **GitHub** | https://github.com/Tencent-Hunyuan |+| **HuggingFace** | https://huggingface.co/tencent, https://huggingface.co/Tencent-Hunyuan |+| **arXiv** | https://arxiv.org/search/?query=Tencent+Hunyuan |+| **Covered Products** | Hunyuan LLM, HunyuanVideo, HunyuanImage |+| **Reddit Keywords** | Hunyuan, Tencent AI |+++---+diff --git a/ai_agents/devable_research_agent/entities/benchmarks-academic.md b/ai_agents/devable_research_agent/entities/benchmarks-academic.mdnew file mode 100644index 0000000..a9b1d72--- /dev/null+++ b/ai_agents/devable_research_agent/entities/benchmarks-academic.md@@ -0,0 +1,75 @@+# Benchmarks & Academic Entity Registry++Entity registry for benchmark organizations, academic research channels, and industry media.+++---++## Assigned Entity List++### Benchmark Organizations++| Name | X Account | Website | Modality | Description |+|------|--------|------|------|------|+| LMArena | [@arena](https://x.com/arena) | - | Text, Vision | Model battle ranking |+| Artificial Analysis | [@ArtificialAnlys](https://x.com/ArtificialAnlys) | https://artificialanalysis.ai | Text, Image, Video, Audio | Model speed/quality comparison |+| HuggingFace Open LLM | [@huggingface](https://x.com/huggingface) | https://huggingface.co/spaces/open-llm-leaderboard | Text | Open-source model leaderboard |+| Scale AI SEAL | [@scale_AI](https://x.com/scale_AI) | https://scale.com/leaderboard | Text | Scale Benchmark |+| LMSYS Chatbot Arena | [@laboramsys](https://x.com/laboramsys) | https://lmsys.org | Text, Vision | Chatbot Arena / VLM Arena |+| OpenCompass | - | https://opencompass.org.cn | Text, Multimodal | Multimodal benchmark |+| LiveBench | - | https://livebench.ai | Text | Real-time benchmark |+| WildBench | - | https://huggingface.co/spaces/allenai/WildBench | Text | Allen AI Benchmark |+| Terminal-Bench | - | https://www.tbench.ai | Code | Terminal agent benchmark |+| Vals AI | [@ValsAI](https://x.com/ValsAI) | https://www.vals.ai | Text | Domain-specific benchmark (law, finance, code) |+| Design Arena | [@Designarena](https://x.com/Designarena) | https://www.designarena.ai/leaderboard | Code, Image, Video | Crowdsourced AI design benchmark |+| Vending-Bench | [@andonlabs](https://x.com/andonlabs) | https://andonlabs.com/evals/vending-bench | Text | Long-term agent coherence benchmark |+| SimpleBench | [@AIExplainedYT](https://x.com/AIExplainedYT) | https://simple-bench.com | Text | Commonsense reasoning benchmark |+| Repo Bench | [@RepoPrompt](https://x.com/RepoPrompt) | https://repoprompt.com/bench | Code | Large context file editing benchmark |++### Additional Benchmark Sources++| Name | X Account | Description |+|------|--------|------|+| HuggingFace | [@huggingface](https://x.com/huggingface) | Model releases, trends |+| Replicate | [@replicate](https://x.com/replicate) | Model deployment, trends |++### Paper Channels++| Name | URL | Type |+|------|-----|------|+| Papers with Code | https://paperswithcode.com | Papers + Code |+| HuggingFace Papers | https://huggingface.co/papers | Daily trending papers |+| arXiv cs.LG | https://arxiv.org/list/cs.LG/recent | Machine Learning |+| arXiv cs.CL | https://arxiv.org/list/cs.CL/recent | Natural Language Processing |+| arXiv cs.CV | https://arxiv.org/list/cs.CV/recent | Computer Vision |++### Community Discussions++| Name | URL | Type |+|------|-----|------|+| Reddit r/MachineLearning | https://reddit.com/r/MachineLearning | ML academic discussion |+| Reddit r/LocalLLaMA | https://reddit.com/r/LocalLLaMA | Open-source LLM community |+| Reddit r/artificial | https://reddit.com/r/artificial | AI general discussion |+| Reddit r/singularity | https://reddit.com/r/singularity | AI frontier discussion |++### Industry Media (for lead discovery only, must trace to source)++| Name | URL |+|------|-----|+| VentureBeat AI | https://venturebeat.com/ai |+| The Decoder | https://the-decoder.com |+| Ars Technica AI | https://arstechnica.com/ai |+| TechCrunch AI | https://techcrunch.com/category/artificial-intelligence/ |++---++## Deduplication Notes++This Agent focuses on **cross-vendor** benchmarks/papers/trends. The following content is covered by other Agents, this Agent skips:++- Specific vendor model/product updates -> covered by corresponding vendor Agent+- Vendor-specific technical papers -> if papers are from OpenAI/Anthropic etc., covered by ai-labs etc. Agent+- This Agent only focuses on: independent benchmark results, cross-vendor comparisons, general academic research, open-source community updates, industry trends++---+diff --git a/ai_agents/devable_research_agent/entities/coding-agent.md b/ai_agents/devable_research_agent/entities/coding-agent.mdnew file mode 100644index 0000000..9c4b0c7--- /dev/null+++ b/ai_agents/devable_research_agent/entities/coding-agent.md@@ -0,0 +1,115 @@+# Coding Agent Entity Registry++Entity registry for AI coding agents and developer assistant platforms (agents under major labs such as Claude Code, Codex CLI, GitHub Copilot are handled by the ai-labs group).++---++## Assigned Entity List++### 1. Cursor++| Attribute | Info |+|------|------|+| **X Official Account** | [@cursor_ai](https://x.com/cursor_ai) |+| **Key People** | [@mntruell](https://x.com/mntruell) - Michael Truell, CEO |+| **Changelog** | https://cursor.com/changelog |+| **Reddit Keywords** | Cursor AI |+| **Reddit Community** | [r/cursor](https://www.reddit.com/r/cursor/) |+| **HN Keywords** | Cursor |++### 2. Cline++| Attribute | Info |+|------|------|+| **X Official Account** | [@cline](https://x.com/cline) |+| **Key People** | [@sdrzn](https://x.com/sdrzn) - Saoud Rizwan, CEO<br>[@nickbaumann_](https://x.com/nickbaumann_) - Nick Baumann |+| **GitHub Releases** | https://github.com/cline/cline/releases |+| **Reddit Keywords** | Cline AI |+| **Reddit Community** | [r/ClineAI](https://www.reddit.com/r/ClineAI/) |++### 3. OpenCode++| Attribute | Info |+|------|------|+| **Key People** | [@thdxr](https://x.com/thdxr) - Dax Raad, Founder |+| **GitHub Releases** | https://github.com/sst/opencode/releases |++### 4. Droid (Factory AI)++| Attribute | Info |+|------|------|+| **X Official Account** | [@FactoryAI](https://x.com/FactoryAI) |+| **CLI Changelog** | https://docs.factory.ai/changelog/cli-updates |++### 5. OpenClaw (formerly Clawd/Moltbot)++| Attribute | Info |+|------|------|+| **X Official Account** | [@openclaw](https://x.com/openclaw) |+| **Key People** | [@steipete](https://x.com/steipete) - Peter Steinberger, Founder |+| **Official Website** | https://openclaw.ai |+| **Docs** | https://docs.openclaw.ai |+| **Blog** | https://openclaws.io/blog |+| **Changelog** | https://openclawai.io/changelog |+| **GitHub** | https://github.com/openclaw/openclaw |+| **GitHub Releases** | https://github.com/openclaw/openclaw/releases |+| **Reddit Keywords** | OpenClaw |+| **Reddit Community** | [r/OpenClaw](https://www.reddit.com/r/OpenClaw/) |++### 6. Windsurf (Codeium)++| Attribute | Info |+|------|------|+| **X Official Account** | [@windsurf](https://x.com/windsurf) |+| **Official Blog** | https://windsurf.com/blog |+| **Changelog** | https://windsurf.com/changelog |+| **Reddit Keywords** | Windsurf, Codeium |+| **Reddit Community** | [r/Windsurf](https://www.reddit.com/r/Windsurf/) |++### 7. Augment Code++| Attribute | Info |+|------|------|+| **X Official Account** | [@AugmentCode](https://x.com/AugmentCode) |+| **Official Blog** | https://www.augmentcode.com/blog |++### 8. Aider++| Attribute | Info |+|------|------|+| **Key People** | Paul Gauthier, Creator |+| **Official Website** | https://aider.chat |+| **GitHub** | https://github.com/Aider-AI/aider |+| **GitHub Releases** | https://github.com/Aider-AI/aider/releases |++### 9. Devin (Cognition)++| Attribute | Info |+|------|------|+| **X Official Account** | [@cognition](https://x.com/cognition) |+| **Official Blog** | https://cognition.ai/blog |+| **Reddit Keywords** | Devin AI |+| **Reddit Community** | [r/DevinAI](https://www.reddit.com/r/DevinAI/) |++### 10. browser-use++| Attribute | Info |+|------|------|+| **X Official Account** | [@browser_use](https://x.com/browser_use) |+| **Key People** | [@gregpr07](https://x.com/gregpr07) |+| **Official Website** | https://browser-use.com |+| **Changelog** | https://browser-use.com/changelog |+| **GitHub** | https://github.com/browser-use/browser-use |+| **GitHub Releases** | https://github.com/browser-use/browser-use/releases |++### 11. Hermes Agent (Nous Research)++| Attribute | Info |+|------|------|+| **X Official Account** | [@NousResearch](https://x.com/NousResearch) |+| **Official Website** | https://hermes-agent.nousresearch.com |+| **Docs** | https://hermes-agent.nousresearch.com/docs |+| **GitHub** | https://github.com/NousResearch/hermes-agent |++---+diff --git a/ai_agents/devable_research_agent/entities/custom/ai-engineering-watchlist.md b/ai_agents/devable_research_agent/entities/custom/ai-engineering-watchlist.mdnew file mode 100644index 0000000..85e294a--- /dev/null+++ b/ai_agents/devable_research_agent/entities/custom/ai-engineering-watchlist.md@@ -0,0 +1,200 @@+\# AI Engineering Custom Watchlist++++\## LangChain++| Platform | Value |++|----------|-------|++| X | @LangChainAI |++| GitHub | langchain-ai/langchain |++| HuggingFace | langchain-ai |++| Reddit | LangChain |++| Reddit Community | r/LangChain |++| HN | LangChain |++++\## LlamaIndex++| Platform | Value |++|----------|-------|++| X | @llama\_index |++| GitHub | run-llama/llama\_index |++| HuggingFace | llamaindex |++| Reddit | LlamaIndex |++| HN | LlamaIndex |++++\## LangGraph++| Platform | Value |++|----------|-------|++| X | @LangChainAI |++| GitHub | langchain-ai/langgraph |++| HN | LangGraph |++++\## CrewAI++| Platform | Value |++|----------|-------|++| X | @crewAIInc |++| GitHub | crewAIInc/crewAI |++| Reddit | crewAI |++| HN | CrewAI |++++\## AutoGen++| Platform | Value |++|----------|-------|++| X | @pyautogen |++| GitHub | microsoft/autogen |++| HuggingFace | microsoft |++| Reddit | AutoGen |++| HN | AutoGen |++++\## Mastra++| Platform | Value |++|----------|-------|++| X | @mastraai |++| GitHub | mastra-ai/mastra |++| HN | Mastra |++++\## Haystack++| Platform | Value |++|----------|-------|++| X | @deepset\_ai |++| GitHub | deepset-ai/haystack |++| HuggingFace | deepset |++| Reddit | Haystack |++| HN | Haystack |++++\## Ollama++| Platform | Value |++|----------|-------|++| X | @ollama |++| GitHub | ollama/ollama |++| Reddit | ollama |++| Reddit Community | r/ollama |++| HN | Ollama |++++\## LiteLLM++| Platform | Value |++|----------|-------|++| X | @BerriAI |++| GitHub | BerriAI/litellm |++| HN | LiteLLM |++++\## Hugging Face TGI++| Platform | Value |++|----------|-------|++| X | @huggingface |++| GitHub | huggingface/text-generation-inference |++| HN | TGI |++++\## Llamafile++| Platform | Value |++|----------|-------|++| X | @justinefm |++| GitHub | Mozilla-Ocho/llamafile |++| HN | llamafile |++++## AI Engineering Reddit Communities++| Platform | Value |+|----------|-------|+| Reddit Community | r/LocalLLaMA, r/MachineLearning, r/artificial, r/singularity, r/OpenSourceAI |++## AlphaXiv++| Platform | Value |+|----------|-------|+| X | @askalphaxiv |++## HuggingFace Papers++| Platform | Value |+|----------|-------|+| X | @HuggingPapers |+diff --git a/ai_agents/devable_research_agent/entities/kol.md b/ai_agents/devable_research_agent/entities/kol.mdnew file mode 100644index 0000000..cdd98d2--- /dev/null+++ b/ai_agents/devable_research_agent/entities/kol.md@@ -0,0 +1,39 @@+# Key Opinion Leaders (KOL) Entity Registry++Entity registry for AI industry key opinion leaders and influential voices.+++---++## Assigned Entity List++### Key Opinion Leaders (KOL)++| Name | X Account | Description |+|------|--------|------|+| Andrej Karpathy | [@karpathy](https://x.com/karpathy) | Former Tesla AI / OpenAI founding member |+| AK (Paper digest) | [@_akhaliq](https://x.com/_akhaliq) | Real-time AI paper releases, HuggingFace member |+| Andrew Ng | [@AndrewYNg](https://x.com/AndrewYNg) | AI pioneer |+| Rowan Cheung | [@rowancheung](https://x.com/rowancheung) | The Rundown AI Founder |+| Ben Tossell | [@bentossell](https://x.com/bentossell) | Ben's Bites Founder |+| Elie Bakouch | [@eliebakouch](https://x.com/eliebakouch) | AI news blogger |+| Swyx | [@swyx](https://x.com/swyx) | Latent Space Host, AI engineering advocate |+| Simon Willison | [@simonw](https://x.com/simonw) | Django Co-creator, in-depth AI tool reviews |+| François Chollet | [@fchollet](https://x.com/fchollet) | Keras creator, ARC-AGI initiator, intelligence & benchmark research |+| DAIR.AI | [@dair_ai](https://x.com/dair_ai) | Weekly ML/AI paper threads and accessible research explainers |+| Lilian Weng | [@lilianweng](https://x.com/lilianweng) | Ex-OpenAI, Lil'Log in-depth LLM research breakdowns |+| Riley Goodside | [@goodside](https://x.com/goodside) | LLM evaluation, prompting research, real capabilities testing |++> **Note**: KOL information must be traced back to official channels for confirmation, cannot be used directly as a primary source++---++## Deduplication Notes++This entity group tracks **individual opinion leaders**. The following content is covered by other entities, this group skips:++- Official company announcements -> covered by corresponding vendor entity+- Benchmark results/papers -> covered by benchmarks-academic entity+- This group only focuses on: KOL commentary, trend analysis, independent reviews, community discussions initiated by KOLs++---diff --git a/ai_agents/devable_research_agent/entities/model-infra.md b/ai_agents/devable_research_agent/entities/model-infra.mdnew file mode 100644index 0000000..df851da--- /dev/null+++ b/ai_agents/devable_research_agent/entities/model-infra.md@@ -0,0 +1,100 @@+# Model & Infrastructure Entity Registry++Entity registry for model providers and inference infrastructure platforms.+++---++## Assigned Entity List++### 1. NVIDIA++| Attribute | Info |+|------|------|+| **X Official Account** | [@nvidia](https://x.com/nvidia), [@NVIDIAAIDev](https://x.com/NVIDIAAIDev) |+| **Key People** | [@DrJimFan](https://x.com/DrJimFan) - Jim Fan, Robotics Director |+| **Official Blog** | https://blogs.nvidia.com |+| **GitHub** | https://github.com/NVIDIA |+| **HuggingFace** | https://huggingface.co/nvidia |+| **arXiv** | https://arxiv.org/search/?query=NVIDIA+AI |+| **Reddit Keywords** | NVIDIA AI, CUDA |+| **Reddit Community** | [r/nvidia](https://www.reddit.com/r/nvidia/) |++### 2. Mistral AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@MistralAI](https://x.com/MistralAI) |+| **Key People** | [@arthurmensch](https://x.com/arthurmensch) - Arthur Mensch, CEO |+| **Official Blog** | https://mistral.ai/news |+| **Changelog** | https://docs.mistral.ai/getting-started/changelog |+| **GitHub** | https://github.com/mistralai |+| **HuggingFace** | https://huggingface.co/mistralai |+| **arXiv** | https://arxiv.org/search/?query=Mistral+AI |+| **Reddit Keywords** | Mistral |+| **Reddit Community** | [r/MistralAI](https://www.reddit.com/r/MistralAI/) |+| **HN Keywords** | Mistral |++### 3. Cohere++| Attribute | Info |+|------|------|+| **X Official Account** | [@cohere](https://x.com/cohere) |+| **Official Blog** | https://cohere.com/blog |+| **GitHub** | https://github.com/cohere-ai |+| **HuggingFace** | https://huggingface.co/CohereForAI |+| **Reddit Keywords** | Cohere, Command R |+| **Reddit Community** | [r/CohereAI](https://www.reddit.com/r/CohereAI/) |++### 4. Perplexity AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@perplexity_ai](https://x.com/perplexity_ai) |+| **Key People** | [@AravSrinivas](https://x.com/AravSrinivas) - Aravind Srinivas, CEO |+| **Official Blog** | https://www.perplexity.ai/hub/blog |+| **Reddit Keywords** | Perplexity |+| **Reddit Community** | [r/perplexity_ai](https://www.reddit.com/r/perplexity_ai/) |+| **HN Keywords** | Perplexity |++### 5. Amazon/AWS (AI)++| Attribute | Info |+|------|------|+| **X Official Account** | [@awscloud](https://x.com/awscloud) |+| **AI Blog** | https://aws.amazon.com/blogs/machine-learning/ |+| **Bedrock** | https://aws.amazon.com/bedrock/ |++### 6. Together AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@togethercomputer](https://x.com/togethercomputer) |+| **Official Blog** | https://together.ai/blog |+| **GitHub** | https://github.com/togethercomputer |++### 7. Groq++| Attribute | Info |+|------|------|+| **X Official Account** | [@GroqInc](https://x.com/GroqInc) |+| **Official Blog** | https://wow.groq.com/blog/ |++### 8. Apple (MLX/AI)++| Attribute | Info |+|------|------|+| **ML Research Blog** | https://machinelearning.apple.com |+| **GitHub (MLX)** | https://github.com/ml-explore |+| **HuggingFace** | https://huggingface.co/apple |++### Inference Frameworks++| Name | X Account | GitHub | Description |+|------|--------|--------|------|+| vLLM | [@vllm_project](https://x.com/vllm_project) | https://github.com/vllm-project/vllm | High-throughput LLM inference engine |+| SGLang | [@sgl_project](https://x.com/sgl_project) | https://github.com/sgl-project/sglang | High-performance LLM/VLM serving framework |+| KTransformers | - | https://github.com/kvcache-ai/ktransformers | Heterogeneous CPU/GPU inference framework |++---+diff --git a/ai_agents/devable_research_agent/entities/vision-media.md b/ai_agents/devable_research_agent/entities/vision-media.mdnew file mode 100644index 0000000..2ba4a2e--- /dev/null+++ b/ai_agents/devable_research_agent/entities/vision-media.md@@ -0,0 +1,119 @@+# Vision & Media Entity Registry++Entity registry for independent visual/audio/video generation vendors (major lab vision models like Sora, Veo, DALL-E, Kling, Hailuo are covered by ai-labs).+++---++## Assigned Entity List++### Image Generation++#### 1. Midjourney++| Attribute | Info |+|------|------|+| **X Official Account** | [@midjourney](https://x.com/midjourney) |+| **Key People** | David Holz, CEO |+| **Official Website** | https://www.midjourney.com |+| **Discord** | https://discord.gg/midjourney |+| **Reddit Community** | [r/midjourney](https://www.reddit.com/r/midjourney/) |++#### 2. FLUX / Black Forest Labs++| Attribute | Info |+|------|------|+| **X Official Account** | [@bfl_ml](https://x.com/bfl_ml) |+| **GitHub** | https://github.com/black-forest-labs |+| **HuggingFace** | https://huggingface.co/black-forest-labs |++#### 3. Ideogram++| Attribute | Info |+|------|------|+| **X Official Account** | [@ideaboramAI](https://x.com/ideaboramAI) |+| **Official Website** | https://ideogram.ai |++#### 4. Adobe Firefly++| Attribute | Info |+|------|------|+| **X Official Account** | [@AdobeFirefly](https://x.com/AdobeFirefly) |+| **Official Blog** | https://blog.adobe.com/en/topics/creativity |++#### 5. Leonardo AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@LeonardoAi_](https://x.com/LeonardoAi_) |+| **Official Website** | https://leonardo.ai |++#### 6. Stability AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@StabilityAI](https://x.com/StabilityAI) |+| **Key People** | Robin Rombach |+| **Official Blog** | https://stability.ai/news |+| **GitHub** | https://github.com/Stability-AI |+| **HuggingFace** | https://huggingface.co/stabilityai |+| **Discord** | https://discord.gg/stablediffusion |+| **Reddit Keywords** | Stable Diffusion, Stability AI |+| **Reddit Community** | [r/StableDiffusion](https://www.reddit.com/r/StableDiffusion/) |++#### 7. Lightricks++| Attribute | Info |+|------|------|+| **X Official Account** | [@Lightricks](https://x.com/Lightricks) |+| **Official Blog** | https://www.lightricks.com/blog |++### Video Generation++#### 8. Runway++| Attribute | Info |+|------|------|+| **X Official Account** | [@runwayml](https://x.com/runwayml) |+| **Key People** | Cristobal Valenzuela, CEO |+| **Official Blog** | https://runwayml.com/blog |+| **Changelog** | https://runwayml.com/changelog |++#### 9. Pika Labs++| Attribute | Info |+|------|------|+| **X Official Account** | [@pika_labs](https://x.com/pika_labs) |+| **Key People** | Demi Chen, Co-founder |+| **Official Website** | https://pika.art |++#### 10. Luma AI++| Attribute | Info |+|------|------|+| **X Official Account** | [@LumaLabsAI](https://x.com/LumaLabsAI) |+| **Key People** | Amit Jain, CEO |+| **Official Website** | https://lumalabs.ai |++### Audio/Speech/Music++#### 11. ElevenLabs++| Attribute | Info |+|------|------|+| **X Official Account** | [@elevenlabsio](https://x.com/elevenlabsio) |+| **Official Blog** | https://elevenlabs.io/blog |+| **Reddit Community** | [r/ElevenLabs](https://www.reddit.com/r/ElevenLabs/) |++#### 12. Udio / Suno (Music AI)++| Attribute | Info |+|------|------|+| **X Official Account (Udio)** | [@udiomusic](https://x.com/udiomusic) |+| **X Official Account (Suno)** | [@SunoAIMusic](https://x.com/SunoAIMusic) |+| **Udio Website** | https://www.udio.com |+| **Suno Website** | https://suno.com |+| **Reddit Community** | [r/SunoAI](https://www.reddit.com/r/SunoAI/), [r/udio](https://www.reddit.com/r/udio/) |++---+diff --git a/ai_agents/devable_research_agent/lib/__init__.py b/ai_agents/devable_research_agent/lib/__init__.pynew file mode 100644index 0000000..68c19dd--- /dev/null+++ b/ai_agents/devable_research_agent/lib/__init__.py@@ -0,0 +1 @@+# devable-research-agent data collection librarydiff --git a/ai_agents/devable_research_agent/lib/ainews_collector.py b/ai_agents/devable_research_agent/lib/ainews_collector.pynew file mode 100644index 0000000..774541a--- /dev/null+++ b/ai_agents/devable_research_agent/lib/ainews_collector.py@@ -0,0 +1,387 @@+"""AINews RSS collector for devable-research-agent.++Fetches daily AINews issues from smol.ai RSS, then parses each issue+HTML into individual story TrackerItems (Twitter sections, Twitter intro+bullets, and high-activity Reddit threads).+"""++import calendar+import hashlib+import html+import re+from datetime import datetime, timedelta, timezone+from typing import Dict, List, Optional, Tuple++try:+ import feedparser+ _HAS_FEEDPARSER = True+except ImportError:+ feedparser = None # type: ignore[misc, assignment]+ _HAS_FEEDPARSER = False++from . import http+from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_WEB+from .util import log, parse_date++AINEWS_RSS_URL = "https://news.smol.ai/rss.xml"+AINEWS_ENTITY = "AINews (smol.ai)"+AINEWS_LABEL = "AINews"+LOOKBACK_HOURS = 72+DEFAULT_RELEVANCE = 0.55+REDDIT_MIN_ACTIVITY = 100+SUMMARY_LIMIT = 500+TITLE_LIMIT = 200++_H1_SECTION_RE = re.compile(+ r'<h1[^>]*id="([^"]+)"[^>]*>(.*?)(?=<h1[^>]*id=|$)',+ re.IGNORECASE | re.DOTALL,+)+_H2_BLOCK_RE = re.compile(+ r'<h2[^>]*id="([^"]+)"[^>]*>(.*?)</h2>(.*?)(?=<h2[^>]*id=|$)',+ re.IGNORECASE | re.DOTALL,+)+_LI_RE = re.compile(r"<li>(.*?)</li>", re.IGNORECASE | re.DOTALL)+_FIRST_P_RE = re.compile(r"<p[^>]*>(.*?)</p>", re.IGNORECASE | re.DOTALL)+_X_URL_RE = re.compile(+ r'href="(https?://(?:www\.)?(?:x\.com|twitter\.com)/[^"]+)"',+ re.IGNORECASE,+)+_REDDIT_THREAD_RE = re.compile(+ r'<strong><a href="(https://www\.reddit\.com/[^"]+)">([^<]+)</a></strong>'+ r'\s*\(Activity:\s*(\d+)\)\s*:?\s*(.*?)(?=(?:<strong><a href="https://www\.reddit\.com/)|</li>)',+ re.IGNORECASE | re.DOTALL,+)++_log = lambda msg: log("AINews", msg, tty_only=True)+++def _url_id(url: str) -> str:+ digest = hashlib.md5(url.encode("utf-8")).hexdigest()[:12]+ return f"WEB-{digest}"+++def _strip_html(text: str) -> str:+ if not text:+ return ""+ text = html.unescape(text)+ text = re.sub(r"<br\s*/?>", "\n", text, flags=re.IGNORECASE)+ text = re.sub(r"<[^>]+>", " ", text)+ return " ".join(text.split())+++def _truncate(text: str, limit: int = SUMMARY_LIMIT) -> str:+ text = text.strip()+ if len(text) <= limit:+ return text+ return text[: limit - 3].rstrip() + "..."+++def _entry_timestamp(entry: Dict) -> Optional[float]:+ """Return entry publish time as UTC epoch seconds."""+ for attr in ("published_parsed", "updated_parsed"):+ parsed = entry.get(attr)+ if parsed:+ try:+ return float(calendar.timegm(parsed))+ except (TypeError, ValueError, OverflowError):+ continue+ for attr in ("published", "updated"):+ raw = entry.get(attr)+ if raw:+ date_str = parse_date(str(raw))+ if date_str:+ dt = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)+ return dt.timestamp()+ return None+++def _lookback_window(to_date: str) -> Tuple[float, float]:+ """Return (cutoff_ts, upper_ts) for the 72-hour window ending at to_date."""+ try:+ end = datetime.strptime(to_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)+ end = end + timedelta(days=1)+ except ValueError:+ end = datetime.now(timezone.utc)+ cutoff = end - timedelta(hours=LOOKBACK_HOURS)+ return cutoff.timestamp(), end.timestamp()+++def _fetch_feed(url: str = AINEWS_RSS_URL) -> Tuple[Optional[object], Optional[str]]:+ """Fetch and parse the RSS feed. Returns (feed, error)."""+ if not _HAS_FEEDPARSER:+ return None, "feedparser not installed (pip install feedparser)"++ try:+ body = http.get_text(+ url,+ headers={"Accept": "application/rss+xml, application/xml, text/xml"},+ timeout=20,+ retries=3,+ )+ except http.HTTPError as exc:+ return None, f"fetch failed: {exc}"+ except Exception as exc:+ return None, f"fetch failed: {exc}"++ if not body:+ return None, "empty RSS response"++ try:+ feed = feedparser.parse(body)+ except Exception as exc:+ return None, f"parse failed: {exc}"++ if getattr(feed, "bozo", False) and not getattr(feed, "entries", None):+ bozo_exc = getattr(feed, "bozo_exception", None)+ return None, f"malformed RSS feed: {bozo_exc or 'unknown parse error'}"++ return feed, None+++def _fetch_issue_html(issue_url: str) -> Tuple[Optional[str], Optional[str]]:+ """Fetch issue page HTML. Returns (article_inner_html, error)."""+ try:+ body = http.get_text(issue_url, timeout=30, retries=3)+ except http.HTTPError as exc:+ return None, f"{issue_url}: fetch failed: {exc}"+ except Exception as exc:+ return None, f"{issue_url}: fetch failed: {exc}"++ if not body:+ return None, f"{issue_url}: empty response"++ match = re.search(+ r'<article class="content-area"[^>]*>(.*?)</article>',+ body,+ re.IGNORECASE | re.DOTALL,+ )+ if not match:+ return None, f"{issue_url}: content-area not found"++ return match.group(1), None+++def _h1_section(article: str, section_id: str) -> Optional[str]:+ """Return inner HTML for a top-level h1 section by id."""+ for hid, content in _H1_SECTION_RE.findall(article):+ if hid.lower() == section_id.lower():+ return content+ return None+++def _first_paragraph_summary(chunk: str) -> str:+ match = _FIRST_P_RE.search(chunk)+ if not match:+ return ""+ return _truncate(_strip_html(match.group(1)))+++def _make_item(+ title: str,+ summary: str,+ source_url: str,+ issue_date: str,+ *,+ relevance: float = DEFAULT_RELEVANCE,+ engagement: Optional[Engagement] = None,+) -> TrackerItem:+ title = _truncate(title, TITLE_LIMIT)+ summary = _truncate(summary or title, SUMMARY_LIMIT)+ return TrackerItem(+ id=_url_id(source_url),+ title=title,+ summary=summary,+ entity=AINEWS_ENTITY,+ source=SOURCE_WEB,+ source_url=source_url,+ source_label=AINEWS_LABEL,+ date=issue_date,+ date_confidence="high",+ raw_text=summary,+ engagement=engagement or Engagement(),+ relevance=relevance,+ )+++def _parse_twitter_h2_sections(+ article: str,+ issue_url: str,+ issue_date: str,+) -> List[TrackerItem]:+ """Each h2 block in the Twitter chapter becomes one TrackerItem."""+ twitter = _h1_section(article, "ai-twitter-recap")+ if not twitter:+ return []++ base = issue_url.rstrip("/")+ items: List[TrackerItem] = []+ for section_id, heading_html, body_html in _H2_BLOCK_RE.findall(twitter):+ title = _strip_html(heading_html)+ if not title:+ continue+ summary = _first_paragraph_summary(body_html) or title+ x_match = _X_URL_RE.search(body_html)+ source_url = x_match.group(1) if x_match else f"{base}#{section_id}"+ items.append(_make_item(title, summary, source_url, issue_date))+ return items+++def _parse_twitter_intro_bullets(+ article: str,+ issue_url: str,+ issue_date: str,+) -> List[TrackerItem]:+ """li items under Twitter h1 before the first h2."""+ twitter = _h1_section(article, "ai-twitter-recap")+ if not twitter:+ return []++ intro_match = re.search(r"^(.*?)(?=<h2[^>]*id=)", twitter, re.IGNORECASE | re.DOTALL)+ if not intro_match:+ return []++ base = issue_url.rstrip("/")+ items: List[TrackerItem] = []+ for idx, li_html in enumerate(_LI_RE.findall(intro_match.group(1)), start=1):+ plain = _strip_html(li_html)+ if not plain:+ continue++ x_match = _X_URL_RE.search(li_html)+ source_url = x_match.group(1) if x_match else f"{base}#ai-twitter-recap-bullet-{idx}"+ title = _truncate(plain, TITLE_LIMIT)+ items.append(_make_item(title, plain, source_url, issue_date))+ return items+++def _parse_reddit_threads(+ article: str,+ issue_url: str,+ issue_date: str,+) -> List[TrackerItem]:+ """Reddit li items with (Activity: N); only Activity > 100."""+ reddit = _h1_section(article, "ai-reddit-recap")+ if not reddit:+ return []++ items: List[TrackerItem] = []+ seen_urls: set = set()+ for thread_url, title, activity_str, summary_html in _REDDIT_THREAD_RE.findall(reddit):+ activity = int(activity_str)+ if activity <= REDDIT_MIN_ACTIVITY:+ continue+ if thread_url in seen_urls:+ continue+ seen_urls.add(thread_url)++ title = _strip_html(title)+ summary = _truncate(_strip_html(summary_html) or title)+ relevance = min(1.0, DEFAULT_RELEVANCE + (activity / 2000))+ items.append(+ _make_item(+ title,+ summary,+ thread_url,+ issue_date,+ relevance=round(relevance, 2),+ engagement=Engagement(score=activity, total=activity),+ )+ )+ return items+++def _parse_issue_stories(+ article: str,+ issue_url: str,+ issue_date: str,+) -> List[TrackerItem]:+ """Extract all story-level TrackerItems from one issue page."""+ items: List[TrackerItem] = []+ items.extend(_parse_twitter_intro_bullets(article, issue_url, issue_date))+ items.extend(_parse_twitter_h2_sections(article, issue_url, issue_date))+ items.extend(_parse_reddit_threads(article, issue_url, issue_date))+ return items+++def _recent_issue_entries(entries: List[Dict], to_date: str) -> List[Tuple[str, str]]:+ """Return (issue_url, issue_date) pairs within the 72h lookback window."""+ cutoff_ts, upper_ts = _lookback_window(to_date)+ issues: List[Tuple[str, str]] = []+ for entry in entries:+ link = (entry.get("link") or "").strip()+ if not link:+ continue+ published_ts = _entry_timestamp(entry)+ if published_ts is None:+ continue+ if published_ts < cutoff_ts or published_ts >= upper_ts:+ continue+ issue_date = datetime.fromtimestamp(published_ts, tz=timezone.utc).strftime("%Y-%m-%d")+ issues.append((link, issue_date))+ return issues+++def collect(+ from_date: str,+ to_date: str,+ depth: str = "default",+) -> CollectionResult:+ """Collect AINews stories from issues published in the last 72 hours.++ Args:+ from_date: Start of collection window (unused; kept for collector API parity)+ to_date: End date YYYY-MM-DD — 72h lookback ends at start of next day UTC+ depth: Collection depth (unused; single feed)++ Returns:+ CollectionResult with source=\"ainews\". Never raises.+ """+ del from_date, depth # API parity with other collectors+ result = CollectionResult(source="ainews")+ result.entities_checked = 1++ feed, error = _fetch_feed()+ if error:+ result.errors.append(error)+ _log(error)+ return result++ entries = getattr(feed, "entries", []) or []+ issues = _recent_issue_entries(entries, to_date)+ if not issues:+ _log(f"0 issues in last {LOOKBACK_HOURS}h (from {len(entries)} feed entries)")+ return result++ seen_urls: set = set()+ for issue_url, issue_date in issues:+ article, fetch_error = _fetch_issue_html(issue_url)+ if fetch_error:+ result.errors.append(fetch_error)+ _log(fetch_error)+ continue++ try:+ stories = _parse_issue_stories(article, issue_url, issue_date)+ except Exception as exc:+ result.errors.append(f"{issue_url}: parse error: {exc}")+ _log(f"{issue_url}: parse error: {exc}")+ continue++ added = 0+ for item in stories:+ if item.source_url in seen_urls:+ continue+ seen_urls.add(item.source_url)+ result.items.append(item)+ added += 1++ _log(f"{issue_url}: {added} stories ({len(stories)} parsed)")++ if result.items:+ result.entities_with_updates = 1++ _log(+ f"{len(result.items)} items from {len(issues)} issues "+ f"in last {LOOKBACK_HOURS}h"+ )+ return resultdiff --git a/ai_agents/devable_research_agent/lib/arxiv.py b/ai_agents/devable_research_agent/lib/arxiv.pynew file mode 100644index 0000000..b370525--- /dev/null+++ b/ai_agents/devable_research_agent/lib/arxiv.py@@ -0,0 +1,242 @@+"""arXiv collector for devable-research-agent.++Searches arXiv papers via the Atom/XML API (free, no auth).+New collector — no last30days equivalent.+"""++import os+import re+import sys+import xml.etree.ElementTree as ET+from datetime import datetime, timedelta+from typing import Any, Dict, List, Optional+from urllib.parse import urlencode, quote++from . import http+from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_ARXIV+from .util import log, parse_date++ARXIV_API = "http://export.arxiv.org/api/query"++DEPTH_CONFIG = {"quick": 10, "default": 25, "deep": 50}++# arXiv categories for AI+AI_CATEGORIES = ["cs.AI", "cs.LG", "cs.CL", "cs.CV", "cs.MA"]++ATOM_NS = "{http://www.w3.org/2005/Atom}"++# arXiv papers don't drop daily in every category — most days the cs.AI feed has+# nothing newer than 2-3 days back. Caller passes a 1-day window which would+# leave the digest empty most mornings; widen it here. Override via+# ARXIV_LOOKBACK_DAYS=1 to restore the strict 1-day filter.+LOOKBACK_DAYS = max(1, int(os.environ.get("ARXIV_LOOKBACK_DAYS", "3")))+++_log = lambda msg: log("arXiv", msg, tty_only=True)+++_parse_date = parse_date+++def _clean_text(text: str) -> str:+ """Clean arXiv abstract text."""+ text = re.sub(r"\s+", " ", text)+ return text.strip()+++def search_papers(+ query: str,+ from_date: str,+ to_date: str,+ categories: Optional[List[str]] = None,+ max_results: int = 25,+) -> List[Dict[str, Any]]:+ """Search arXiv papers via Atom API.++ Args:+ query: Search query (author, title, abstract keywords)+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ categories: arXiv categories to filter (e.g. ["cs.CL", "cs.LG"])+ max_results: Max papers to return++ Returns:+ List of paper dicts+ """+ # Build arXiv search query+ search_parts = []+ if query:+ search_parts.append(f"all:{query}")+ if categories:+ cat_query = " OR ".join(f"cat:{cat}" for cat in categories)+ search_parts.append(f"({cat_query})")++ search_query = " AND ".join(search_parts) if search_parts else query++ params = urlencode({+ "search_query": search_query,+ "start": "0",+ "max_results": str(max_results),+ "sortBy": "submittedDate",+ "sortOrder": "descending",+ })+ url = f"{ARXIV_API}?{params}"++ try:+ xml_text = http.get(url, timeout=30, raw=True)+ except Exception as e:+ _log(f"arXiv search '{query}' failed: {e}")+ return []++ # Parse XML+ try:+ root = ET.fromstring(xml_text)+ except ET.ParseError as e:+ _log(f"Failed to parse arXiv XML: {e}")+ return []++ papers = []+ for entry in root.findall(f"{ATOM_NS}entry"):+ title_el = entry.find(f"{ATOM_NS}title")+ summary_el = entry.find(f"{ATOM_NS}summary")+ published_el = entry.find(f"{ATOM_NS}published")+ updated_el = entry.find(f"{ATOM_NS}updated")++ title = _clean_text(title_el.text) if title_el is not None and title_el.text else ""+ abstract = _clean_text(summary_el.text) if summary_el is not None and summary_el.text else ""+ published = _parse_date(published_el.text if published_el is not None else None)+ updated = _parse_date(updated_el.text if updated_el is not None else None)++ date = published or updated+ if date and (date < from_date or date > to_date):+ continue++ # Get paper URL+ paper_url = ""+ pdf_url = ""+ for link in entry.findall(f"{ATOM_NS}link"):+ href = link.get("href", "")+ link_type = link.get("type", "")+ title_attr = link.get("title", "")+ if title_attr == "pdf" or "pdf" in href:+ pdf_url = href+ elif link_type == "text/html" or (href and "abs" in href):+ paper_url = href+ elif not paper_url and href:+ paper_url = href++ # Get authors+ authors = []+ for author_el in entry.findall(f"{ATOM_NS}author"):+ name_el = author_el.find(f"{ATOM_NS}name")+ if name_el is not None and name_el.text:+ authors.append(name_el.text.strip())++ # Get categories+ cats = []+ for cat_el in entry.findall("{http://arxiv.org/schemas/atom}primary_category"):+ term = cat_el.get("term", "")+ if term:+ cats.append(term)+ for cat_el in entry.findall(f"{ATOM_NS}category"):+ term = cat_el.get("term", "")+ if term and term not in cats:+ cats.append(term)++ # Extract arXiv ID from URL+ arxiv_id = ""+ if paper_url:+ match = re.search(r"(\d{4}\.\d{4,5})(v\d+)?$", paper_url)+ if match:+ arxiv_id = match.group(1)++ papers.append({+ "arxiv_id": arxiv_id,+ "title": title,+ "abstract": abstract,+ "authors": authors,+ "date": date,+ "published": published,+ "updated": updated,+ "url": paper_url,+ "pdf_url": pdf_url,+ "categories": cats,+ })++ _log(f"arXiv '{query}': {len(papers)} papers in date range")+ return papers+++def collect(+ entities: Dict[str, List[str]],+ from_date: str,+ to_date: str,+ depth: str = "default",+) -> CollectionResult:+ """Collect arXiv papers for tracked entities.++ Args:+ entities: Dict mapping entity name -> list of search queries+ e.g. {"OpenAI": ["OpenAI"], "Anthropic": ["Anthropic"]}+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ depth: Search depth++ Returns:+ CollectionResult+ """+ result = CollectionResult(source=SOURCE_ARXIV)+ all_items = []+ max_results = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])++ # Widen the date window backwards so days with no fresh papers in the strict+ # 24h band still surface recent submissions. to_date is left as-is.+ fd = datetime.strptime(from_date, "%Y-%m-%d")+ effective_from = (fd - timedelta(days=LOOKBACK_DAYS - 1)).strftime("%Y-%m-%d")+ if effective_from != from_date:+ _log(f"window widened: {from_date}→{effective_from} (ARXIV_LOOKBACK_DAYS={LOOKBACK_DAYS})")++ for entity_name, queries in entities.items():+ result.entities_checked += 1+ entity_found = False++ for query in queries:+ papers = search_papers(+ query, effective_from, to_date,+ categories=AI_CATEGORIES,+ max_results=max_results,+ )++ for paper in papers:+ authors = paper.get("authors", [])+ author_str = ", ".join(authors[:3])+ if len(authors) > 3:+ author_str += f" et al. ({len(authors)} authors)"++ cats = paper.get("categories", [])+ cat_str = ", ".join(cats[:3])++ abstract = paper.get("abstract", "")+ summary = f"By {author_str}. {abstract[:200]}" if author_str else abstract[:300]++ all_items.append(TrackerItem(+ id=f"ARXIV-{paper.get('arxiv_id', '')}",+ title=paper.get("title", ""),+ summary=summary,+ entity=entity_name,+ source=SOURCE_ARXIV,+ source_url=paper.get("url", ""),+ source_label=f"arXiv [{cat_str}]" if cat_str else "arXiv",+ date=paper.get("date"),+ date_confidence="high" if paper.get("date") else "low",+ raw_text=abstract,+ relevance=0.7,+ ))+ entity_found = True++ if entity_found:+ result.entities_with_updates += 1++ result.items = all_items+ _log(f"Collected {len(all_items)} arXiv papers from {result.entities_checked} entities")+ return resultdiff --git a/ai_agents/devable_research_agent/lib/cache.py b/ai_agents/devable_research_agent/lib/cache.pynew file mode 100644index 0000000..02dac9e--- /dev/null+++ b/ai_agents/devable_research_agent/lib/cache.py@@ -0,0 +1,85 @@+"""Caching utilities for devable-research-agent (adapted from last30days)."""++import hashlib+import json+import os+import tempfile+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Optional++CACHE_DIR = Path.home() / ".cache" / "morning-ai"+DEFAULT_TTL_HOURS = 1 # short TTL for daily tracking — prevents stale cross-day cache+++def ensure_cache_dir():+ global CACHE_DIR+ env_dir = os.environ.get("MORNING_AI_CACHE_DIR")+ if env_dir:+ CACHE_DIR = Path(env_dir)+ try:+ CACHE_DIR.mkdir(parents=True, exist_ok=True)+ except PermissionError:+ CACHE_DIR = Path(tempfile.gettempdir()) / "morning-ai" / "cache"+ CACHE_DIR.mkdir(parents=True, exist_ok=True)+++def get_cache_key(source: str, entity: str, date: str, extra: Optional[str] = None) -> str:+ """Compute a stable 16-char cache key.++ `extra` is an optional discriminator — pass it when two callers would+ otherwise collide on (source, entity, date) but want separate cache slots+ (e.g. partial vs full source list in a daily run).+ """+ parts = [source, entity, date]+ if extra:+ parts.append(extra)+ key_data = "|".join(parts)+ return hashlib.sha256(key_data.encode()).hexdigest()[:16]+++def get_cache_path(cache_key: str) -> Path:+ return CACHE_DIR / f"{cache_key}.json"+++def is_cache_valid(cache_path: Path, ttl_hours: int = DEFAULT_TTL_HOURS) -> bool:+ if not cache_path.exists():+ return False+ try:+ stat = cache_path.stat()+ mtime = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc)+ now = datetime.now(timezone.utc)+ age_hours = (now - mtime).total_seconds() / 3600+ return age_hours < ttl_hours+ except OSError:+ return False+++def load_cache(cache_key: str, ttl_hours: int = DEFAULT_TTL_HOURS) -> Optional[dict]:+ cache_path = get_cache_path(cache_key)+ if not is_cache_valid(cache_path, ttl_hours):+ return None+ try:+ with open(cache_path, "r", encoding="utf-8") as f:+ return json.load(f)+ except (json.JSONDecodeError, OSError):+ return None+++def save_cache(cache_key: str, data: dict):+ ensure_cache_dir()+ cache_path = get_cache_path(cache_key)+ try:+ with open(cache_path, "w", encoding="utf-8") as f:+ json.dump(data, f, ensure_ascii=False)+ except OSError:+ pass+++def clear_cache():+ if CACHE_DIR.exists():+ for f in CACHE_DIR.glob("*.json"):+ try:+ f.unlink()+ except OSError:+ passdiff --git a/ai_agents/devable_research_agent/lib/classify.py b/ai_agents/devable_research_agent/lib/classify.pynew file mode 100644index 0000000..99d98d9--- /dev/null+++ b/ai_agents/devable_research_agent/lib/classify.py@@ -0,0 +1,115 @@+"""Content type classifier for devable-research-agent.++Heuristic classifier that assigns content_type (product, model, benchmark,+financing) to TrackerItems based on source, title, and summary keywords.+Runs in the collect pipeline before scoring.+"""++import re+from typing import List++from .schema import (+ TrackerItem,+ TYPE_PRODUCT,+ TYPE_MODEL,+ TYPE_BENCHMARK,+ TYPE_FINANCING,+ SOURCE_ARXIV,+ SOURCE_HUGGINGFACE,+ SOURCE_GITHUB,+)++# Keyword patterns (case-insensitive) — checked against title + summary+_FINANCING_KEYWORDS = re.compile(+ r"(?i)\b("+ r"raises|raised|funding|funded|series\s+[a-f]|valuation|"+ r"acquisition|acquire[ds]?|merger|merg(?:ed|ing)|"+ r"ipo|invest(?:ment|ed|or)|"+ r"\$\d+[mb]\b|billion|million"+ r")\b"+)++_MODEL_KEYWORDS = re.compile(+ r"(?i)\b("+ r"model|weights|parameters|param|llm|"+ r"checkpoint|fine[- ]?tun|quantiz|"+ r"gguf|ggml|fp16|bf16|int[48]|"+ r"transformer|diffusion|"+ r"open[- ]?source[ds]?\s+(?:model|weight)|"+ r"vllm|ollama|lora|qlora|"+ r"embedding|tokenizer|"+ r"\d+[bB]\b"+ r")\b"+)++_BENCHMARK_KEYWORDS = re.compile(+ r"(?i)\b("+ r"benchmark|leaderboard|arena|eval(?:uation)?|"+ r"paper|arxiv|research|study|"+ r"ranking|score[ds]?|accuracy|"+ r"MMLU|GPQA|HumanEval|MATH|ARC|HellaSwag|"+ r"interpretab|alignment|safety"+ r")\b"+)++_PRODUCT_KEYWORDS = re.compile(+ r"(?i)\b("+ r"feature|launch(?:ed|es)?|changelog|"+ r"version\s|v\d+\.\d+|release[ds]?|"+ r"cli|sdk|api|app|plugin|extension|"+ r"update[ds]?|upgrade[ds]?|"+ r"pricing|plan|tier|"+ r"beta|preview|ga\b|"+ r"dashboard|interface|ui|ux"+ r")\b"+)+++def _classify_one(item: TrackerItem) -> str:+ """Classify a single item's content type."""+ text = f"{item.title} {item.summary}"++ # Rule 1: financing keywords (highest priority — rare and distinctive)+ if _FINANCING_KEYWORDS.search(text):+ return TYPE_FINANCING++ # Rule 2: arXiv source → benchmark/research+ if item.source == SOURCE_ARXIV:+ return TYPE_BENCHMARK++ # Rule 3: HuggingFace source → model+ if item.source == SOURCE_HUGGINGFACE:+ return TYPE_MODEL++ # Rule 4: benchmark keywords+ if _BENCHMARK_KEYWORDS.search(text):+ return TYPE_BENCHMARK++ # Rule 5: model keywords+ if _MODEL_KEYWORDS.search(text):+ return TYPE_MODEL++ # Rule 6: product keywords or GitHub source (tool releases)+ if _PRODUCT_KEYWORDS.search(text):+ return TYPE_PRODUCT++ if item.source == SOURCE_GITHUB:+ return TYPE_PRODUCT++ # Rule 7: fallback+ return TYPE_PRODUCT+++def classify_items(items: List[TrackerItem]) -> List[TrackerItem]:+ """Assign content_type to items that don't already have one.++ Args:+ items: List of TrackerItems from collectors++ Returns:+ Same list with content_type populated+ """+ for item in items:+ if not item.content_type:+ item.content_type = _classify_one(item)+ return itemsdiff --git a/ai_agents/devable_research_agent/lib/custom_entities.py b/ai_agents/devable_research_agent/lib/custom_entities.pynew file mode 100644index 0000000..e4d0fb4--- /dev/null+++ b/ai_agents/devable_research_agent/lib/custom_entities.py@@ -0,0 +1,543 @@+"""Entity loader for devable-research-agent.++Parses entity markdown files from entities/ and merges them into+platform-specific registries at runtime.++Supports three markdown formats:+ 1. Standard — ``#### N. Entity Name`` headers with ``| Attribute | Info |`` tables+ 2. Tabular — ``| Name | X Account | ... |`` row-per-entity tables (KOL, benchmarks)+ 3. Custom — ``## Entity Name`` headers with ``| Platform | Value |`` tables++Search paths for custom entities (first match wins):+ 1. CUSTOM_ENTITIES_DIR env var+ 2. ~/.config/morning-ai/entities/+ 3. {project_root}/entities/custom/+"""++import os+import re+import sys+from pathlib import Path+from typing import Dict, List, Any, Optional, Tuple+from urllib.parse import unquote_plus+++# Platform field → target dict key mapping (for custom entity format)+PLATFORM_KEYS = {+ "x": "x_handles",+ "github": "github_sources",+ "huggingface": "huggingface_authors",+ "arxiv": "arxiv_queries",+ "web": "web_queries",+ "reddit": "reddit_keywords",+ "reddit_community": "reddit_subreddits",+ "hn": "hn_keywords",+}++# Attribute names that map to X handles+_X_ATTRS = {"x official account", "x account"}++# Attribute names that map to GitHub sources+_GITHUB_ATTRS = {"github", "github releases"}++# Attribute keywords that map to web_queries (blogs, changelogs, docs, etc.)+_WEB_KEYWORDS = [+ "blog", "changelog", "release notes", "research", "docs",+ "official website", "page", "volcengine", "npm package",+]++# Files to skip when loading built-in entities+_SKIP_FILES = {"custom-example.md", "trending-discovery.md"}++# Tier-aware X handle dict keys (populated alongside x_handles for collectors+# that need to distinguish official accounts from Key People).+_TIER_KEYS = ("x_handles_official", "x_handles_key_people", "x_handles_kol")+++def _empty_registry() -> Dict[str, Dict[str, Any]]:+ """Initialize a registry dict with all platform + tier keys."""+ result = {key: {} for key in PLATFORM_KEYS.values()}+ for tier_key in _TIER_KEYS:+ result[tier_key] = {}+ return result+++# ---------------------------------------------------------------------------+# Value extraction helpers+# ---------------------------------------------------------------------------++def _extract_x_handles(value: str) -> List[str]:+ """Extract X handles from markdown like ``[@OpenAI](https://x.com/OpenAI)``."""+ handles = re.findall(r'@(\w+)', value)+ return handles+++def _extract_github(value: str) -> Dict[str, List[str]]:+ """Extract GitHub orgs and repos from URLs."""+ orgs: List[str] = []+ repos: List[str] = []+ for match in re.finditer(r'github\.com/([^/\s\)]+)(?:/([^/\s\)]+))?', value):+ org = match.group(1)+ repo_name = match.group(2)+ if repo_name and repo_name not in ("releases", "blob", "tree", "wiki", "issues", "pulls"):+ repo = f"{org}/{repo_name}"+ if repo not in repos:+ repos.append(repo)+ else:+ if org not in orgs:+ orgs.append(org)+ return {"orgs": orgs, "repos": repos}+++def _extract_hf_authors(value: str) -> List[str]:+ """Extract HuggingFace author/org from URLs like ``huggingface.co/google``."""+ authors = []+ for match in re.finditer(r'huggingface\.co/([^/\s\)]+)', value):+ name = match.group(1)+ if name not in ("spaces", "papers", "datasets", "models"):+ authors.append(name)+ return authors+++def _extract_arxiv_queries(value: str) -> List[str]:+ """Extract arXiv search queries from URLs or plain text."""+ queries = []+ for match in re.finditer(r'query=([^&\s\)]+)', value):+ queries.append(unquote_plus(match.group(1)))+ return queries+++def _urls_to_site_queries(value: str) -> List[str]:+ """Convert URLs to ``site:`` search queries."""+ queries = []+ for match in re.finditer(r'https?://(?:www\.)?([^\s\)]+)', value):+ url = match.group(1).rstrip("/,.")+ # Skip repo-level GitHub/HF/arXiv URLs (handled by dedicated extractors)+ # But keep deep-path GitHub URLs (blob/tree/wiki — these are web content)+ if url.startswith("github.com"):+ parts = url.split("/")+ if len(parts) <= 3: # github.com/org or github.com/org/repo+ continue+ if url.startswith("huggingface.co") or url.startswith("arxiv.org"):+ continue+ queries.append(f"site:{url}")+ return queries+++def _parse_multi(value: str) -> List[str]:+ """Split comma-separated value and strip whitespace."""+ return [v.strip() for v in value.split(",") if v.strip()]+++def _extract_subreddits(value: str) -> List[str]:+ """Extract subreddit names from Reddit Community field.++ Handles formats like:+ - [r/DeepSeek](https://www.reddit.com/r/DeepSeek/)+ - r/DeepSeek+ - https://www.reddit.com/r/DeepSeek/+ """+ subs = []+ for match in re.finditer(r'r/(\w+)', value):+ sub = match.group(1)+ if sub not in subs:+ subs.append(sub)+ return subs+++def _parse_x_handles_custom(value: str) -> List[str]:+ """Parse X handles from custom format, stripping @ prefix."""+ return [h.lstrip("@") for h in _parse_multi(value)]+++def _parse_github_custom(value: str) -> Dict[str, List[str]]:+ """Parse GitHub value from custom format into orgs and repos."""+ orgs = []+ repos = []+ for item in _parse_multi(value):+ if "/" in item:+ repos.append(item)+ else:+ orgs.append(item)+ return {"orgs": orgs, "repos": repos}+++# ---------------------------------------------------------------------------+# Built-in entity format parser (Attribute | Info tables)+# ---------------------------------------------------------------------------++def _classify_attr(attr: str) -> str:+ """Map an attribute name to a platform key or 'skip'."""+ lower = attr.lower().strip("* ")++ # Exact matches first+ if lower in _X_ATTRS:+ return "x"+ if lower.startswith("x official account"): # handles "(Suno)", "(Udio)" suffixes+ return "x"+ if lower in _GITHUB_ATTRS or lower.startswith("github"):+ return "github"+ if lower == "huggingface":+ return "huggingface"+ if lower == "arxiv":+ return "arxiv"+ if lower == "key people":+ return "key_people"+ if lower == "reddit keywords":+ return "reddit"+ if lower == "reddit community":+ return "reddit_community"+ if lower == "hn keywords":+ return "hn"++ # Web query keywords+ for kw in _WEB_KEYWORDS:+ if kw in lower:+ return "web"++ return "skip"+++def parse_builtin_file(path: Path) -> Dict[str, Dict[str, Any]]:+ """Parse a built-in entity file with ``| Attribute | Info |`` format.++ Also handles tabular sections (``| Name | X Account | ... |``).+ """+ result = _empty_registry()+ text = path.read_text(encoding="utf-8")+ lines = text.split("\n")++ i = 0+ while i < len(lines):+ line = lines[i]++ # Detect entity header: ### N. Name or #### N. Name+ header_match = re.match(r'^#{2,4}\s+(?:\d+\.\s+)?(.+)', line)+ if header_match:+ raw_name = header_match.group(1).strip()+ # Strip suffixes like "(Full Line)"+ raw_name = re.sub(r'\s*\(Full Line\)\s*$', '', raw_name)+ entity_name = raw_name.strip()++ # Check if next non-empty lines contain a table+ i += 1+ # Look ahead for table+ while i < len(lines) and not lines[i].strip():+ i += 1++ if i < len(lines) and lines[i].strip().startswith("|"):+ # Detect table type by header row+ header_row = lines[i].strip()+ cols = [c.strip() for c in header_row.split("|") if c.strip()]++ if len(cols) >= 2 and cols[0].lower() in ("attribute", "info"):+ # Standard Attribute | Info table+ i += 1 # skip header+ # Skip separator row+ if i < len(lines) and lines[i].strip().startswith("|--"):+ i += 1+ # Parse rows+ while i < len(lines) and lines[i].strip().startswith("|"):+ row = lines[i].strip()+ parts = [p.strip() for p in row.split("|")]+ parts = [p for p in parts if p]+ if len(parts) >= 2 and not parts[0].startswith("--"):+ attr_name = parts[0].strip("* ")+ attr_value = parts[1]+ _store_attr(result, entity_name, attr_name, attr_value)+ i += 1++ elif len(cols) >= 2 and cols[0].lower() == "name":+ # Tabular format: Name | X Account | ... (multiple entities)+ col_headers = [c.lower().strip("* ") for c in cols]+ i += 1+ if i < len(lines) and lines[i].strip().startswith("|--"):+ i += 1+ while i < len(lines) and lines[i].strip().startswith("|"):+ row = lines[i].strip()+ parts = [p.strip() for p in row.split("|")]+ parts = [p for p in parts if p]+ if len(parts) >= 2 and not parts[0].startswith("--"):+ row_name = parts[0].strip()+ _store_tabular_row(result, row_name, col_headers, parts, section_name=entity_name)+ i += 1+ else:+ i += 1+ continue++ # Also detect standalone tabular sections (no entity header, like benchmarks)+ if line.strip().startswith("|"):+ cols = [c.strip() for c in line.split("|") if c.strip()]+ if len(cols) >= 2 and cols[0].lower() == "name":+ col_headers = [c.lower().strip("* ") for c in cols]+ i += 1+ if i < len(lines) and lines[i].strip().startswith("|--"):+ i += 1+ while i < len(lines) and lines[i].strip().startswith("|"):+ row = lines[i].strip()+ parts = [p.strip() for p in row.split("|")]+ parts = [p for p in parts if p]+ if len(parts) >= 2 and not parts[0].startswith("--"):+ row_name = parts[0].strip()+ _store_tabular_row(result, row_name, col_headers, parts)+ i += 1+ continue++ i += 1++ return result+++def _store_attr(result: dict, entity: str, attr_name: str, value: str):+ """Store a single attribute value into the appropriate registry."""+ platform = _classify_attr(attr_name)++ if platform == "x":+ handles = _extract_x_handles(value)+ if handles:+ result["x_handles"].setdefault(entity, []).extend(handles)+ result["x_handles_official"].setdefault(entity, []).extend(handles)+ elif platform == "key_people":+ # Extract X handles from Key People field+ handles = _extract_x_handles(value)+ if handles:+ result["x_handles"].setdefault(entity, []).extend(handles)+ result["x_handles_key_people"].setdefault(entity, []).extend(handles)+ elif platform == "github":+ gh = _extract_github(value)+ existing = result["github_sources"].get(entity, {"orgs": [], "repos": []})+ existing["orgs"].extend(o for o in gh["orgs"] if o not in existing["orgs"])+ existing["repos"].extend(r for r in gh["repos"] if r not in existing["repos"])+ result["github_sources"][entity] = existing+ elif platform == "huggingface":+ authors = _extract_hf_authors(value)+ if authors:+ result["huggingface_authors"].setdefault(entity, []).extend(authors)+ elif platform == "arxiv":+ queries = _extract_arxiv_queries(value)+ if queries:+ result["arxiv_queries"].setdefault(entity, []).extend(queries)+ elif platform == "web":+ queries = _urls_to_site_queries(value)+ if queries:+ result["web_queries"].setdefault(entity, []).extend(queries)+ elif platform == "reddit":+ keywords = _parse_multi(value)+ if keywords:+ result["reddit_keywords"][entity] = keywords+ elif platform == "reddit_community":+ subs = _extract_subreddits(value)+ if subs:+ result["reddit_subreddits"].setdefault(entity, []).extend(+ s for s in subs if s not in result["reddit_subreddits"].get(entity, [])+ )+ elif platform == "hn":+ keywords = _parse_multi(value)+ if keywords:+ result["hn_keywords"][entity] = keywords+++def _is_kol_section(section_name: str) -> bool:+ """Check if a section header indicates KOL / Key People entities."""+ lower = section_name.lower()+ return "kol" in lower or "key opinion leader" in lower or "key people" in lower+++def _store_tabular_row(+ result: dict, name: str, col_headers: List[str], parts: List[str],+ section_name: str = "",+):+ """Store a row from a tabular entity table (Name | X Account | ...)."""+ is_kol = _is_kol_section(section_name)+ for idx, header in enumerate(col_headers):+ if idx >= len(parts):+ break+ value = parts[idx]+ if not value or value == "-":+ continue++ if header in ("x account",):+ handles = _extract_x_handles(value)+ if handles:+ result["x_handles"].setdefault(name, []).extend(handles)+ tier_key = "x_handles_kol" if is_kol else "x_handles_official"+ result[tier_key].setdefault(name, []).extend(handles)+ elif header == "github":+ gh = _extract_github(value)+ existing = result["github_sources"].get(name, {"orgs": [], "repos": []})+ existing["orgs"].extend(o for o in gh["orgs"] if o not in existing["orgs"])+ existing["repos"].extend(r for r in gh["repos"] if r not in existing["repos"])+ result["github_sources"][name] = existing+ elif header == "website":+ queries = _urls_to_site_queries(value)+ if queries:+ result["web_queries"].setdefault(name, []).extend(queries)+++# ---------------------------------------------------------------------------+# Built-in entity loader+# ---------------------------------------------------------------------------++def load_builtin_entities() -> Dict[str, Dict[str, Any]]:+ """Load all built-in entity files from ``entities/`` directory.++ Returns:+ Merged dictionary with keys matching PLATFORM_KEYS values.+ """+ merged = _empty_registry()+ entities_dir = Path(__file__).resolve().parent.parent / "entities"++ if not entities_dir.is_dir():+ return merged++ for md_file in sorted(entities_dir.glob("*.md")):+ if md_file.name in _SKIP_FILES:+ continue+ if md_file.name.startswith("custom"):+ continue+ try:+ parsed = parse_builtin_file(md_file)+ for dict_key in merged.keys():+ for entity, values in parsed[dict_key].items():+ if dict_key in ("github_sources",):+ existing = merged[dict_key].get(entity, {"orgs": [], "repos": []})+ existing["orgs"].extend(o for o in values["orgs"] if o not in existing["orgs"])+ existing["repos"].extend(r for r in values["repos"] if r not in existing["repos"])+ merged[dict_key][entity] = existing+ elif isinstance(values, list):+ merged[dict_key].setdefault(entity, []).extend(+ v for v in values if v not in merged[dict_key].get(entity, [])+ )+ else:+ merged[dict_key][entity] = values+ except Exception as e:+ print(f"[devable-research-agent] Warning: failed to parse {md_file}: {e}", file=sys.stderr)++ return merged+++# ---------------------------------------------------------------------------+# Custom entity format parser (Platform | Value tables)+# ---------------------------------------------------------------------------++def parse_custom_file(path: Path) -> Dict[str, Dict[str, Any]]:+ """Parse a single custom entity markdown file.++ Returns:+ Dict with keys matching PLATFORM_KEYS values, each mapping+ entity names to their platform-specific values.+ """+ result = _empty_registry()++ text = path.read_text(encoding="utf-8")+ sections = re.split(r"^## +", text, flags=re.MULTILINE)++ for section in sections[1:]:+ lines = section.strip().split("\n")+ entity_name = lines[0].strip()+ if not entity_name:+ continue++ for line in lines[1:]:+ line = line.strip()+ if not line.startswith("|") or line.startswith("|--") or line.startswith("| Platform"):+ continue+ parts = [p.strip() for p in line.split("|")]+ parts = [p for p in parts if p]+ if len(parts) < 2:+ continue++ platform = parts[0].lower().strip("*")+ value = parts[1]++ if platform == "x":+ handles = _parse_x_handles_custom(value)+ result["x_handles"][entity_name] = handles+ # Custom entity X handles default to official tier+ result["x_handles_official"][entity_name] = handles+ elif platform == "github":+ result["github_sources"][entity_name] = _parse_github_custom(value)+ elif platform == "huggingface":+ result["huggingface_authors"][entity_name] = _parse_multi(value)+ elif platform == "arxiv":+ result["arxiv_queries"][entity_name] = _parse_multi(value)+ elif platform == "web":+ result["web_queries"][entity_name] = _parse_multi(value)+ elif platform == "reddit":+ result["reddit_keywords"][entity_name] = _parse_multi(value)+ elif platform in ("reddit community", "reddit_community"):+ subs = _extract_subreddits(value)+ if subs:+ result["reddit_subreddits"][entity_name] = subs+ elif platform == "hn":+ result["hn_keywords"][entity_name] = _parse_multi(value)++ return result+++def _get_search_dirs() -> List[Path]:+ """Get custom entity directories in priority order."""+ dirs = []+ env_dir = os.environ.get("CUSTOM_ENTITIES_DIR")+ if env_dir:+ dirs.append(Path(env_dir))+ dirs.append(Path.home() / ".config" / "morning-ai" / "entities")+ project_root = Path(__file__).resolve().parent.parent+ dirs.append(project_root / "entities" / "custom")+ return dirs+++def load_custom_entities() -> Dict[str, Dict[str, Any]]:+ """Load all custom entity files from search directories.++ Returns:+ Merged dictionary of all custom entities across all files and directories.+ """+ merged = _empty_registry()++ for search_dir in _get_search_dirs():+ if not search_dir.is_dir():+ continue+ for md_file in sorted(search_dir.glob("*.md")):+ if md_file.name == "custom-example.md":+ continue+ try:+ parsed = parse_custom_file(md_file)+ for dict_key in merged.keys():+ merged[dict_key].update(parsed[dict_key])+ except Exception as e:+ print(f"[devable-research-agent] Warning: failed to parse {md_file}: {e}", file=sys.stderr)++ return merged+++def merge_into_registries(+ x_handles: dict,+ github_sources: dict,+ huggingface_authors: dict,+ arxiv_queries: dict,+ web_queries: dict,+ reddit_keywords: dict,+ reddit_subreddits: dict,+ hn_keywords: dict,+ x_handles_official: Optional[dict] = None,+ x_handles_key_people: Optional[dict] = None,+ x_handles_kol: Optional[dict] = None,+) -> None:+ """Load custom entities and merge into the provided registry dicts."""+ custom = load_custom_entities()++ x_handles.update(custom["x_handles"])+ github_sources.update(custom["github_sources"])+ huggingface_authors.update(custom["huggingface_authors"])+ arxiv_queries.update(custom["arxiv_queries"])+ web_queries.update(custom["web_queries"])+ reddit_keywords.update(custom["reddit_keywords"])+ reddit_subreddits.update(custom["reddit_subreddits"])+ hn_keywords.update(custom["hn_keywords"])+ if x_handles_official is not None:+ x_handles_official.update(custom["x_handles_official"])+ if x_handles_key_people is not None:+ x_handles_key_people.update(custom["x_handles_key_people"])+ if x_handles_kol is not None:+ x_handles_kol.update(custom["x_handles_kol"])diff --git a/ai_agents/devable_research_agent/lib/dedupe.py b/ai_agents/devable_research_agent/lib/dedupe.pynew file mode 100644index 0000000..b6b738e--- /dev/null+++ b/ai_agents/devable_research_agent/lib/dedupe.py@@ -0,0 +1,282 @@+"""Near-duplicate detection for devable-research-agent.++Adapted from last30days dedupe.py.+Supports within-source dedup and cross-source linking.+"""++import re+from datetime import date as _date+from typing import List, Set, Tuple+from urllib.parse import urlparse++from .schema import TrackerItem++# Stopwords for token-based matching+STOPWORDS = frozenset({+ "the", "a", "an", "to", "for", "how", "is", "in", "of", "on",+ "and", "with", "from", "by", "at", "this", "that", "it", "my",+ "your", "i", "me", "we", "you", "what", "are", "do", "can",+ "its", "be", "or", "not", "no", "so", "if", "but", "about",+ "all", "just", "get", "has", "have", "was", "will", "new",+ "ai", "model", "release", "update", "now", "available",+})+++def normalize_text(text: str) -> str:+ """Normalize text for comparison."""+ text = text.lower()+ text = re.sub(r"[^\w\s]", " ", text)+ text = re.sub(r"\s+", " ", text)+ return text.strip()+++def get_ngrams(text: str, n: int = 3) -> Set[str]:+ """Get character n-grams from text."""+ text = normalize_text(text)+ if len(text) < n:+ return {text}+ return {text[i:i + n] for i in range(len(text) - n + 1)}+++def jaccard_similarity(set1: Set[str], set2: Set[str]) -> float:+ """Compute Jaccard similarity between two sets."""+ if not set1 or not set2:+ return 0.0+ intersection = len(set1 & set2)+ union = len(set1 | set2)+ return intersection / union if union > 0 else 0.0+++def get_item_text(item: TrackerItem) -> str:+ """Get comparable text from a TrackerItem."""+ if item.title:+ return item.title+ return item.raw_text[:150]+++def _tokenize(text: str) -> Set[str]:+ """Tokenize text for token-level Jaccard."""+ words = re.sub(r"[^\w\s]", " ", text.lower()).split()+ return {w for w in words if w not in STOPWORDS and len(w) > 1}+++def _token_jaccard(text_a: str, text_b: str) -> float:+ """Token-level Jaccard similarity."""+ tokens_a = _tokenize(text_a)+ tokens_b = _tokenize(text_b)+ if not tokens_a or not tokens_b:+ return 0.0+ intersection = len(tokens_a & tokens_b)+ union = len(tokens_a | tokens_b)+ return intersection / union if union else 0.0+++def hybrid_similarity(text_a: str, text_b: str) -> float:+ """Hybrid similarity: max of char-trigram Jaccard and token Jaccard."""+ trigram_sim = jaccard_similarity(get_ngrams(text_a), get_ngrams(text_b))+ token_sim = _token_jaccard(text_a, text_b)+ return max(trigram_sim, token_sim)+++def find_duplicates(+ items: List[TrackerItem],+ threshold: float = 0.7,+) -> List[Tuple[int, int]]:+ """Find near-duplicate pairs by Jaccard similarity.++ Args:+ items: List of items to check+ threshold: Similarity threshold (0-1)++ Returns:+ List of (i, j) index pairs where items are similar+ """+ duplicates = []+ ngrams = [get_ngrams(get_item_text(item)) for item in items]++ for i in range(len(items)):+ for j in range(i + 1, len(items)):+ similarity = jaccard_similarity(ngrams[i], ngrams[j])+ if similarity >= threshold:+ duplicates.append((i, j))++ return duplicates+++def dedupe_items(+ items: List[TrackerItem],+ threshold: float = 0.7,+) -> List[TrackerItem]:+ """Remove near-duplicates, keeping highest-scored item.++ Args:+ items: List of items (should be pre-sorted by importance desc)+ threshold: Similarity threshold++ Returns:+ Deduplicated items+ """+ if len(items) <= 1:+ return items++ dup_pairs = find_duplicates(items, threshold)++ to_remove = set()+ for i, j in dup_pairs:+ if items[i].importance >= items[j].importance:+ to_remove.add(j)+ else:+ to_remove.add(i)++ return [item for idx, item in enumerate(items) if idx not in to_remove]+++def dedupe_by_source(items: List[TrackerItem], threshold: float = 0.7) -> List[TrackerItem]:+ """Deduplicate items within each source separately.++ More efficient than global dedup for large item sets.++ Args:+ items: All collected items+ threshold: Similarity threshold++ Returns:+ Deduplicated items+ """+ by_source = {}+ for item in items:+ by_source.setdefault(item.source, []).append(item)++ result = []+ for source, source_items in by_source.items():+ source_items.sort(key=lambda x: x.importance, reverse=True)+ deduped = dedupe_items(source_items, threshold)+ result.extend(deduped)++ return result+++def cross_source_link(+ items: List[TrackerItem],+ threshold: float = 0.40,+) -> List[TrackerItem]:+ """Link similar items across different sources.++ Uses hybrid similarity (char-trigram + token Jaccard) for cross-source+ matching. Adds bidirectional cross_refs when similarity exceeds threshold.++ Also considers entity matching: items about the same entity get a+ similarity boost for more accurate cross-referencing.++ Args:+ items: All items from all sources+ threshold: Similarity threshold for cross-linking++ Returns:+ Items with cross_refs populated+ """+ if len(items) <= 1:+ return items++ # Pre-compute normalized texts for cross-source comparison+ texts = []+ for item in items:+ texts.append(_normalize_for_cross_source(item))++ # Pre-compute URL domains for URL-based matching+ domains = []+ for item in items:+ domains.append(_extract_url_domain(item.source_url))++ # Pre-parse dates for proximity check+ parsed_dates = []+ for item in items:+ try:+ parsed_dates.append(_date.fromisoformat(item.date) if item.date else None)+ except ValueError:+ parsed_dates.append(None)++ for i in range(len(items)):+ for j in range(i + 1, len(items)):+ # Skip same-source comparisons+ if items[i].source == items[j].source:+ continue++ # Skip items with dates too far apart (>3 days)+ if parsed_dates[i] and parsed_dates[j]:+ if abs((parsed_dates[i] - parsed_dates[j]).days) > 3:+ continue++ similarity = hybrid_similarity(texts[i], texts[j])++ # Entity match bonus: same entity increases likelihood of cross-ref+ same_entity = items[i].entity and items[i].entity == items[j].entity+ if same_entity:+ similarity += 0.25++ # URL domain bonus: items linking to same domain+ if domains[i] and domains[j] and domains[i] == domains[j]:+ similarity += 0.15++ # Use lower threshold for same-entity comparisons+ effective_threshold = 0.25 if same_entity else threshold++ if similarity >= effective_threshold:+ if items[j].id not in items[i].cross_refs:+ items[i].cross_refs.append(items[j].id)+ if items[i].id not in items[j].cross_refs:+ items[j].cross_refs.append(items[i].id)++ return items+++def _normalize_for_cross_source(item: TrackerItem) -> str:+ """Normalize item text for cross-source comparison.++ Different sources use very different title formats:+ - HuggingFace: "nvidia/Gemma-4-31B-IT-NVFP4" (model IDs)+ - GitHub: "anthropics/claude-code v2.1.107" (repo + version)+ - HN/Reddit: Natural language titles++ This function normalizes them to improve cross-source matching.+ """+ text = get_item_text(item)++ if item.source == "huggingface":+ # Split org/model format, expand separators+ if "/" in text:+ text = text.split("/", 1)[-1] # drop org prefix+ text = re.sub(r"[-_]", " ", text)++ elif item.source == "github":+ # Drop org prefix, remove version numbers+ if "/" in text:+ parts = text.split("/", 1)+ text = parts[-1]+ text = re.sub(r"\bv?\d+\.\d+\.\d+\b", "", text) # remove semver+ text = re.sub(r"[-_]", " ", text)++ # Common cleanup for all sources+ text = re.sub(r"\bv?\d+(?:\.\d+)+\b", "", text) # version numbers like v2.1, 2.1.107+ text = re.sub(r"\bv\d+\b", "", text) # simple version tags like v2+ text = re.sub(r"\b\d{4,}\b", "", text) # long numbers (dates, IDs)+ text = text.lower().strip()+ return text+++def _extract_url_domain(url: str) -> str:+ """Extract domain from URL for cross-source matching."""+ if not url:+ return ""+ try:+ parsed = urlparse(url)+ domain = parsed.netloc or ""+ if domain.startswith("www."):+ domain = domain[4:]+ # Exclude generic platforms (they host many unrelated items)+ if domain in ("github.com", "news.ycombinator.com", "reddit.com",+ "huggingface.co", "arxiv.org", "x.com", "twitter.com"):+ return ""+ return domain+ except Exception:+ return ""diff --git a/ai_agents/devable_research_agent/lib/entities.py b/ai_agents/devable_research_agent/lib/entities.pynew file mode 100644index 0000000..2b232db--- /dev/null+++ b/ai_agents/devable_research_agent/lib/entities.py@@ -0,0 +1,40 @@+"""Entity registry for devable-research-agent.++Loads 80+ tracked entities from ``entities/*.md`` at import time.+Custom entities are merged from:+ 1. CUSTOM_ENTITIES_DIR env var+ 2. ~/.config/morning-ai/entities/+ 3. {project_root}/entities/custom/+"""++from lib.custom_entities import load_builtin_entities, merge_into_registries++# Load built-in entities from entities/*.md+_builtin = load_builtin_entities()++X_HANDLES = _builtin["x_handles"]+X_HANDLES_OFFICIAL = _builtin["x_handles_official"]+X_HANDLES_KEY_PEOPLE = _builtin["x_handles_key_people"]+X_HANDLES_KOL = _builtin["x_handles_kol"]+GITHUB_SOURCES = _builtin["github_sources"]+HUGGINGFACE_AUTHORS = _builtin["huggingface_authors"]+ARXIV_QUERIES = _builtin["arxiv_queries"]+WEB_QUERIES = _builtin["web_queries"]+REDDIT_KEYWORDS = _builtin["reddit_keywords"]+REDDIT_SUBREDDITS = _builtin["reddit_subreddits"]+HN_KEYWORDS = _builtin["hn_keywords"]++# Merge custom entities on top+merge_into_registries(+ X_HANDLES,+ GITHUB_SOURCES,+ HUGGINGFACE_AUTHORS,+ ARXIV_QUERIES,+ WEB_QUERIES,+ REDDIT_KEYWORDS,+ REDDIT_SUBREDDITS,+ HN_KEYWORDS,+ x_handles_official=X_HANDLES_OFFICIAL,+ x_handles_key_people=X_HANDLES_KEY_PEOPLE,+ x_handles_kol=X_HANDLES_KOL,+)diff --git a/ai_agents/devable_research_agent/lib/env.py b/ai_agents/devable_research_agent/lib/env.pynew file mode 100644index 0000000..c5b6bcf--- /dev/null+++ b/ai_agents/devable_research_agent/lib/env.py@@ -0,0 +1,63 @@+"""Environment and configuration management for devable-research-agent."""++import os+from pathlib import Path+from typing import Any, Dict, Optional+++def load_env_file(path: str) -> Dict[str, str]:+ """Parse a .env file into a dict."""+ env = {}+ p = Path(path)+ if not p.exists():+ return env+ for line in p.read_text().splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ if "=" not in line:+ continue+ key, _, value = line.partition("=")+ key = key.strip()+ value = value.strip().strip("'\"")+ env[key] = value+ return env+++def get_config() -> Dict[str, Any]:+ """Load config from environment + .env files.++ Priority: env vars > project .env > project .claude/morning-ai.env > global config+ """+ global_env = load_env_file(str(Path.home() / ".config" / "morning-ai" / ".env"))+ project_claude_env = load_env_file(".claude/morning-ai.env")+ project_env = load_env_file(".env")+ local_env = load_env_file(".env.local")++ config = {}+ config.update(global_env)+ 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_"))})++ return config+++def get_key(config: Dict[str, Any], key: str) -> Optional[str]:+ """Get a config value, returning None if empty."""+ val = config.get(key, "")+ return val if val else None+++def get_available_sources(config: Dict[str, Any]) -> Dict[str, bool]:+ """Check which data sources are available based on configured API keys."""+ return {+ "hackernews": True,+ "github": bool(get_key(config, "GITHUB_TOKEN")),+ "huggingface": True,+ "arxiv": True,+ "tavily": bool(get_key(config, "TAVILY_API_KEY")),+ "goodailist": True,+ "ainews": True,+ }diff --git a/ai_agents/devable_research_agent/lib/github.py b/ai_agents/devable_research_agent/lib/github.pynew file mode 100644index 0000000..839a6c3--- /dev/null+++ b/ai_agents/devable_research_agent/lib/github.py@@ -0,0 +1,305 @@+"""GitHub collector for devable-research-agent.++Monitors releases, trending repos, and commit activity via GitHub API.+New collector — no last30days equivalent.+"""++import math+import sys+from typing import Any, Dict, List, Optional+from urllib.parse import urlencode++from . import http+from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_GITHUB+from .util import log, parse_date++GITHUB_API = "https://api.github.com"++DEPTH_CONFIG = {"quick": 5, "default": 10, "deep": 20}+++_log = lambda msg: log("GitHub", msg, tty_only=True)+++def _gh_headers(token: Optional[str] = None) -> Dict[str, str]:+ headers = {+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ }+ if token:+ headers["Authorization"] = f"Bearer {token}"+ return headers+++_parse_date = parse_date+++def get_org_releases(+ org: str,+ from_date: str,+ to_date: str,+ token: Optional[str] = None,+ depth: str = "default",+) -> List[Dict[str, Any]]:+ """Get recent releases from an org's repos."""+ per_page = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])+ headers = _gh_headers(token)++ # Search for recent releases via GitHub search API+ query = f"org:{org}"+ params = urlencode({+ "q": query,+ "sort": "updated",+ "order": "desc",+ "per_page": str(per_page),+ })+ url = f"{GITHUB_API}/search/repositories?{params}"++ try:+ response = http.get(url, headers=headers, timeout=30)+ except Exception as e:+ _log(f"Failed to search org {org}: {e}")+ return []++ repos = response.get("items", [])+ releases = []++ for repo in repos[:per_page]:+ repo_name = repo.get("full_name", "")+ releases_url = f"{GITHUB_API}/repos/{repo_name}/releases?per_page=5"++ try:+ repo_releases = http.get(releases_url, headers=headers, timeout=15)+ except Exception:+ continue++ if not isinstance(repo_releases, list):+ continue++ for rel in repo_releases:+ pub_date = _parse_date(rel.get("published_at"))+ if pub_date and from_date <= pub_date <= to_date:+ releases.append({+ "repo": repo_name,+ "tag": rel.get("tag_name", ""),+ "name": rel.get("name", ""),+ "body": rel.get("body", ""),+ "url": rel.get("html_url", ""),+ "date": pub_date,+ "prerelease": rel.get("prerelease", False),+ })++ return releases+++def get_repo_releases(+ repo: str,+ from_date: str,+ to_date: str,+ token: Optional[str] = None,+) -> List[Dict[str, Any]]:+ """Get recent releases from a specific repo."""+ headers = _gh_headers(token)+ url = f"{GITHUB_API}/repos/{repo}/releases?per_page=10"++ try:+ response = http.get(url, headers=headers, timeout=15)+ except Exception as e:+ _log(f"Failed to get releases for {repo}: {e}")+ return []++ if not isinstance(response, list):+ return []++ releases = []+ for rel in response:+ pub_date = _parse_date(rel.get("published_at"))+ if pub_date and from_date <= pub_date <= to_date:+ releases.append({+ "repo": repo,+ "tag": rel.get("tag_name", ""),+ "name": rel.get("name", ""),+ "body": (rel.get("body") or "")[:500],+ "url": rel.get("html_url", ""),+ "date": pub_date,+ "prerelease": rel.get("prerelease", False),+ })++ return releases+++OSSINSIGHT_API = "https://api.ossinsight.io/v1/trends/repos/"+OSSINSIGHT_DEPTH = {"quick": 20, "default": 50, "deep": 100}+++def fetch_ossinsight_trending(depth: str = "default") -> List[Dict[str, Any]]:+ """Fetch trending repos from OSS Insight API (past 24 hours).++ Returns rows sorted by composite score (stars + forks + PRs + pushes).+ Free API, no auth required.+ """+ limit = OSSINSIGHT_DEPTH.get(depth, 50)+ url = f"{OSSINSIGHT_API}?period=past_24_hours&language=All"++ try:+ response = http.get(url, timeout=15, retries=2)+ except Exception as e:+ _log(f"OSS Insight API failed: {e}")+ return []++ rows = response.get("data", {}).get("rows", [])+ return rows[:limit]+++def collect(+ entities: Dict[str, Dict[str, Any]],+ from_date: str,+ to_date: str,+ token: Optional[str] = None,+ depth: str = "default",+) -> CollectionResult:+ """Collect GitHub data for tracked entities.++ Args:+ entities: Dict mapping entity name -> {+ "orgs": ["openai", "anthropics"], # GitHub org names+ "repos": ["owner/repo"], # Specific repos+ }+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ token: GitHub token (optional, increases rate limit)+ depth: Search depth++ Returns:+ CollectionResult+ """+ result = CollectionResult(source=SOURCE_GITHUB)+ all_items = []++ for entity_name, sources in entities.items():+ result.entities_checked += 1+ entity_found = False++ # Check specific repos+ for repo in sources.get("repos", []):+ releases = get_repo_releases(repo, from_date, to_date, token)+ for rel in releases:+ tag = rel.get("tag", "")+ name = rel.get("name") or tag+ body = rel.get("body", "")++ all_items.append(TrackerItem(+ id=f"GH-{repo}-{tag}",+ title=f"{repo} {name}",+ summary=body[:300] if body else f"New release: {name}",+ entity=entity_name,+ source=SOURCE_GITHUB,+ source_url=rel.get("url", f"https://github.com/{repo}/releases"),+ source_label=f"GitHub {repo}",+ date=rel.get("date"),+ date_confidence="high",+ raw_text=body,+ engagement=Engagement(), # no repo-level stars for releases+ relevance=0.8 if not rel.get("prerelease") else 0.5,+ ))+ entity_found = True++ # Check org releases+ for org in sources.get("orgs", []):+ releases = get_org_releases(org, from_date, to_date, token, depth)+ for rel in releases:+ tag = rel.get("tag", "")+ name = rel.get("name") or tag+ repo = rel.get("repo", org)+ body = rel.get("body", "")++ all_items.append(TrackerItem(+ id=f"GH-{repo}-{tag}",+ title=f"{repo} {name}",+ summary=body[:300] if body else f"New release: {name}",+ entity=entity_name,+ source=SOURCE_GITHUB,+ source_url=rel.get("url", f"https://github.com/{repo}"),+ source_label=f"GitHub {repo}",+ date=rel.get("date"),+ date_confidence="high",+ raw_text=body,+ engagement=Engagement(), # no repo-level stars for releases+ relevance=0.8 if not rel.get("prerelease") else 0.5,+ ))+ entity_found = True++ if entity_found:+ result.entities_with_updates += 1++ result.items = all_items+ _log(f"Collected {len(all_items)} GitHub releases from {result.entities_checked} entities")++ # --- OSS Insight trending: cross-verify + discover ---+ _log("Fetching OSS Insight trending repos...")+ trending_rows = fetch_ossinsight_trending(depth)++ if trending_rows:+ # Build org -> entity lookup for matching+ org_to_entity: Dict[str, str] = {}+ repo_to_entity: Dict[str, str] = {}+ for entity_name, sources in entities.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++ # Score threshold: skip bottom 20% by total_score+ scores = sorted(float(r.get("total_score", 0)) for r in trending_rows)+ min_score = scores[len(scores) // 5] if len(scores) >= 5 else 0+ max_score = scores[-1] if scores else 1++ trending_count = 0+ for row in trending_rows:+ repo_name = row.get("repo_name", "")+ total_score = float(row.get("total_score", 0))++ if not repo_name or total_score < min_score:+ continue++ owner = repo_name.split("/")[0].lower() if "/" in repo_name else ""+ description = row.get("description") or ""+ stars = int(row.get("stars") or 0)+ forks = int(row.get("forks") or 0)++ # Match against tracked entities+ matched_entity = (+ org_to_entity.get(owner)+ or repo_to_entity.get(repo_name.lower())+ )++ if matched_entity:+ entity_label = matched_entity+ relevance = 0.8+ else:+ entity_label = "GitHub Trending"+ relevance = 0.6++ # Normalize OSS Insight score to 0-1 for relevance boost+ norm_score = total_score / max_score if max_score > 0 else 0+ relevance = min(1.0, relevance + norm_score * 0.15)++ all_items.append(TrackerItem(+ id=f"GH-TREND-{repo_name}",+ title=repo_name,+ summary=description[:300] if description else f"Trending repo with {stars} stars",+ entity=entity_label,+ source=SOURCE_GITHUB,+ source_url=f"https://github.com/{repo_name}",+ source_label=f"GitHub Trending (OSS Insight)",+ date=to_date,+ date_confidence="high",+ engagement=Engagement(stars=stars, forks=forks),+ relevance=relevance,+ ))+ trending_count += 1++ result.items = all_items+ _log(f"Added {trending_count} trending repos from OSS Insight")++ return resultdiff --git a/ai_agents/devable_research_agent/lib/goodailist_scraper.py b/ai_agents/devable_research_agent/lib/goodailist_scraper.pynew file mode 100644index 0000000..c064e07--- /dev/null+++ b/ai_agents/devable_research_agent/lib/goodailist_scraper.py@@ -0,0 +1,329 @@+"""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 re+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']"++_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 _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")++ 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 _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")+ 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}")+ return result++ if not rows:+ result.errors.append("Good AI List scrape returned no AI Engineering NEW repos")+ 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 resultdiff --git a/ai_agents/devable_research_agent/lib/hackernews.py b/ai_agents/devable_research_agent/lib/hackernews.pynew file mode 100644index 0000000..5a7c8a5--- /dev/null+++ b/ai_agents/devable_research_agent/lib/hackernews.py@@ -0,0 +1,229 @@+"""Hacker News collector for devable-research-agent (Algolia API, free).++Adapted from last30days hackernews.py.+"""++import html+import math+import re+import sys+from concurrent.futures import ThreadPoolExecutor, as_completed+from typing import Any, Dict, List, Optional+from urllib.parse import urlencode++from . import http+from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_HACKERNEWS+from .util import log++ALGOLIA_SEARCH_URL = "https://hn.algolia.com/api/v1/search"+ALGOLIA_ITEM_URL = "https://hn.algolia.com/api/v1/items"++DEPTH_CONFIG = {"quick": 15, "default": 30, "deep": 60}+ENRICH_LIMITS = {"quick": 3, "default": 5, "deep": 10}++# Noise patterns to filter low-quality HN posts+NOISE_PATTERNS = [+ r"(?i)\bis\s+\w+\s+down\b",+ r"(?i)\bdown\b.*\bagain\b",+ r"(?i)\bregret\b.*\bai\b",+ r"(?i)\brant\b",+ r"(?i)^ask hn:.*\b(career|hire|interview|freelance)\b",+]++MIN_POINTS = 5+++def _is_noise(title: str, points: int) -> bool:+ """Check if a story title matches noise patterns."""+ if points >= 100:+ return False+ for pat in NOISE_PATTERNS:+ if re.search(pat, title):+ return True+ return False+++def _extract_domain(url: str) -> str:+ """Extract domain from URL for summary display."""+ if not url:+ return ""+ try:+ from urllib.parse import urlparse+ parsed = urlparse(url)+ domain = parsed.netloc or ""+ if domain.startswith("www."):+ domain = domain[4:]+ return domain+ except Exception:+ return ""+++_log = lambda msg: log("HN", msg, tty_only=True)+++def _date_to_unix(date_str: str) -> int:+ import datetime+ parts = date_str.split("-")+ dt = datetime.datetime(int(parts[0]), int(parts[1]), int(parts[2]), tzinfo=datetime.timezone.utc)+ return int(dt.timestamp())+++def _unix_to_date(ts: int) -> str:+ import datetime+ dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)+ return dt.strftime("%Y-%m-%d")+++def _strip_html(text: str) -> str:+ text = html.unescape(text)+ text = re.sub(r"<p>", "\n", text)+ text = re.sub(r"<[^>]+>", "", text)+ return text.strip()+++def search(+ query: str,+ from_date: str,+ to_date: str,+ depth: str = "default",+) -> List[Dict[str, Any]]:+ """Search HN via Algolia API."""+ count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])+ from_ts = _date_to_unix(from_date)+ to_ts = _date_to_unix(to_date) + 86400++ params = {+ "query": query,+ "tags": "story",+ "numericFilters": f"created_at_i>{from_ts},created_at_i<{to_ts},points>{MIN_POINTS}",+ "hitsPerPage": str(count),+ }+ url = f"{ALGOLIA_SEARCH_URL}?{urlencode(params)}"++ try:+ response = http.get(url, timeout=30)+ except Exception as e:+ _log(f"Search failed: {e}")+ return []++ return response.get("hits", [])+++def _fetch_comments(object_id: str, max_comments: int = 5) -> List[str]:+ """Fetch top comments for a story."""+ url = f"{ALGOLIA_ITEM_URL}/{object_id}"+ try:+ data = http.get(url, timeout=15)+ except Exception:+ return []++ children = data.get("children", [])+ real_comments = [c for c in children if c.get("text") and c.get("author")]+ real_comments.sort(key=lambda c: c.get("points") or 0, reverse=True)++ insights = []+ for c in real_comments[:max_comments]:+ text = _strip_html(c.get("text", ""))+ first_sentence = text.split(". ")[0].split("\n")[0][:200]+ if first_sentence:+ insights.append(first_sentence)+ return insights+++def collect(+ entities: Dict[str, List[str]],+ from_date: str,+ to_date: str,+ depth: str = "default",+) -> CollectionResult:+ """Collect HN stories for tracked entities.++ Args:+ entities: Dict mapping entity name -> list of search keywords+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ depth: Search depth++ Returns:+ CollectionResult+ """+ result = CollectionResult(source=SOURCE_HACKERNEWS)+ all_items = []+ enrich_limit = ENRICH_LIMITS.get(depth, ENRICH_LIMITS["default"])++ for entity_name, keywords in entities.items():+ result.entities_checked += 1+ entity_found = False++ for keyword in keywords:+ hits = search(keyword, from_date, to_date, depth)+ if not hits:+ continue++ for i, hit in enumerate(hits):+ object_id = hit.get("objectID", "")+ title = hit.get("title", "")+ points = hit.get("points") or 0+ num_comments_val = hit.get("num_comments") or 0+ created_at_i = hit.get("created_at_i")+ date_str = _unix_to_date(created_at_i) if created_at_i else None+ article_url = hit.get("url") or ""+ story_text = hit.get("story_text") or ""+ hn_url = f"https://news.ycombinator.com/item?id={object_id}"++ if _is_noise(title, points):+ continue++ # Build meaningful summary+ if story_text:+ # Text posts (Ask HN, Show HN): use story text+ summary = _strip_html(story_text)[:300]+ elif article_url:+ # Link posts: include domain for context+ domain = _extract_domain(article_url)+ summary = f"via {domain} ({points} pts, {num_comments_val} comments)" if domain else f"({points} pts, {num_comments_val} comments)"+ else:+ summary = f"HN discussion ({points} pts, {num_comments_val} comments)"++ rank_score = max(0.3, 1.0 - (i * 0.02))+ engagement_boost = min(0.2, math.log1p(points) / 40)+ relevance = min(1.0, rank_score * 0.7 + engagement_boost + 0.1)++ all_items.append(TrackerItem(+ id=f"HN-{object_id}",+ title=title,+ summary=summary,+ entity=entity_name,+ source=SOURCE_HACKERNEWS,+ source_url=article_url or hn_url,+ source_label=f"Hacker News",+ date=date_str,+ date_confidence="high" if date_str else "low",+ raw_text=title,+ engagement=Engagement(points=points, num_comments=num_comments_val),+ relevance=round(relevance, 2),+ ))+ entity_found = True++ if entity_found:+ result.entities_with_updates += 1++ # Enrich top stories with comments+ top_items = sorted(all_items, key=lambda x: x.engagement.points, reverse=True)[:enrich_limit]+ with ThreadPoolExecutor(max_workers=5) as executor:+ futures = {}+ for item in top_items:+ oid = item.id.replace("HN-", "")+ futures[executor.submit(_fetch_comments, oid)] = item+ for future in as_completed(futures):+ item = futures[future]+ try:+ insights = future.result(timeout=15)+ if insights:+ item.summary += "\nKey discussion points: " + "; ".join(insights[:3])+ except Exception:+ pass++ result.items = all_items+ _log(f"Collected {len(all_items)} HN stories from {result.entities_checked} entities")+ return resultdiff --git a/ai_agents/devable_research_agent/lib/http.py b/ai_agents/devable_research_agent/lib/http.pynew file mode 100644index 0000000..7746325--- /dev/null+++ b/ai_agents/devable_research_agent/lib/http.py@@ -0,0 +1,130 @@+"""HTTP utilities for devable-research-agent (stdlib only, adapted from last30days)."""++import json+import os+import sys+import time+import urllib.error+import urllib.request+from contextlib import nullcontext+from typing import Any, Dict, Optional+from urllib.parse import urlencode++from .net import force_ipv4_only, is_ipv6_unreachable++DEFAULT_TIMEOUT = 30+MAX_RETRIES = 5+RETRY_DELAY = 2.0+USER_AGENT = "devable-research-agent/1.0 (AI Industry Tracker)"+DEBUG = os.environ.get("MORNING_AI_DEBUG", "").lower() in ("1", "true", "yes")+++def log(msg: str):+ if DEBUG:+ sys.stderr.write(f"[HTTP] {msg}\n")+ sys.stderr.flush()+++class HTTPError(Exception):+ def __init__(self, message: str, status_code: Optional[int] = None, body: Optional[str] = None):+ super().__init__(message)+ self.status_code = status_code+ self.body = body+++def request(+ method: str,+ url: str,+ headers: Optional[Dict[str, str]] = None,+ json_data: Optional[Dict[str, Any]] = None,+ timeout: int = DEFAULT_TIMEOUT,+ retries: int = MAX_RETRIES,+ raw: bool = False,+) -> Any:+ headers = headers or {}+ headers.setdefault("User-Agent", USER_AGENT)++ data = None+ if json_data is not None:+ data = json.dumps(json_data).encode("utf-8")+ headers.setdefault("Content-Type", "application/json")++ req = urllib.request.Request(url, data=data, headers=headers, method=method)+ log(f"{method} {url}")++ last_error = None+ ipv4_fallback = False+ for attempt in range(retries):+ ctx = force_ipv4_only() if ipv4_fallback else nullcontext()+ try:+ with ctx, urllib.request.urlopen(req, timeout=timeout) as response:+ body = response.read().decode("utf-8")+ log(f"Response: {response.status} ({len(body)} bytes)")+ if raw:+ return body+ return json.loads(body) if body else {}+ except urllib.error.HTTPError as e:+ body = None+ try:+ body = e.read().decode("utf-8")+ except Exception:+ pass+ log(f"HTTP Error {e.code}: {e.reason}")+ last_error = HTTPError(f"HTTP {e.code}: {e.reason}", e.code, body)++ if 400 <= e.code < 500 and e.code != 429:+ raise last_error++ if attempt < retries - 1:+ if e.code == 429:+ retry_after = e.headers.get("Retry-After") if hasattr(e, "headers") else None+ if retry_after:+ try:+ delay = float(retry_after)+ except ValueError:+ delay = RETRY_DELAY * (2 ** attempt) + 1+ else:+ delay = RETRY_DELAY * (2 ** attempt) + 1+ log(f"Rate limited (429). Waiting {delay:.1f}s before retry {attempt + 2}/{retries}")+ else:+ delay = RETRY_DELAY * (2 ** attempt)+ time.sleep(delay)+ except urllib.error.URLError as e:+ log(f"URL Error: {e.reason}")+ last_error = HTTPError(f"URL Error: {e.reason}")+ # Broken IPv6 routing: retry once IPv4-only without burning the backoff.+ if not ipv4_fallback and is_ipv6_unreachable(e):+ log("IPv6 unreachable, switching to IPv4-only DNS for remaining retries")+ ipv4_fallback = True+ continue+ if attempt < retries - 1:+ time.sleep(RETRY_DELAY * (attempt + 1))+ except json.JSONDecodeError as e:+ last_error = HTTPError(f"Invalid JSON response: {e}")+ raise last_error+ except (OSError, TimeoutError, ConnectionResetError) as e:+ log(f"Connection error: {type(e).__name__}: {e}")+ last_error = HTTPError(f"Connection error: {type(e).__name__}: {e}")+ if not ipv4_fallback and is_ipv6_unreachable(e):+ log("IPv6 unreachable, switching to IPv4-only DNS for remaining retries")+ ipv4_fallback = True+ continue+ if attempt < retries - 1:+ time.sleep(RETRY_DELAY * (attempt + 1))++ if last_error:+ raise last_error+ raise HTTPError("Request failed with no error details")+++def get(url: str, headers: Optional[Dict[str, str]] = None, **kwargs) -> Any:+ return request("GET", url, headers=headers, **kwargs)+++def get_text(url: str, headers: Optional[Dict[str, str]] = None, **kwargs) -> str:+ """GET request returning raw text (not parsed as JSON)."""+ return request("GET", url, headers=headers, raw=True, **kwargs)+++def post(url: str, json_data: Dict[str, Any], headers: Optional[Dict[str, str]] = None, **kwargs) -> Any:+ return request("POST", url, headers=headers, json_data=json_data, **kwargs)diff --git a/ai_agents/devable_research_agent/lib/huggingface.py b/ai_agents/devable_research_agent/lib/huggingface.pynew file mode 100644index 0000000..f7cf780--- /dev/null+++ b/ai_agents/devable_research_agent/lib/huggingface.py@@ -0,0 +1,405 @@+"""HuggingFace collector for devable-research-agent.++Monitors model/space/dataset updates via HuggingFace API.+New collector — no last30days equivalent.+"""++import re+import sys+from concurrent.futures import ThreadPoolExecutor, as_completed+from typing import Any, Dict, List, Optional+from urllib.parse import urlencode, quote++from . import http+from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_HUGGINGFACE+from .util import log, parse_date++HF_API = "https://huggingface.co/api"++DEPTH_CONFIG = {"quick": 5, "default": 10, "deep": 20}+++def _format_params(total: int) -> str:+ """Format parameter count to human-readable string (e.g. 31B, 600M)."""+ if total >= 1_000_000_000:+ val = total / 1_000_000_000+ return f"{val:.0f}B" if val == int(val) else f"{val:.1f}B"+ if total >= 1_000_000:+ val = total / 1_000_000+ return f"{val:.0f}M" if val == int(val) else f"{val:.1f}M"+ if total >= 1_000:+ val = total / 1_000+ return f"{val:.0f}K" if val == int(val) else f"{val:.1f}K"+ return str(total)+++def _fetch_model_meta(model_id: str) -> Dict[str, str]:+ """Fetch rich metadata from HuggingFace model API.++ Returns dict with keys: params, arch, license, base_model (all optional).+ """+ url = f"{HF_API}/models/{quote(model_id, safe='/')}"+ try:+ data = http.get(url, timeout=15, retries=1)+ except Exception:+ return {}++ if not isinstance(data, dict):+ return {}++ result: Dict[str, str] = {}++ # Parameter count from safetensors+ safetensors = data.get("safetensors")+ if isinstance(safetensors, dict):+ total = safetensors.get("total")+ if isinstance(total, (int, float)) and total > 0:+ result["params"] = _format_params(int(total))++ # Architecture from config+ config = data.get("config")+ if isinstance(config, dict):+ archs = config.get("architectures")+ if isinstance(archs, list) and archs:+ # "Gemma3ForConditionalGeneration" -> "Gemma3"+ arch = archs[0]+ arch = re.sub(r'(For\w+|LMHead\w*|Model)$', '', arch)+ if arch:+ result["arch"] = arch+ if "arch" not in result:+ model_type = config.get("model_type")+ if model_type:+ result["arch"] = model_type++ # License and base_model from cardData+ card = data.get("cardData")+ if isinstance(card, dict):+ lic = card.get("license")+ if isinstance(lic, str) and lic:+ result["license"] = lic+ base = card.get("base_model")+ if isinstance(base, str) and base:+ result["base_model"] = base+ elif isinstance(base, list) and base:+ result["base_model"] = base[0] if isinstance(base[0], str) else ""++ return result+++def _fetch_model_description(model_id: str) -> str:+ """Fetch model card description from HuggingFace README.++ Fetches the raw README.md and extracts the first meaningful paragraph+ after the YAML frontmatter. Falls back to empty string on failure.+ """+ url = f"https://huggingface.co/{model_id}/raw/main/README.md"+ try:+ text = http.get(url, timeout=10, retries=1, raw=True)+ except Exception:+ return ""++ if not isinstance(text, str) or len(text) < 20:+ return ""++ # Strip YAML frontmatter+ if text.startswith("---"):+ end = text.find("---", 3)+ if end > 0:+ text = text[end + 3:]++ # Find first substantial paragraph (skip blanks, headers, links, badges, emoji lines)+ for line in text.split("\n"):+ line = line.strip()+ if not line:+ continue+ if line.startswith(("#", "|", "[", "!", "<", "-", "*", ">")):+ continue+ if line.startswith("```"):+ break+ # Skip lines starting with emoji (common promotional banners)+ if re.match(r'^[\U0001F000-\U0001FFFF\u2600-\u27BF\u2B50]', line):+ continue+ # Skip short lines and markdown link-only lines+ if len(line) < 50:+ continue+ if re.match(r'^\[.*\]\(.*\)$', line):+ continue+ # Found a real paragraph+ return line[:300]++ return ""+++_log = lambda msg: log("HF", msg, tty_only=True)+++_parse_date = parse_date+++def get_author_models(+ author: str,+ from_date: str,+ to_date: str,+ limit: int = 10,+) -> List[Dict[str, Any]]:+ """Get recent models from an author/org on HuggingFace.++ Args:+ author: HuggingFace username or org (e.g. "meta-llama")+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ limit: Max results++ Returns:+ List of model info dicts+ """+ params = urlencode({+ "author": author,+ "sort": "createdAt",+ "direction": "-1",+ "limit": str(limit),+ })+ url = f"{HF_API}/models?{params}"++ try:+ response = http.get(url, timeout=30)+ except Exception as e:+ _log(f"Failed to fetch models for {author}: {e}")+ return []++ if not isinstance(response, list):+ return []++ models = []+ for model in response:+ created = _parse_date(model.get("createdAt"))+ modified = _parse_date(model.get("lastModified"))+ date = created or modified++ if not date:+ continue++ if not (from_date <= date <= to_date):+ continue++ downloads = model.get("downloads", 0) or 0+ likes = model.get("likes", 0) or 0++ models.append({+ "model_id": model.get("modelId", model.get("id", "")),+ "pipeline_tag": model.get("pipeline_tag", ""),+ "tags": model.get("tags", []),+ "downloads": downloads,+ "likes": likes,+ "date": date,+ "created": created,+ "modified": modified,+ "url": f"https://huggingface.co/{model.get('modelId', model.get('id', ''))}",+ "private": model.get("private", False),+ "library_name": model.get("library_name", ""),+ })++ _log(f"{author}: {len(models)} models in date range")+ return models+++def get_trending_models(+ limit: int = 20,+) -> List[Dict[str, Any]]:+ """Get trending models from HuggingFace."""+ params = urlencode({+ "sort": "trending",+ "direction": "-1",+ "limit": str(limit),+ })+ url = f"{HF_API}/models?{params}"++ try:+ response = http.get(url, timeout=30)+ except Exception as e:+ _log(f"Failed to fetch trending models: {e}")+ return []++ if not isinstance(response, list):+ return []+ return response+++def search_models(+ query: str,+ from_date: str,+ to_date: str,+ limit: int = 10,+) -> List[Dict[str, Any]]:+ """Search for models by keyword."""+ params = urlencode({+ "search": query,+ "sort": "createdAt",+ "direction": "-1",+ "limit": str(limit),+ })+ url = f"{HF_API}/models?{params}"++ try:+ response = http.get(url, timeout=30)+ except Exception as e:+ _log(f"Model search '{query}' failed: {e}")+ return []++ if not isinstance(response, list):+ return []++ models = []+ for model in response:+ created = _parse_date(model.get("createdAt"))+ modified = _parse_date(model.get("lastModified"))+ date = created or modified+ if date and (date < from_date or date > to_date):+ continue+ models.append(model)++ return models+++def collect(+ entities: Dict[str, List[str]],+ from_date: str,+ to_date: str,+ depth: str = "default",+) -> CollectionResult:+ """Collect HuggingFace model updates for tracked entities.++ Args:+ entities: Dict mapping entity name -> list of HF author/org names+ e.g. {"Meta AI": ["meta-llama"], "Google": ["google"]}+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ depth: Search depth++ Returns:+ CollectionResult+ """+ result = CollectionResult(source=SOURCE_HUGGINGFACE)+ all_items = []+ limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])++ for entity_name, hf_authors in entities.items():+ result.entities_checked += 1+ entity_found = False++ for author in hf_authors:+ models = get_author_models(author, from_date, to_date, limit)++ for model in models:+ model_id = model.get("model_id", "")+ pipeline = model.get("pipeline_tag", "")+ downloads = model.get("downloads", 0)+ likes = model.get("likes", 0)+ tags = model.get("tags", [])++ # Metadata fallback summary+ tag_str = ", ".join(tags[:5]) if tags else ""+ meta_parts = []+ if pipeline:+ meta_parts.append(f"Pipeline: {pipeline}")+ if downloads:+ meta_parts.append(f"{downloads:,} downloads")+ if likes:+ meta_parts.append(f"{likes} likes")+ if tag_str:+ meta_parts.append(f"Tags: {tag_str}")+ fallback_summary = " | ".join(meta_parts) if meta_parts else model_id++ all_items.append(TrackerItem(+ id=f"HF-{model_id}",+ title=model_id,+ summary=fallback_summary,+ entity=entity_name,+ source=SOURCE_HUGGINGFACE,+ source_url=model.get("url", f"https://huggingface.co/{model_id}"),+ source_label=f"HuggingFace {author}",+ date=model.get("date"),+ date_confidence="high" if model.get("date") else "low",+ raw_text=model_id,+ engagement=Engagement(+ likes=likes,+ views=downloads,+ ),+ relevance=min(1.0, 0.5 + min(0.5, (downloads / 10000 + likes / 100))),+ ))+ entity_found = True++ if entity_found:+ result.entities_with_updates += 1++ # Enrich summaries with model card descriptions + technical metadata (concurrent)+ if all_items:+ _log(f"Fetching model details for {len(all_items)} models...")+ with ThreadPoolExecutor(max_workers=5) as executor:+ desc_futures = {+ executor.submit(_fetch_model_description, item.title): ("desc", item)+ for item in all_items+ }+ meta_futures = {+ executor.submit(_fetch_model_meta, item.title): ("meta", item)+ for item in all_items+ }++ # Collect results keyed by item id+ descriptions: Dict[str, str] = {}+ metas: Dict[str, Dict[str, str]] = {}++ for future in as_completed({**desc_futures, **meta_futures}):+ if future in desc_futures:+ _, item = desc_futures[future]+ try:+ descriptions[item.id] = future.result(timeout=20)+ except Exception:+ pass+ else:+ _, item = meta_futures[future]+ try:+ metas[item.id] = future.result(timeout=20)+ except Exception:+ pass++ # Build enriched summaries+ for item in all_items:+ desc = descriptions.get(item.id, "")+ model_meta = metas.get(item.id, {})++ # Technical specs+ specs = []+ if model_meta.get("params"):+ specs.append(f"{model_meta['params']} params")+ if model_meta.get("arch"):+ specs.append(f"{model_meta['arch']} architecture")+ if model_meta.get("base_model"):+ specs.append(f"based on {model_meta['base_model']}")+ if model_meta.get("license"):+ specs.append(model_meta["license"])+ spec_str = ", ".join(specs)++ # Engagement metrics+ metrics = []+ if item.engagement.views:+ metrics.append(f"{item.engagement.views:,} downloads")+ if item.engagement.likes:+ metrics.append(f"{item.engagement.likes} likes")+ metric_str = " | ".join(metrics)++ # Assemble: description + specs + metrics+ parts = []+ if desc:+ parts.append(desc[:200])+ if spec_str:+ parts.append(spec_str)+ if metric_str:+ parts.append(metric_str)++ if parts:+ item.summary = ". ".join(parts)++ result.items = all_items+ _log(f"Collected {len(all_items)} HF models from {result.entities_checked} entities")+ return resultdiff --git a/ai_agents/devable_research_agent/lib/net.py b/ai_agents/devable_research_agent/lib/net.pynew file mode 100644index 0000000..8e1080c--- /dev/null+++ b/ai_agents/devable_research_agent/lib/net.py@@ -0,0 +1,61 @@+"""Network helpers — IPv4-only DNS fallback for broken-IPv6 environments.++Some hosts have a working IPv4 path but resolve AAAA records that route to a+black hole (the kernel reports `OSError(errno=101, ENETUNREACH)` once it tries+to connect). The Python stdlib happily prefers the IPv6 record returned by+`socket.getaddrinfo`, so any blocking I/O fails before we get a chance to fall+back to IPv4.++This module exposes:++- `is_ipv6_unreachable(exc)` — recognise that error class+- `force_ipv4_only()` — context manager that monkey-patches+ `socket.getaddrinfo` to return only AF_INET addresses, restored on exit++Typical usage::++ try:+ do_network_call()+ except OSError as e:+ if not is_ipv6_unreachable(e):+ raise+ with force_ipv4_only():+ do_network_call()+"""++import socket+from contextlib import contextmanager+from typing import Iterator+++def is_ipv6_unreachable(exc: BaseException) -> bool:+ """True if exc is an OSError with errno 101 (ENETUNREACH).++ Also unwraps `urllib.error.URLError`, whose `.reason` attribute carries the+ underlying `OSError` for connection failures.+ """+ if isinstance(exc, OSError) and getattr(exc, "errno", None) == 101:+ return True+ reason = getattr(exc, "reason", None)+ if isinstance(reason, OSError) and getattr(reason, "errno", None) == 101:+ return True+ return False+++@contextmanager+def force_ipv4_only() -> Iterator[None]:+ """Monkey-patch `socket.getaddrinfo` to return only AF_INET (IPv4) entries.++ Restored on exit. Not thread-safe — but neither is the underlying problem,+ and the collectors that need this are short-lived per-source futures.+ """+ original = socket.getaddrinfo++ def _v4_only(host, port, family=0, *args, **kwargs):+ return original(host, port, socket.AF_INET, *args, **kwargs)++ socket.getaddrinfo = _v4_only+ try:+ yield+ finally:+ socket.getaddrinfo = originaldiff --git a/ai_agents/devable_research_agent/lib/schema.py b/ai_agents/devable_research_agent/lib/schema.pynew file mode 100644index 0000000..ed08973--- /dev/null+++ b/ai_agents/devable_research_agent/lib/schema.py@@ -0,0 +1,162 @@+"""Data schema for devable-research-agent items."""++from dataclasses import dataclass, field+from typing import Any, Dict, List, Optional+++# AI Tracker content types (matching config.yaml)+TYPE_PRODUCT = "product"+TYPE_MODEL = "model"+TYPE_BENCHMARK = "benchmark"+TYPE_FINANCING = "financing"++VALID_TYPES = {TYPE_PRODUCT, TYPE_MODEL, TYPE_BENCHMARK, TYPE_FINANCING}++# Data source identifiers+SOURCE_X = "x"+SOURCE_REDDIT = "reddit"+SOURCE_HACKERNEWS = "hackernews"+SOURCE_GITHUB = "github"+SOURCE_HUGGINGFACE = "huggingface"+SOURCE_ARXIV = "arxiv"+SOURCE_WEB = "web"+SOURCE_REPO = "repo"+++@dataclass+class Engagement:+ """Platform-specific engagement metrics."""+ # X/Twitter+ likes: int = 0+ reposts: int = 0+ replies: int = 0+ quotes: int = 0+ score: int = 0+ num_comments: int = 0+ upvote_ratio: float = 0.0+ # YouTube / HN+ views: int = 0+ points: int = 0+ # GitHub+ stars: int = 0+ forks: int = 0+ # General+ total: int = 0++ def to_dict(self) -> Dict[str, Any]:+ d = {}+ for k, v in self.__dict__.items():+ if v:+ d[k] = v+ return d++ @classmethod+ def from_dict(cls, d: Dict[str, Any]) -> "Engagement":+ return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})+++@dataclass+class TrackerItem:+ """A single tracked update from any source."""+ id: str = ""+ title: str = ""+ summary: str = ""+ entity: str = "" # tracked entity name, e.g. "OpenAI", "Anthropic"+ content_type: str = "" # product | model | benchmark | financing+ source: str = "" # x | reddit | hackernews | github | huggingface | arxiv | web | repo+ source_url: str = ""+ source_label: str = "" # human-readable source, e.g. "@OpenAI on X"+ date: Optional[str] = None # YYYY-MM-DD+ date_confidence: str = "low" # high | med | low+ raw_text: str = ""+ engagement: Engagement = field(default_factory=Engagement)+ relevance: float = 0.0 # 0-1 from collector+ importance: float = 0.0 # 1-10 devable-research-agent scale (set by scoring)+ cross_refs: List[str] = field(default_factory=list)+ verified: bool = False+ verify_sources: List[str] = field(default_factory=list)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "id": self.id,+ "title": self.title,+ "summary": self.summary,+ "entity": self.entity,+ "content_type": self.content_type,+ "source": self.source,+ "source_url": self.source_url,+ "source_label": self.source_label,+ "date": self.date,+ "date_confidence": self.date_confidence,+ "raw_text": self.raw_text,+ "engagement": self.engagement.to_dict(),+ "relevance": self.relevance,+ "importance": self.importance,+ "cross_refs": self.cross_refs,+ "verified": self.verified,+ "verify_sources": self.verify_sources,+ }++ @classmethod+ def from_dict(cls, d: Dict[str, Any]) -> "TrackerItem":+ engagement = Engagement.from_dict(d.get("engagement", {}))+ return cls(+ id=d.get("id", ""),+ title=d.get("title", ""),+ summary=d.get("summary", ""),+ entity=d.get("entity", ""),+ content_type=d.get("content_type", ""),+ source=d.get("source", ""),+ source_url=d.get("source_url", ""),+ source_label=d.get("source_label", ""),+ date=d.get("date"),+ date_confidence=d.get("date_confidence", "low"),+ raw_text=d.get("raw_text", ""),+ engagement=engagement,+ relevance=d.get("relevance", 0.0),+ importance=d.get("importance", 0.0),+ cross_refs=d.get("cross_refs", []),+ verified=d.get("verified", False),+ verify_sources=d.get("verify_sources", []),+ )+++@dataclass+class CollectionResult:+ """Result from a single collector run."""+ source: str+ items: List[TrackerItem] = field(default_factory=list)+ errors: List[str] = field(default_factory=list)+ entities_checked: int = 0+ entities_with_updates: int = 0++ def to_dict(self) -> Dict[str, Any]:+ return {+ "source": self.source,+ "items": [item.to_dict() for item in self.items],+ "errors": self.errors,+ "entities_checked": self.entities_checked,+ "entities_with_updates": self.entities_with_updates,+ }+++@dataclass+class DailyReport:+ """Aggregated daily report from all sources."""+ date: str = ""+ time_window: str = "" # e.g. "2026-04-02 08:00 ~ 2026-04-03 08:00 UTC+8"+ generated_at: str = ""+ items: List[TrackerItem] = field(default_factory=list)+ collection_results: List[CollectionResult] = field(default_factory=list)+ stats: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "date": self.date,+ "time_window": self.time_window,+ "generated_at": self.generated_at,+ "items": [item.to_dict() for item in self.items],+ "collection_results": [r.to_dict() for r in self.collection_results],+ "stats": self.stats,+ }diff --git a/ai_agents/devable_research_agent/lib/score.py b/ai_agents/devable_research_agent/lib/score.pynew file mode 100644index 0000000..df43288--- /dev/null+++ b/ai_agents/devable_research_agent/lib/score.py@@ -0,0 +1,196 @@+"""Scoring module for devable-research-agent.++Maps collector relevance scores to devable-research-agent's 1-10 importance scale.+Combines engagement, source reliability, and content relevance.+Adapted from last30days score.py composite scoring approach.+"""++import bisect+import math+from typing import List++from .schema import TrackerItem, SOURCE_X, SOURCE_GITHUB, SOURCE_HUGGINGFACE, SOURCE_ARXIV, SOURCE_WEB, SOURCE_REPO, SOURCE_REDDIT, SOURCE_HACKERNEWS++# Source reliability weights (official sources > community)+SOURCE_RELIABILITY = {+ SOURCE_GITHUB: 0.9,+ SOURCE_REPO: 0.85,+ SOURCE_HUGGINGFACE: 0.85,+ SOURCE_ARXIV: 0.8,+ SOURCE_WEB: 0.7,+ SOURCE_X: 0.65,+ SOURCE_REDDIT: 0.5,+ SOURCE_HACKERNEWS: 0.55,+}++# Scoring component weights — Stage 1 automated scoring dimensions.+# These are computable from collector metadata (not the same as the+# 5-dimension agent evaluation criteria in tracking-list/SKILL.md).+WEIGHT_RELEVANCE = 0.35+WEIGHT_ENGAGEMENT = 0.30+WEIGHT_SOURCE_RELIABILITY = 0.20+WEIGHT_RECENCY = 0.15+++def _compute_engagement_score(item: TrackerItem) -> float:+ """Compute normalized engagement score (0-1) based on source type."""+ eng = item.engagement++ if item.source == SOURCE_X:+ raw = (+ 0.55 * math.log1p(eng.likes)+ + 0.25 * math.log1p(eng.reposts)+ + 0.15 * math.log1p(eng.replies)+ + 0.05 * math.log1p(eng.quotes)+ )+ return min(1.0, raw / 10.0)++ elif item.source == SOURCE_REDDIT:+ raw = (+ 0.55 * math.log1p(eng.score)+ + 0.45 * math.log1p(eng.num_comments)+ )+ return min(1.0, raw / 6.0)++ elif item.source == SOURCE_HACKERNEWS:+ raw = (+ 0.55 * math.log1p(eng.points)+ + 0.45 * math.log1p(eng.num_comments)+ )+ return min(1.0, raw / 6.0)++ elif item.source == SOURCE_GITHUB:+ if "Trending" in (item.source_label or ""):+ # Trending repos: star surge IS the story+ raw = (+ 0.60 * math.log1p(eng.stars)+ + 0.40 * math.log1p(eng.forks)+ )+ return min(1.0, raw / 7.0)+ else:+ # Tracked-entity releases: repo lifetime stars ≠ release+ # significance. Use flat moderate engagement so relevance+ # and source reliability drive the score instead.+ return 0.35++ elif item.source == SOURCE_HUGGINGFACE:+ raw = (+ 0.50 * math.log1p(eng.views) # downloads+ + 0.50 * math.log1p(eng.likes)+ )+ return min(1.0, raw / 8.0)++ elif item.source == SOURCE_ARXIV:+ # Variable score based on author count (proxy for lab size/importance)+ author_boost = min(0.2, eng.total * 0.02) if eng.total else 0+ return 0.4 + author_boost++ elif item.source == SOURCE_WEB:+ return 0.4 # web search results have limited engagement info++ elif item.source == SOURCE_REPO:+ raw = (+ 0.55 * math.log1p(eng.stars)+ + 0.45 * math.log1p(max(0, eng.total))+ )+ return min(1.0, raw / 7.0)++ return 0.3+++def _compute_recency_score(item: TrackerItem) -> float:+ """Score based on date confidence."""+ if item.date_confidence == "high":+ return 1.0+ elif item.date_confidence == "med":+ return 0.7+ return 0.4+++def score_item(item: TrackerItem) -> float:+ """Compute importance score for a single item on 1-10 scale.++ Combines:+ - Relevance (from collector): 35%+ - Engagement (platform-specific): 30%+ - Source reliability: 20%+ - Recency confidence: 15%++ Returns:+ Score from 1.0 to 10.0+ """+ relevance = item.relevance+ engagement = _compute_engagement_score(item)+ reliability = SOURCE_RELIABILITY.get(item.source, 0.5)+ recency = _compute_recency_score(item)++ composite = (+ WEIGHT_RELEVANCE * relevance+ + WEIGHT_ENGAGEMENT * engagement+ + WEIGHT_SOURCE_RELIABILITY * reliability+ + WEIGHT_RECENCY * recency+ )++ # Map 0-1 composite to 1-10 scale+ score = max(1.0, min(10.0, composite * 10.0))+ return round(score, 1)+++def score_items(items: List[TrackerItem]) -> List[TrackerItem]:+ """Score all items and sort by importance descending.++ Args:+ items: List of TrackerItem to score++ Returns:+ Same items with importance field set, sorted by importance desc+ """+ for item in items:+ item.importance = score_item(item)++ # Rescale scores using percentile mapping for better distribution+ _rescale_scores(items)++ items.sort(key=lambda x: x.importance, reverse=True)+ return items+++def _rescale_scores(items: List[TrackerItem]) -> None:+ """Rescale scores to spread across 2.0-9.5 range using percentiles.++ Preserves relative ordering while ensuring scores use the full range+ instead of clustering around 5-7.+ """+ if len(items) < 5:+ return++ scores = sorted(i.importance for i in items)+ n = len(scores)+ for item in items:+ pct = bisect.bisect_left(scores, item.importance) / n+ item.importance = round(2.0 + pct * 7.5, 1)+++def apply_verification_bonus(items: List[TrackerItem]) -> List[TrackerItem]:+ """Apply cross-verification bonus per devable-research-agent rules.++ Items with 2+ cross-references get a verification bonus.+ Items scoring 7+ with <2 independent sources get a penalty.++ Args:+ items: Pre-scored items with cross_refs populated++ Returns:+ Items with adjusted importance scores+ """+ for item in items:+ num_refs = len(item.cross_refs)++ if num_refs >= 2:+ item.verified = True+ item.importance = min(10.0, item.importance + 0.5)+ else:+ item.verified = False++ items.sort(key=lambda x: x.importance, reverse=True)+ return itemsdiff --git a/ai_agents/devable_research_agent/lib/tavily_collector.py b/ai_agents/devable_research_agent/lib/tavily_collector.pynew file mode 100644index 0000000..1750a15--- /dev/null+++ b/ai_agents/devable_research_agent/lib/tavily_collector.py@@ -0,0 +1,279 @@+"""Tavily web search collector for devable-research-agent.++Uses the Tavily Search API to find general web signals:++1. Entity ``web_queries`` from the entity registry (site: queries, etc.)+2. Fallback entity news queries for tracked entities without explicit web queries+3. High-signal release/announcement discovery queries++X/Twitter handle searches were removed — AINews RSS covers X signals.++Requires ``tavily-python`` and ``TAVILY_API_KEY`` in config or environment.+"""++import hashlib+import re+from concurrent.futures import ThreadPoolExecutor, as_completed+from typing import Any, Dict, List, Optional, Tuple++try:+ from tavily import TavilyClient+ _HAS_TAVILY = True+except ImportError:+ TavilyClient = None # type: ignore[misc, assignment]+ _HAS_TAVILY = False++from .schema import TrackerItem, Engagement, CollectionResult, SOURCE_WEB+from .util import log, parse_date++TAVILY_SEARCH_DEPTH = {"quick": "basic", "default": "advanced", "deep": "advanced"}+MAX_RESULTS = {"quick": 5, "default": 8, "deep": 10}+DEPTH_WEB_ENTITIES = {"quick": 15, "default": 35, "deep": 60}+MAX_WORKERS = 4++# Release-focused AI engineering discovery queries (not news commentary)+HIGH_SIGNAL_WEB_QUERIES = [+ "site:news.smol.ai AI engineering signals",+ "new open source LLM model released this week site:huggingface.co",+ "new AI agent framework released github this week",+ "open source model weights released arxiv 2026",+ "new LLM inference engine released open source",+ "new open source benchmark released AI engineering",+ "AI tool release announcement github 2026",+ "open weight model released this week",+ "new multimodal model open source released",+ "new open source coding agent released",+ "new RAG framework released open source",+]+HIGH_SIGNAL_ENTITY = "AI Engineering Web"++# Skip low-signal results (mirrors HN noise filtering spirit)+NOISE_PATTERNS = [+ r"(?i)\b(opinion|hot take|rant|thread)\b",+ r"(?i)\b(hiring|we're hiring|job opening)\b",+ r"(?i)\bjust shipped a (bug|patch) fix\b",+]++_log = lambda msg: log("Tavily", msg, tty_only=True)+++def _url_id(url: str) -> str:+ digest = hashlib.md5(url.encode("utf-8")).hexdigest()[:12]+ return f"WEB-{digest}"+++def _is_noise(title: str, content: str = "") -> bool:+ text = f"{title} {content}"+ for pat in NOISE_PATTERNS:+ if re.search(pat, text):+ return True+ return False+++def _compute_relevance(tavily_score: Optional[float], rank: int) -> float:+ """Blend Tavily relevance score with result rank position."""+ rank_score = max(0.3, 1.0 - (rank * 0.03))+ score_part = min(1.0, float(tavily_score or 0.5))+ relevance = min(1.0, rank_score * 0.45 + score_part * 0.45 + 0.1)+ return round(relevance, 2)+++def _build_entity_news_query(entity_name: str) -> str:+ return (+ f'"{entity_name}" AI '+ "(model release OR framework OR agent OR benchmark OR open source)"+ )+++def build_web_tasks(+ web_queries: Dict[str, List[str]],+ entity_names: List[str],+ depth: str = "default",+) -> List[Tuple[str, str]]:+ """Build the Tavily web query task list (entity, query) pairs."""+ web_entity_cap = DEPTH_WEB_ENTITIES.get(depth, DEPTH_WEB_ENTITIES["default"])+ web_tasks: List[Tuple[str, str]] = []++ for entity_name in list(web_queries.keys())[:web_entity_cap]:+ for query in web_queries.get(entity_name, []):+ if query.strip():+ web_tasks.append((entity_name, query.strip()))++ for entity_name in entity_names[:web_entity_cap]:+ if entity_name not in web_queries:+ web_tasks.append((entity_name, _build_entity_news_query(entity_name)))++ for query in HIGH_SIGNAL_WEB_QUERIES:+ web_tasks.append((HIGH_SIGNAL_ENTITY, query))++ return web_tasks+++def search(+ client: Any,+ query: str,+ from_date: str,+ to_date: str,+ depth: str = "default",+ *,+ topic: str = "news",+ include_domains: Optional[List[str]] = None,+) -> List[Dict[str, Any]]:+ """Run a single Tavily search and return normalized hit dicts."""+ max_results = MAX_RESULTS.get(depth, MAX_RESULTS["default"])+ search_depth = TAVILY_SEARCH_DEPTH.get(depth, TAVILY_SEARCH_DEPTH["default"])++ try:+ response = client.search(+ query=query,+ search_depth=search_depth,+ topic=topic,+ start_date=from_date,+ end_date=to_date,+ max_results=max_results,+ include_domains=include_domains,+ timeout=60,+ )+ except Exception as e:+ _log(f"Search failed for '{query[:80]}': {e}")+ return []++ return response.get("results", []) or []+++def _hit_to_item(+ hit: Dict[str, Any],+ entity: str,+ rank: int,+ *,+ source_label: str,+) -> Optional[TrackerItem]:+ url = (hit.get("url") or "").strip()+ title = (hit.get("title") or "").strip()+ content = (hit.get("content") or "").strip()++ if not url or not title:+ return None++ if _is_noise(title, content):+ return None++ date_str = parse_date(hit.get("published_date"))+ summary = content[:300] if content else title[:300]+ tavily_score = hit.get("score")++ return TrackerItem(+ id=_url_id(url),+ title=title,+ summary=summary,+ entity=entity,+ source=SOURCE_WEB,+ source_url=url,+ source_label=source_label,+ date=date_str,+ date_confidence="high" if date_str else "med",+ raw_text=content or title,+ engagement=Engagement(),+ relevance=_compute_relevance(tavily_score, rank),+ )+++def _search_web_query(+ client: Any,+ entity: str,+ query: str,+ from_date: str,+ to_date: str,+ depth: str,+) -> List[TrackerItem]:+ hits = search(client, query, from_date, to_date, depth, topic="news")++ items: List[TrackerItem] = []+ for i, hit in enumerate(hits):+ item = _hit_to_item(+ hit,+ entity,+ i,+ source_label="Tavily",+ )+ if item:+ items.append(item)++ _log(f"Web '{query[:60]}' ({entity}): {len(items)} items")+ return items+++def collect(+ x_handles_official: Dict[str, List[str]],+ x_handles_key_people: Dict[str, List[str]],+ web_queries: Dict[str, List[str]],+ from_date: str,+ to_date: str,+ api_key: Optional[str] = None,+ depth: str = "default",+ x_handles_kol: Optional[Dict[str, List[str]]] = None,+) -> CollectionResult:+ """Collect AI news signals via Tavily Search.++ Args:+ x_handles_official: Unused (kept for collect.py API compatibility)+ x_handles_key_people: Unused (kept for collect.py API compatibility)+ web_queries: Entity -> web search queries (site: queries, etc.)+ from_date: Start date YYYY-MM-DD+ to_date: End date YYYY-MM-DD+ api_key: Tavily API key+ depth: quick | default | deep+ x_handles_kol: Unused (kept for collect.py API compatibility)++ Returns:+ CollectionResult with source=web+ """+ result = CollectionResult(source=SOURCE_WEB)++ if not _HAS_TAVILY:+ result.errors.append("tavily-python not installed — run: pip install tavily-python")+ return result++ if not api_key:+ result.errors.append("TAVILY_API_KEY not configured")+ return result++ client = TavilyClient(api_key=api_key)+ all_items: List[TrackerItem] = []+ seen_urls: set = set()++ tracked_entities = sorted(+ set(web_queries)+ | set(x_handles_official)+ | set(x_handles_key_people)+ | (set(x_handles_kol) if x_handles_kol else set())+ )+ result.entities_checked = len(tracked_entities)++ web_tasks = build_web_tasks(web_queries, tracked_entities, depth)++ entities_with_updates: set = set()+ if web_tasks:+ with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:+ futures = {+ pool.submit(_search_web_query, client, entity, query, from_date, to_date, depth): (entity, query)+ for entity, query in web_tasks+ }+ for future in as_completed(futures):+ entity, query = futures[future]+ try:+ items = future.result()+ except Exception as e:+ result.errors.append(f"Web search '{query[:40]}': {e}")+ 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(entity)++ result.entities_with_updates = len(entities_with_updates)+ result.items = all_items+ _log(f"Collected {len(all_items)} Tavily items ({len(web_tasks)} web queries)")+ return resultdiff --git a/ai_agents/devable_research_agent/lib/util.py b/ai_agents/devable_research_agent/lib/util.pynew file mode 100644index 0000000..02bf451--- /dev/null+++ b/ai_agents/devable_research_agent/lib/util.py@@ -0,0 +1,17 @@+import sys+from typing import Optional+++def log(tag: str, msg: str, *, tty_only: bool = False) -> None:+ if tty_only and not sys.stderr.isatty():+ return+ sys.stderr.write(f"[{tag}] {msg}\n")+ sys.stderr.flush()+++def parse_date(date_str: Optional[str]) -> Optional[str]:+ if not date_str:+ return None+ if len(date_str) >= 10:+ return date_str[:10]+ return Nonediff --git a/ai_agents/devable_research_agent/logs/.gitkeep b/ai_agents/devable_research_agent/logs/.gitkeepnew file mode 100644index 0000000..8b13789--- /dev/null+++ b/ai_agents/devable_research_agent/logs/.gitkeep@@ -0,0 +1 @@+diff --git a/ai_agents/devable_research_agent/scripts/filter_top_items.py b/ai_agents/devable_research_agent/scripts/filter_top_items.pynew file mode 100644index 0000000..f3c73d2--- /dev/null+++ b/ai_agents/devable_research_agent/scripts/filter_top_items.py@@ -0,0 +1,1942 @@+#!/usr/bin/env python3+"""+Filter top scored items from the daily collection JSON.+Outputs a smaller JSON file with only the top N items for digest generation.++Applies category diversity quotas so the digest is not dominated by a single source.+"""++import argparse+import json+import os+import re+import sys+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++try:+ from mistralai.client import Mistral++ _HAS_MISTRAL = True+except ImportError:+ _HAS_MISTRAL = False++MORNING_AI_ENV_FILE = Path.home() / ".config" / "morning-ai" / ".env"+PROJECT_ROOT = Path(__file__).resolve().parent.parent+DELIVERED_ITEMS_PATH = PROJECT_ROOT / "logs" / "delivered_items.json"+DEFAULT_DELIVERED_LOOKBACK_DAYS = 7+GITHUB_REPO_DELIVERED_LOOKBACK_DAYS = 14+REPO_FREQUENCY_CAP = 2+REPO_FREQUENCY_LOOKBACK_DAYS = 30+VERIFY_MEMORY_LOOKBACK_DAYS = 14+TZ_CN = timezone(timedelta(hours=8))++# Per-source date cutoffs for stale-item filtering+SOURCE_DATE_CUTOFF_HOURS = {+ "arxiv": 72,+ "github": 48,+ "web": 48,+ "huggingface": 72,+ "x": 72,+}+SOURCE_DATE_CUTOFF_DAYS = {+ "repo": 7,+}+DEFAULT_DATE_CUTOFF_HOURS = 48++PAPER_LLM_MODEL = "mistral-small-latest"+VERIFY_LLM_MODEL = "mistral-small-latest"+MIN_PAPER_LLM_SCORE = 5+FAILED_PAPER_LLM_SCORE = 3+PAPER_LLM_MAX_WORKERS = 8++_PAPER_LLM_SYSTEM = (+ "You are an editor for an AI engineering newsletter for developers who "+ "build with LLMs and agents. Score paper relevance strictly."+)++_PAPER_LLM_USER_TEMPLATE = """Score this paper's relevance to AI engineers who build, train, or deploy AI systems. Reply with ONLY a single digit 1-5.++5 = core AI engineering: LLMs, agents, reasoning, inference, fine-tuning, benchmarks, RAG, tool use, multimodal models+4 = strong engineering value: new techniques builders can use today+3 = tangentially related: uses AI but not about building AI systems+2 = domain application of AI: medical, legal, social, scientific+1 = not relevant: math, music, networking, other domains++Title: {title}+Summary: {summary}"""++_VERIFY_LLM_SYSTEM = (+ "You are an editorial verifier for an AI engineering digest. "+ "Return only a JSON array — no prose, no markdown fences."+)++_VERIFY_LLM_USER_TEMPLATE = """You are an editorial verifier for an AI engineering digest.++Here are the items selected for today's digest:+{top_items_json}++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++Return only the filtered list as a JSON array with the same structure. Be strict. Remove duplicates ruthlessly."""++# 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},+ "huggingface": {"min": 0, "max": 2},+ "good_ai_list": {"min": 8, "max": 12},+}++GOOD_AI_LIST_IMPORTANCE_BOOST = 2.0++_paper_llm_scores: Dict[str, int] = {}+_MISTRAL_CLIENT: "Mistral | None" = None++_HF_INCLUDE_KEYWORDS = [+ "llm",+ "language model",+ "agent",+ "reasoning",+ "inference",+ "embedding",+ "multimodal",+ "code",+ "text generation",+ "vision",+ "audio",+]++_HF_SKIP_KEYWORDS = [+ "molecular docking",+ "docking",+ "diffdock",+ "chemistry",+ "biology",+ "medical imaging",+ "protein",+ "molecule",+ "chemoinformatics",+]++_GITHUB_MAINTENANCE_KEYWORDS = [+ "migrate ci",+ "bump",+ "chore",+ "relicense",+ "dependency update",+ "fix typo",+ "shell expansion",+ "removed shell",+ "remove shell",+ "minor fix",+ "cleanup",+ "refactor",+ "remove unused",+ "update readme",+ "documentation",+ "updated bundled",+ "bundled claude cli",+ "updated to parity",+ "fixed hook events",+]++_GITHUB_FEATURE_KEYWORDS = [+ "new feature",+ "new capability",+ "capability",+ "capabilities",+ "improvement",+ "improve",+ "introduce",+ "introduces",+ "adds support",+ "add support",+ "now supports",+ "enable",+ "enables",+ "performance",+ "faster",+ "benchmark",+ "launch",+ "announce",+ "new api",+ "breaking change",+]++# Claude Agent SDK parity releases — wiring/stream-json sync, not product news.+_SDK_SYNC_KEYWORDS = [+ "updated bundled",+ "bundled claude cli",+ "updated to parity",+ "command_lifecycle",+ "duration_api_ms",+ "stream-json",+]++# Skip fix-heavy patch releases only when Added/Improved bullets lack major capability.+_MAJOR_RELEASE_CAPABILITY_KEYWORDS = [+ "new api",+ "breaking change",+ "launch",+ "benchmark",+ "agent framework",+ "mcp server",+ "multi-agent",+ "openapi",+]++# GitHub Trending only — finance/trading repos are not AI engineering news.+_GITHUB_TRENDING_FINANCE_KEYWORDS = [+ "stock",+ "trading",+ "forex",+ "crypto trading",+ "investment",+]++# GitHub Trending only — Devable Research Agent ecosystem plugin repos should not surface.+_GITHUB_TRENDING_PLUGIN_KEYWORDS = [+ "devable-research-agent skill",+ "last30days",+ "tracking-list skill",+]++# Thin commercial-AI plugin wrappers (not novel engineering).+_GITHUB_LOW_SIGNAL_PLUGIN_KEYWORDS = [+ "codex-plugin",+ "plugin-cc",+ "claude-plugin",+ "claude code plugin",+ "use codex from claude",+]++# GitHub Trending — must signal AI engineering in name or description.+_GITHUB_TRENDING_AI_KEYWORDS = [+ "llm",+ "ai",+ "agent",+ "model",+ "inference",+ "embedding",+ "rag",+ "fine-tune",+ "finetune",+ "transformer",+ "diffusion",+ "neural",+ "gpt",+ "claude",+ "llama",+ "mistral",+ "deepseek",+ "qwen",+ "benchmark",+ "eval",+ "prompt",+ "skill",+ "mcp",+ "open source ai",+ "machine learning",+ "deep learning",+]++# GitHub Trending only — offensive-security cheat-sheet launchers, not AI engineering.+_GITHUB_TRENDING_CYBERSECURITY_PHRASES = [+ "cybersecurity cheat-sheet",+ "penetration testing",+ "just install and start hacking",+]++# Explicit owner/repo blocklist (GitHub Trending + Good AI List).+_REPO_BLOCKLIST = {+ "alibaba/page-agent",+ "jcodesmore/ai-website-cloner-template",+ "xbtlin/ai-berkshire",+ "synthetic-sciences/openscience",+ "heygen-com/hyperframes",+ "isjiamu/gzh-design-skill",+}++# Skip repos whose primary purpose is cloning, generic scraping, or standalone browser automation.+_REPO_WEBSITE_CLONER_KEYWORDS = [+ "website cloner",+ "clone any website",+ "site cloner",+ "website-cloner",+ "ai-website-cloner",+ "clone website",+ "replicate website",+ "website replication",+ "website cloner template",+]++_REPO_GENERIC_SCRAPING_KEYWORDS = [+ "web scraper",+ "web scraping",+ "scrape websites",+ "scraping tool",+ "scrape the web",+ "website crawler",+ "crawl the web",+ "crawl websites",+]++_REPO_BROWSER_AUTOMATION_KEYWORDS = [+ "browser automation",+ "automate your browser",+ "headless browser",+ "browser control",+ "browser agent",+ "puppeteer",+ "playwright automation",+ "selenium automation",+]++# Scraping/automation is OK when clearly part of an AI agent framework.+_REPO_AI_AGENT_FRAMEWORK_SIGNALS = [+ "ai agent",+ "coding agent",+ "agent framework",+ "agent workflow",+ "llm",+ "language model",+ "mcp",+ "rag",+ "agent skill",+ "agent tool",+ "for agents",+ "agent-ready",+]++_WEB_SKIP_KEYWORDS = [+ "legal",+ "law firm",+ "harvey",+ "compliance",+ "healthcare",+ "climate",+ "environment",+ "drone",+ "satellite",+ "agriculture",+ "music",+ "suno",+ "raises $",+ "funding round",+ "series a",+ "series b",+ "valuation",+ "techcrunch",+ "investors",+ "venture capital",+]++_WEB_RELEASE_KEYWORDS = [+ "release",+ "released",+ "launch",+ "launched",+ "announce",+ "announcing",+ "introducing",+ "open-weight",+ "open weight",+ "model weights",+ "weights available",+ "now available",+ "new version",+ "open source",+ "open-source",+]++_WEB_NEWS_DOMAINS = [+ "techcrunch.com",+ "venturebeat.com",+ "theverge.com",+ "wired.com",+ "bloomberg.com",+ "reuters.com",+ "cnbc.com",+]++_WEB_RELEVANCE_KEYWORDS = [+ "llm",+ "large language model",+ "language model",+ "model release",+ "open-weight",+ "open source",+ "open-source",+ "agent",+ "framework",+ "benchmark",+ "leaderboard",+ "inference",+ "fine-tun",+ "finetun",+ "transformer",+ "multimodal",+ "embedding",+ "vllm",+ "sglang",+ "rag",+ "tool use",+ "coding agent",+ "github",+ "huggingface",+ "weights",+ "dataset",+ "sdk",+ "api",+ "release",+ "launch",+ "announc",+ "reasoning",+ "diffusion",+ "neural",+ "machine learning",+ "deep learning",+ "ai engineering",+ "build agent",+ "developer tool",+ "context window",+ "coding",+ "openai",+ "anthropic",+ "gemini",+ "claude",+ "mistral",+ "llama",+ "qwen",+ "deepseek",+]++_HN_INCLUDE_KEYWORDS = [+ "open source",+ "open-source",+ "llm",+ "agent",+ "inference",+ "benchmark",+ "framework",+ "fine-tuning",+ "rag",+ "embedding",+ "model weights",+ "arxiv",+ "paper",+ "tool",+ "library",+ "repo",+ "github",+ "release",+ "local model",+ "self-hosted",+ "vllm",+ "llama",+ "mistral",+ "deepseek",+ "qwen",+ "flux",+ "diffusion",+ "transformer",+ "training",+ "weights",+ "distillation",+ "quantization",+ "mcp",+ "skill",+ "evaluation",+ "evals",+]++_HN_CLOSED_COMMERCIAL = [+ "gpt",+ "claude",+ "gemini",+ "chatgpt",+ "copilot",+ "sora",+]++_HN_OPEN_SIGNAL = [+ "open source",+ "open-source",+ "open weight",+ "open-weight",+ "open weights",+]+++_GITHUB_REPO_RE = re.compile(+ r"github\.com/([^/?#]+)/([^/?#]+)",+ re.IGNORECASE,+)+++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):+ 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():+ 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()}"+ return ""+ match = _GITHUB_REPO_RE.search(str(item_or_url or ""))+ if match:+ return f"{match.group(1).lower()}/{match.group(2).lower()}"+ return ""+++def _normalize_source_url(url: str) -> str:+ """Normalize source_url for delivered-item deduplication."""+ if not url:+ return ""+ clean = url.split("?")[0].rstrip("/").lower()+ repo_key = _github_repo_key(clean)+ if repo_key:+ return f"https://github.com/{repo_key}"+ return clean+++def _parse_item_date(date_value: Optional[str]) -> Optional[datetime]:+ """Parse an item date string; return None if missing or unparseable."""+ if not date_value:+ return None+ text = str(date_value).strip()+ if not text:+ return None+ for fmt in ("%Y-%m-%d", "%Y/%m/%d"):+ try:+ parsed = datetime.strptime(text[:10], fmt)+ return parsed.replace(tzinfo=TZ_CN)+ except ValueError:+ continue+ return None+++def _item_date_cutoff(item: Dict, now: datetime) -> datetime:+ """Return the oldest acceptable datetime for an item's source."""+ source = item.get("source", "")+ days = SOURCE_DATE_CUTOFF_DAYS.get(source)+ if days is not None:+ return now - timedelta(days=days)+ hours = SOURCE_DATE_CUTOFF_HOURS.get(source, DEFAULT_DATE_CUTOFF_HOURS)+ return now - timedelta(hours=hours)+++def filter_stale_items(items: List[Dict]) -> Tuple[List[Dict], int, Dict[str, int]]:+ """Drop items older than their source-specific cutoff. Items without a date are kept."""+ now = datetime.now(TZ_CN)+ fresh: List[Dict] = []+ skipped = 0+ by_source: Dict[str, int] = {}++ for item in items:+ parsed = _parse_item_date(item.get("date"))+ source = item.get("source") or "unknown"+ if source == "x":+ confidence = str(item.get("date_confidence", "")).strip().lower()+ if not item.get("date") or confidence == "low" or parsed is None:+ fresh.append(item)+ by_source[source] = by_source.get(source, 0) + 1+ continue+ if parsed is None:+ fresh.append(item)+ by_source[source] = by_source.get(source, 0) + 1+ continue+ if parsed < _item_date_cutoff(item, now):+ skipped += 1+ continue+ fresh.append(item)+ by_source[source] = by_source.get(source, 0) + 1++ return fresh, skipped, by_source+++def _delivered_lookback_days(item: Dict) -> int:+ """URL dedup window: 14 days for GitHub and Good AI List, 7 for others."""+ source = item.get("source", "")+ if source == "github" or source == "repo":+ return GITHUB_REPO_DELIVERED_LOOKBACK_DAYS+ return DEFAULT_DELIVERED_LOOKBACK_DAYS+++def _topic_summary(title: str, summary: str = "") -> str:+ """Derive a short 3-word topic label for the memory spine."""+ stop = {+ "the", "a", "an", "for", "on", "and", "or", "to", "with", "of", "in",+ "is", "are", "was", "new", "from", "by", "at", "as", "its", "via",+ }+ words = re.findall(r"[A-Za-z0-9][A-Za-z0-9+-]*", f"{title} {summary}"[:160])+ picked = [w for w in words if w.lower() not in stop][:3]+ if len(picked) >= 2:+ return " ".join(picked)+ return " ".join((title or "unknown").split()[:3])+++def _load_delivered_store(path: Path = DELIVERED_ITEMS_PATH) -> Tuple[List[Dict], Dict[str, Dict]]:+ """Load delivery log entries and per-repo frequency metadata."""+ if not path.exists():+ return [], {}+ try:+ with open(path, "r", encoding="utf-8") as handle:+ data = json.load(handle)+ except (json.JSONDecodeError, OSError):+ return [], {}++ if isinstance(data, list):+ entries = [e for e in data if isinstance(e, dict)]+ return entries, _derive_frequency_from_entries(entries)++ entries = [e for e in data.get("deliveries", []) if isinstance(e, dict)]+ frequency = data.get("frequency", {})+ if not isinstance(frequency, dict):+ frequency = {}+ if not frequency and entries:+ frequency = _derive_frequency_from_entries(entries)+ return entries, frequency+++def _load_delivered_entries(path: Path = DELIVERED_ITEMS_PATH) -> List[Dict]:+ """Load all delivered-item log entries."""+ entries, _ = _load_delivered_store(path)+ return entries+++def _frequency_key_for_item(item: Dict) -> Optional[str]:+ """Return repo key for frequency tracking (GitHub + Good AI List repos only)."""+ source = item.get("source", "")+ if source not in ("github", "repo"):+ return None+ repo_key = _github_repo_key(item)+ return repo_key or None+++def _derive_frequency_from_entries(entries: List[Dict]) -> Dict[str, Dict]:+ """Build frequency map by counting repo deliveries in the lookback window."""+ cutoff = (+ datetime.now(TZ_CN) - timedelta(days=REPO_FREQUENCY_LOOKBACK_DAYS)+ ).strftime("%Y-%m-%d")+ counts: Dict[str, Dict] = {}+ for entry in entries:+ if entry.get("date", "") < cutoff:+ continue+ repo_key = _github_repo_key(entry)+ if not repo_key:+ continue+ record = counts.setdefault(+ repo_key,+ {+ "delivery_count": 0,+ "last_delivered": entry.get("date", ""),+ "source_url": _normalize_source_url(entry.get("source_url", "")),+ "title": entry.get("title", ""),+ },+ )+ record["delivery_count"] = int(record.get("delivery_count", 0)) + 1+ if entry.get("date", "") >= record.get("last_delivered", ""):+ record["last_delivered"] = entry.get("date", "")+ if entry.get("source_url"):+ record["source_url"] = _normalize_source_url(entry.get("source_url", ""))+ if entry.get("title"):+ record["title"] = entry.get("title", "")+ return counts+++def _load_repo_delivery_counts(path: Path = DELIVERED_ITEMS_PATH) -> Dict[str, int]:+ """Return delivery counts per repo key within the frequency lookback window."""+ entries, frequency = _load_delivered_store(path)+ derived = _derive_frequency_from_entries(entries)+ counts: Dict[str, int] = {}+ for repo_key, record in derived.items():+ counts[repo_key] = int(record.get("delivery_count", 0))+ for repo_key, record in frequency.items():+ if not isinstance(record, dict):+ continue+ counts[repo_key] = max(counts.get(repo_key, 0), int(record.get("delivery_count", 0)))+ return counts+++def _repo_delivery_count(item: Dict) -> int:+ """How many times this repo was delivered in the frequency lookback window."""+ repo_key = _frequency_key_for_item(item)+ if not repo_key:+ return 0+ return _load_repo_delivery_counts().get(repo_key, 0)+++def _is_frequency_capped(item: Dict) -> bool:+ """Block repos delivered REPO_FREQUENCY_CAP+ times in the last 30 days."""+ repo_key = _frequency_key_for_item(item)+ if not repo_key:+ return False+ return _repo_delivery_count(item) >= REPO_FREQUENCY_CAP+++def filter_frequency_capped(items: List[Dict]) -> Tuple[List[Dict], int, List[str]]:+ """Remove repos that hit the 30-day frequency cap."""+ kept: List[Dict] = []+ skipped = 0+ capped_titles: List[str] = []+ counts = _load_repo_delivery_counts()+ for item in items:+ repo_key = _frequency_key_for_item(item)+ if repo_key and counts.get(repo_key, 0) >= REPO_FREQUENCY_CAP:+ skipped += 1+ capped_titles.append(item.get("title") or repo_key)+ continue+ kept.append(item)+ return kept, skipped, capped_titles+++def _load_recent_delivered_urls(path: Path = DELIVERED_ITEMS_PATH) -> set:+ """Return source_urls delivered within each item-type lookback window."""+ entries = _load_delivered_entries(path)+ if not entries:+ return set()++ now = datetime.now(TZ_CN)+ urls: set = set()+ for entry in entries:+ normalized = _normalize_source_url(entry.get("source_url", ""))+ if not normalized:+ continue+ entry_date = entry.get("date", "")+ if not entry_date:+ continue+ # Use the longest lookback so we do not over-filter; per-item check in filter_already_delivered+ cutoff = (now - timedelta(days=GITHUB_REPO_DELIVERED_LOOKBACK_DAYS)).strftime("%Y-%m-%d")+ if entry_date >= cutoff:+ urls.add(normalized)+ repo_key = _github_repo_key(entry)+ if repo_key:+ urls.add(f"https://github.com/{repo_key}")+ return urls+++def _load_memory_spine(lookback_days: int = VERIFY_MEMORY_LOOKBACK_DAYS) -> List[Dict]:+ """Return enriched delivered items from the last N days for LLM verification."""+ cutoff_date = (datetime.now(TZ_CN) - timedelta(days=lookback_days)).strftime("%Y-%m-%d")+ spine: List[Dict] = []+ for entry in _load_delivered_entries():+ if entry.get("date", "") < cutoff_date:+ continue+ spine.append({+ "source_url": entry.get("source_url", ""),+ "date": entry.get("date", ""),+ "title": entry.get("title", ""),+ "entity": entry.get("entity", ""),+ "topic": entry.get("topic", ""),+ })+ return spine+++def _count_delivered_candidate_matches(items: List[Dict]) -> Tuple[int, int, int]:+ """Count how many candidates match the delivered log (by URL or GitHub repo key)."""+ entries = _load_delivered_entries()+ if not entries:+ return 0, 0, 0++ now = datetime.now(TZ_CN)+ recent_urls: set = set()+ recent_repo_keys: set = set()+ for entry in entries:+ entry_date = entry.get("date", "")+ if not entry_date:+ continue+ cutoff = (now - timedelta(days=GITHUB_REPO_DELIVERED_LOOKBACK_DAYS)).strftime("%Y-%m-%d")+ if entry_date < cutoff:+ continue+ normalized = _normalize_source_url(entry.get("source_url", ""))+ if normalized:+ recent_urls.add(normalized)+ repo_key = _github_repo_key(entry)+ if repo_key:+ recent_repo_keys.add(repo_key)++ url_matches = 0+ repo_matches = 0+ for item in items:+ normalized = _normalize_source_url(item.get("source_url", ""))+ repo_key = _github_repo_key(item)+ if normalized and normalized in recent_urls:+ url_matches += 1+ elif repo_key and repo_key in recent_repo_keys:+ repo_matches += 1+ return url_matches + repo_matches, url_matches, repo_matches+++def _recent_delivery_entry(item: Dict) -> Optional[Dict]:+ """Return the delivered-log entry for an item within its lookback window, if any."""+ entries = _load_delivered_entries()+ if not entries:+ return None++ now = datetime.now(TZ_CN)+ entry_by_url: 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+ 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)+ if not entry:+ return None++ lookback = _delivered_lookback_days(item)+ cutoff = (now - timedelta(days=lookback)).strftime("%Y-%m-%d")+ if entry.get("date", "") >= cutoff:+ return entry+ return None+++def _was_recently_delivered(item: Dict) -> bool:+ """True if this item appears in delivered_items.json within its lookback window."""+ return _recent_delivery_entry(item) is not None+++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.++ 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.+ """+ 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_repo_key: Dict[str, Dict] = {}+ for entry in entries:+ normalized = _normalize_source_url(entry.get("source_url", ""))+ if normalized:+ entry_by_url[normalized] = entry+ repo_key = _github_repo_key(entry)+ if repo_key:+ entry_by_repo_key[repo_key] = entry++ 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)++ if entry:+ lookback = _delivered_lookback_days(item)+ cutoff = (now - timedelta(days=lookback)).strftime("%Y-%m-%d")+ if entry.get("date", "") >= cutoff:+ skipped += 1+ continue+ elif normalized and normalized in delivered_urls:+ skipped += 1+ continue+ kept.append(item)+ return kept, skipped+++def _append_delivered_items(+ items: List[Dict],+ delivery_date: str,+ path: Path = DELIVERED_ITEMS_PATH,+) -> None:+ """Append selected digest items and increment per-repo delivery counts."""+ entries, frequency = _load_delivered_store(path)+ cutoff = (+ datetime.now(TZ_CN) - timedelta(days=REPO_FREQUENCY_LOOKBACK_DAYS)+ ).strftime("%Y-%m-%d")++ for item in items:+ source_url = (item.get("source_url") or "").strip()+ if not source_url:+ continue+ title = (item.get("title") or "").strip()+ normalized_url = _normalize_source_url(source_url) or source_url+ 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))+ new_count = prev_count + 1 if repo_key else 1++ entries.append({+ "source_url": normalized_url,+ "date": delivery_date,+ "title": title,+ "entity": (item.get("entity") or "").strip(),+ "topic": _topic_summary(title, item.get("summary") or ""),+ "delivery_count": new_count,+ "repo_key": repo_key or "",+ })++ if repo_key:+ frequency[repo_key] = {+ "delivery_count": new_count,+ "last_delivered": delivery_date,+ "source_url": normalized_url,+ "title": title,+ }++ # Drop frequency records older than the lookback window (counts reset after 30d).+ pruned_frequency: Dict[str, Dict] = {}+ for repo_key, record in frequency.items():+ if not isinstance(record, dict):+ continue+ if record.get("last_delivered", "") >= cutoff:+ pruned_frequency[repo_key] = record++ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, "w", encoding="utf-8") as handle:+ json.dump({"deliveries": entries, "frequency": pruned_frequency}, handle, ensure_ascii=False, indent=2)+++def _item_key(item: Dict) -> str:+ return item.get("id") or item.get("source_url") or item.get("title", "")+++def _is_good_ai_list(item: Dict) -> bool:+ return item.get("source_label") == "Good AI List" or (+ item.get("source") == "repo" and item.get("source_label") == "Good AI List"+ )+++def _is_ainews(item: Dict) -> bool:+ return item.get("source_label") == "AINews" or str(item.get("entity", "")).startswith("AINews")+++def _is_ainews_x(item: Dict) -> bool:+ """AINews story with a direct X/Twitter URL (digest → What's Trending on X)."""+ if not _is_ainews(item):+ return False+ url = (item.get("source_url") or "").lower()+ return "x.com" in url or "twitter.com" in url+++def _load_morning_ai_env() -> None:+ """Load Devable Research Agent .env files into os.environ without overriding existing vars."""+ project_root = Path(__file__).resolve().parent.parent+ if str(project_root) not in sys.path:+ sys.path.insert(0, str(project_root))+ from lib.env import load_env_file++ merged: Dict[str, str] = {}+ for path in (+ MORNING_AI_ENV_FILE,+ project_root / ".claude" / "morning-ai.env",+ project_root / ".env",+ project_root / ".env.local",+ ):+ merged.update(load_env_file(str(path)))++ for key, value in merged.items():+ if value and key not in os.environ:+ os.environ[key] = value+++def _load_mistral_api_key() -> Optional[str]:+ key = os.environ.get("MISTRAL_API_KEY", "").strip()+ return key or None+++def _mistral_client(api_key: str) -> "Mistral":+ global _MISTRAL_CLIENT+ if _MISTRAL_CLIENT is None:+ _MISTRAL_CLIENT = Mistral(api_key=api_key)+ return _MISTRAL_CLIENT+++def _paper_cache_key(item: Dict) -> str:+ title = item.get("title", "") or ""+ summary = (item.get("summary") or "")[:300]+ return f"{title}|{summary}"+++def _parse_llm_paper_score(response_text: str) -> int:+ match = re.search(r"[1-5]", (response_text or "").strip())+ if not match:+ return FAILED_PAPER_LLM_SCORE+ return int(match.group())+++def _mistral_score_paper(title: str, summary: str, api_key: str) -> int:+ user_prompt = _PAPER_LLM_USER_TEMPLATE.format(+ title=title,+ summary=(summary or "")[:300],+ )+ response = _mistral_client(api_key).chat.complete(+ model=PAPER_LLM_MODEL,+ messages=[+ {"role": "system", "content": _PAPER_LLM_SYSTEM},+ {"role": "user", "content": user_prompt},+ ],+ temperature=0,+ max_tokens=8,+ )+ content = response.choices[0].message.content+ return _parse_llm_paper_score(content)+++def _score_single_paper(item: Dict, api_key: str) -> int:+ try:+ return _mistral_score_paper(+ item.get("title", "") or "",+ item.get("summary", "") or "",+ api_key,+ )+ except Exception:+ return FAILED_PAPER_LLM_SCORE+++def score_papers_with_llm(items: List[Dict]) -> None:+ """Score arXiv papers concurrently via Mistral and cache results."""+ global _paper_llm_scores++ api_key = _load_mistral_api_key()+ papers = [item for item in items if item.get("source") == "arxiv"]+ 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)++ if not unique_papers:+ return++ if not _HAS_MISTRAL:+ print("Warning: mistralai SDK not installed; defaulting all paper scores to 3")+ for key in unique_papers:+ _paper_llm_scores[key] = FAILED_PAPER_LLM_SCORE+ return++ if not api_key:+ print("Warning: MISTRAL_API_KEY not set; defaulting all paper scores to 3")+ for key in unique_papers:+ _paper_llm_scores[key] = FAILED_PAPER_LLM_SCORE+ return++ print(f"Scoring {len(unique_papers)} papers with {PAPER_LLM_MODEL}...")+ with ThreadPoolExecutor(max_workers=PAPER_LLM_MAX_WORKERS) as executor:+ futures = {+ executor.submit(_score_single_paper, paper, api_key): cache_key+ for cache_key, paper in unique_papers.items()+ }+ for future in as_completed(futures):+ cache_key = futures[future]+ try:+ _paper_llm_scores[cache_key] = future.result()+ except Exception:+ _paper_llm_scores[cache_key] = FAILED_PAPER_LLM_SCORE++ 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 _parse_json_array_from_llm(text: str) -> List[Dict]:+ """Extract a JSON array from LLM output."""+ if not text:+ raise ValueError("empty LLM response")+ m = re.search(r"```json\s*(\[.*?\])\s*```", text, re.DOTALL)+ if not m:+ m = re.search(r"(\[\s*\{.*?\}\s*\])", text, re.DOTALL)+ if not m:+ if re.search(r"\[\s*\]", text):+ return []+ raise ValueError("no JSON array in LLM response")+ return json.loads(m.group(1))+++def _verify_digest_with_mistral(+ candidates: List[Dict],+ memory_spine: List[Dict],+ api_key: str,+) -> List[Dict]:+ """Plan-Execute-Verify: one Mistral pass to dedupe against memory spine."""+ slim_candidates = [+ {+ "title": item.get("title", ""),+ "summary": (item.get("summary") or "")[:200],+ "entity": item.get("entity", ""),+ "source": item.get("source", ""),+ "source_url": item.get("source_url", ""),+ "importance": item.get("importance", 0),+ }+ for item in candidates+ ]+ user_prompt = _VERIFY_LLM_USER_TEMPLATE.format(+ top_items_json=json.dumps(slim_candidates, ensure_ascii=False, indent=2),+ memory_spine_json=json.dumps(memory_spine, ensure_ascii=False, indent=2),+ )+ response = _mistral_client(api_key).chat.complete(+ model=VERIFY_LLM_MODEL,+ messages=[+ {"role": "system", "content": _VERIFY_LLM_SYSTEM},+ {"role": "user", "content": user_prompt},+ ],+ temperature=0,+ max_tokens=8192,+ )+ content = response.choices[0].message.content+ filtered_slim = _parse_json_array_from_llm(content)++ by_url = {_normalize_source_url(item.get("source_url", "")): item for item in candidates}+ by_title = {(item.get("title") or "").strip().lower(): item for item in candidates}+ verified: List[Dict] = []+ seen: set = set()+ for raw in filtered_slim:+ url_key = _normalize_source_url(raw.get("source_url", ""))+ title_key = (raw.get("title") or "").strip().lower()+ original = by_url.get(url_key) or by_title.get(title_key)+ if not original:+ continue+ key = _item_key(original)+ if key in seen:+ continue+ seen.add(key)+ verified.append(original)+ return verified+++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}+ result = list(verified)+ bucket_counts: Dict[str, int] = {}+ for item in result:+ bucket = _quota_bucket(item)+ bucket_counts[bucket] = bucket_counts.get(bucket, 0) + 1++ restored = 0+ for bucket, limits in QUOTA_LIMITS.items():+ minimum = limits["min"]+ if minimum <= 0:+ continue+ shortfall = minimum - bucket_counts.get(bucket, 0)+ if shortfall <= 0:+ continue+ predicate = _bucket_predicate(bucket)+ for item in sorted(candidates, key=lambda x: x.get("importance", 0), reverse=True):+ if shortfall <= 0:+ break+ key = _item_key(item)+ if key in verified_keys or not predicate(item) or not _is_eligible_for_digest(item):+ continue+ result.append(item)+ verified_keys.add(key)+ bucket_counts[bucket] = bucket_counts.get(bucket, 0) + 1+ shortfall -= 1+ restored += 1++ if restored:+ print(f"Restored {restored} quota-minimum item(s) after LLM verify")+ return sorted(result, key=lambda x: x.get("importance", 0), reverse=True)+++def _print_top_items_list(label: str, items: List[Dict]) -> None:+ print(label)+ for item in items:+ category = _digest_category(item)+ paper_note = ""+ if item.get("source") == "arxiv":+ paper_note = f" [LLM relevance {paper_llm_score(item)}]"+ print(+ f" [{item.get('importance', 0):.1f}] {category:22} "+ f"{item.get('title', 'No title')}{paper_note}"+ )+++def paper_llm_score(item: Dict) -> int:+ if item.get("source") != "arxiv":+ return 0+ return _paper_llm_scores.get(_paper_cache_key(item), FAILED_PAPER_LLM_SCORE)+++def _is_qualifying_paper(item: Dict) -> bool:+ if item.get("source") != "arxiv":+ return False+ return paper_llm_score(item) >= MIN_PAPER_LLM_SCORE+++def _is_qualifying_web(item: Dict) -> bool:+ if item.get("source") != "web":+ return False+ text = f"{item.get('title', '')} {item.get('summary', '')}".lower()+ url = (item.get("source_url") or "").lower()+ if any(keyword in text for keyword in _WEB_SKIP_KEYWORDS):+ return False+ if any(domain in url for domain in _WEB_NEWS_DOMAINS):+ return False+ if item.get("entity") == "AI Engineering Web":+ if not any(keyword in text for keyword in _WEB_RELEASE_KEYWORDS):+ return False+ return any(keyword in text for keyword in _WEB_RELEVANCE_KEYWORDS)+++def _hf_text(item: Dict) -> str:+ return f"{item.get('title', '')} {item.get('summary', '')} {item.get('raw_text', '')}".lower()+++def _is_qualifying_huggingface(item: Dict) -> bool:+ if item.get("source") != "huggingface":+ return False+ text = _hf_text(item)+ if any(keyword in text for keyword in _HF_SKIP_KEYWORDS):+ return False+ return any(keyword in text for keyword in _HF_INCLUDE_KEYWORDS)+++def _github_text(item: Dict) -> str:+ return f"{item.get('title', '')} {item.get('summary', '')} {item.get('raw_text', '')}"+++def _clean_github_summary(summary: str) -> str:+ text = re.sub(r"##[^\n]*\n", " ", summary)+ text = re.sub(r"\*+", " ", text)+ text = re.sub(r"https?://\S+", " ", text)+ text = re.sub(r"\s+", " ", text).strip()+ return text+++def _has_added_or_new_signal(text: str) -> bool:+ scrubbed = re.sub(r"new contributors?", " ", text, flags=re.I)+ lower = scrubbed.lower()+ return bool(re.search(r"\badded\b", lower) or re.search(r"\bnew\b", lower))+++def _first_changelog_entry(summary: str) -> str:+ for line in summary.splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ return line.lstrip("-* ").strip()+ return _clean_github_summary(summary)+++def _changelog_bullets(text: str) -> List[str]:+ """Extract markdown changelog bullets, skipping install command lines."""+ bullets: List[str] = []+ for line in text.splitlines():+ stripped = line.strip()+ if not stripped.startswith(("-", "*")):+ continue+ bullet = stripped.lstrip("-* ").strip()+ lower = bullet.lower()+ if any(cmd in lower for cmd in ("npm install", "pip install", "yarn add", "pnpm add", "bun add")):+ continue+ bullets.append(bullet)+ return bullets+++def _is_claude_agent_sdk_sync_release(item: Dict) -> bool:+ """SDK releases that only sync bundled CLI or add internal wiring frames."""+ repo_key = _github_repo_key(item)+ if not repo_key or not repo_key.startswith("anthropics/claude-agent-sdk"):+ return False++ text = _github_text(item).lower()+ if any(keyword in text for keyword in ("updated bundled", "bundled claude cli", "updated to parity")):+ return True++ combined = item.get("raw_text") or item.get("summary") or ""+ substantive = _changelog_bullets(combined)+ if not substantive or len(substantive) > 3:+ return False++ return all(+ bullet.lower().startswith("added")+ and any(keyword in bullet.lower() for keyword in _SDK_SYNC_KEYWORDS)+ for bullet in substantive+ )+++def _is_fix_heavy_claude_code_patch(item: Dict) -> bool:+ """Patch releases dominated by bugfixes with only minor CLI UX tweaks."""+ repo_key = _github_repo_key(item)+ if repo_key != "anthropics/claude-code":+ return False+ if not re.search(r"v\d+\.\d+\.\d+", item.get("title", ""), re.I):+ return False++ combined = item.get("raw_text") or item.get("summary") or ""+ bullets = _changelog_bullets(combined)+ if len(bullets) < 8:+ return False++ fixed = [bullet for bullet in bullets if bullet.lower().startswith("fixed")]+ other = [+ bullet for bullet in bullets+ if bullet.lower().startswith(("added", "improved", "changed"))+ ]+ if len(fixed) < max(8, len(other) * 2):+ return False++ for bullet in other:+ lower = bullet.lower()+ if any(keyword in lower for keyword in _MAJOR_RELEASE_CAPABILITY_KEYWORDS):+ return False+ return True+++def _is_fixed_only_maintenance(summary: str) -> bool:+ if not summary.strip():+ return False++ bullets = [+ line.strip().lstrip("-* ").strip()+ for line in summary.splitlines()+ if line.strip().startswith(("-", "*"))+ ]+ if len(bullets) == 1 and bullets[0].lower().startswith("fixed"):+ return True++ first = _first_changelog_entry(summary)+ if first.lower().startswith("fixed") and not _has_added_or_new_signal(summary):+ return True++ return False+++def _is_short_low_signal_summary(summary: str) -> bool:+ """Skip terse release notes with no feature, capability, or improvement signal."""+ clean = _clean_github_summary(summary).lower()+ if not clean:+ return True+ if len(clean.split()) >= 15:+ return False+ return not any(keyword in clean for keyword in _GITHUB_FEATURE_KEYWORDS)+++def _is_github_trending(item: Dict) -> bool:+ return "trending" in (item.get("source_label") or "").lower()+++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):+ return True+ return item.get("source") == "github" and _is_github_trending(item)+++def _is_skipped_repo_content(item: Dict) -> bool:+ """Skip blocklisted or low-signal repos (GitHub Trending + Good AI List)."""+ if not _is_curated_repo_source(item):+ return False++ repo_key = _github_repo_key(item)+ if repo_key in _REPO_BLOCKLIST:+ return True++ text = _github_text(item).lower()+ if any(keyword in text for keyword in _REPO_WEBSITE_CLONER_KEYWORDS):+ return True++ has_ai_signal = any(signal in text for signal in _REPO_AI_AGENT_FRAMEWORK_SIGNALS)+ if any(keyword in text for keyword in _REPO_GENERIC_SCRAPING_KEYWORDS) and not has_ai_signal:+ return True+ if any(keyword in text for keyword in _REPO_BROWSER_AUTOMATION_KEYWORDS) and not has_ai_signal:+ return True+ return False+++def _is_skipped_github_cybersecurity(text: str) -> bool:+ """Skip offensive-security cheat-sheet repos; plain cheat-sheets stay."""+ if any(phrase in text for phrase in _GITHUB_TRENDING_CYBERSECURITY_PHRASES):+ return True+ return (+ "command library equipped with" in text+ and "cheat-sheet" in text+ )+++def _is_skipped_github_trending(item: Dict) -> bool:+ """Skip finance, plugin, cybersecurity, and low-signal repos from GitHub Trending."""+ if not _is_github_trending(item):+ return False+ if _is_skipped_repo_content(item):+ return True+ text = _github_text(item).lower()+ if _is_skipped_github_cybersecurity(text):+ return True+ if any(keyword in text for keyword in _GITHUB_TRENDING_FINANCE_KEYWORDS):+ return True+ return any(keyword in text for keyword in _GITHUB_TRENDING_PLUGIN_KEYWORDS)+++def _is_ai_engineering_repo_text(text: str) -> bool:+ """Return True when repo name/description signals AI engineering."""+ lower = text.lower()+ return any(keyword in lower for keyword in _GITHUB_TRENDING_AI_KEYWORDS)+++def _is_low_signal_plugin_repo(text: str) -> bool:+ lower = text.lower()+ if any(keyword in lower for keyword in _GITHUB_LOW_SIGNAL_PLUGIN_KEYWORDS):+ return True+ return any(keyword in lower for keyword in _GITHUB_TRENDING_PLUGIN_KEYWORDS)+++def _is_maintenance_repo_release(item: Dict) -> bool:+ """Skip maintenance, plugin-wrapper, and low-signal repo blurbs (GitHub + Good AI List)."""+ source = item.get("source", "")+ is_github = source == "github"+ is_gal = source == "repo" and _is_good_ai_list(item)+ if not is_github and not is_gal:+ return False++ if _is_skipped_repo_content(item):+ return True++ if is_github and _is_skipped_github_trending(item):+ return True++ text = _github_text(item)+ lower = text.lower()+ if _is_low_signal_plugin_repo(lower):+ return True++ summary = item.get("summary", "") or ""+ if is_gal:+ if any(keyword in lower for keyword in _GITHUB_MAINTENANCE_KEYWORDS):+ return True+ return False++ is_trending_style = is_github and _is_github_trending(item)+ if is_trending_style:+ return _is_short_low_signal_summary(summary)++ if is_github and not is_trending_style:+ if _is_claude_agent_sdk_sync_release(item):+ return True+ if _is_fix_heavy_claude_code_patch(item):+ return True++ if any(keyword in lower for keyword in _GITHUB_MAINTENANCE_KEYWORDS):+ return True+ if re.search(r"\bCI\b", text):+ return True+ if _is_fixed_only_maintenance(summary):+ return True+ return _is_short_low_signal_summary(summary)+++def _is_qualifying_hackernews(item: Dict) -> bool:+ """HN items must signal open-source AI engineering; skip closed-product hype."""+ if item.get("source") != "hackernews":+ return False+ text = f"{item.get('title', '')} {item.get('summary', '')}".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):+ return any(signal in text for signal in _HN_OPEN_SIGNAL)+ return True+++def _is_qualifying_github(item: Dict) -> bool:+ if item.get("source") != "github":+ return True+ if _is_frequency_capped(item):+ return False+ if _is_maintenance_repo_release(item):+ return False+ if _is_github_trending(item):+ return _is_ai_engineering_repo_text(_github_text(item))+ return True+++def _is_qualifying_good_ai_list(item: Dict) -> bool:+ if _is_frequency_capped(item):+ return False+ return _is_good_ai_list(item) and not _is_maintenance_repo_release(item)+++def _is_eligible_for_digest(item: Dict) -> bool:+ source = item.get("source")+ if source == "arxiv":+ return _is_qualifying_paper(item)+ if source == "web":+ return _is_qualifying_web(item)+ if source == "huggingface":+ return _is_qualifying_huggingface(item)+ if source == "github":+ return _is_qualifying_github(item)+ if _is_good_ai_list(item):+ return _is_qualifying_good_ai_list(item)+ if source == "hackernews":+ return _is_qualifying_hackernews(item)+ return True+++def _digest_category(item: Dict) -> str:+ source = item.get("source", "")+ label = item.get("source_label", "")++ if source == "arxiv":+ return "Paper"+ if source == "huggingface":+ return "HuggingFace"+ if _is_good_ai_list(item):+ return "Repo (Good AI List)"+ if source == "repo":+ return "Repo"+ if source == "web":+ if _is_ainews_x(item):+ return "Community (X via AINews)"+ if _is_ainews(item):+ return "Web (AINews)"+ return "Web (Tavily)"+ if source == "github":+ if "Trending" in label:+ return "Repo (GitHub Trending)"+ return "Repo (GitHub)"+ if source == "hackernews":+ return "Community (HN)"+ if source == "reddit":+ return "Community (Reddit)"+ if source == "x":+ return "x"+ return source or "Other"+++def _quota_bucket(item: Dict) -> str:+ """Map an item to its quota bucket for min/max enforcement."""+ if _is_good_ai_list(item):+ return "good_ai_list"+ if _is_ainews_x(item):+ return "x"+ source = item.get("source", "")+ return {+ "arxiv": "paper",+ "github": "github",+ "web": "web",+ "huggingface": "huggingface",+ "x": "x",+ "hackernews": "hackernews",+ }.get(source, "other")+++def _bucket_predicate(bucket: str) -> Callable[[Dict], bool]:+ if bucket == "paper":+ return _is_qualifying_paper+ if bucket == "github":+ return lambda item: item.get("source") == "github" and _is_qualifying_github(item)+ if bucket == "web":+ return _is_qualifying_web+ 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)+ if bucket == "hackernews":+ return _is_qualifying_hackernews+ return lambda item: False+++def _can_add_to_bucket(item: Dict, bucket_counts: Dict[str, int]) -> bool:+ bucket = _quota_bucket(item)+ limits = QUOTA_LIMITS.get(bucket)+ if limits is None:+ return True+ return bucket_counts.get(bucket, 0) < limits["max"]+++def _paper_sort_key(item: Dict) -> Tuple[int, float]:+ """Sort paper candidates: undelivered first, then highest score."""+ delivered_rank = 1 if _was_recently_delivered(item) else 0+ return (delivered_rank, -item.get("importance", 0))+++def _paper_candidates(items: List[Dict]) -> List[Dict]:+ """Qualifying papers sorted by freshness then score."""+ qualifying = [item for item in items if _is_qualifying_paper(item)]+ return sorted(qualifying, key=_paper_sort_key)+++def _good_ai_list_sort_key(item: Dict) -> Tuple[int, float]:+ """Sort Good AI List candidates: fresh first, then highest score."""+ delivered_rank = 1 if _was_recently_delivered(item) else 0+ return (delivered_rank, -item.get("importance", 0))+++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)]+ return sorted(qualifying, key=_good_ai_list_sort_key)+++def select_diverse_items(items: List[Dict], top_n: int = 10) -> List[Dict]:+ """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++ 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.+ """+ 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)+ selected: List[Dict] = []+ selected_keys: set = set()+ bucket_counts: Dict[str, int] = {}++ def _try_add(item: Dict) -> bool:+ if len(selected) >= top_n:+ return False+ key = _item_key(item)+ if key in selected_keys or not _can_add_to_bucket(item, bucket_counts):+ return False+ selected.append(item)+ selected_keys.add(key)+ bucket = _quota_bucket(item)+ bucket_counts[bucket] = bucket_counts.get(bucket, 0) + 1+ return True++ for bucket in ("paper", "good_ai_list", "github", "web", "x", "huggingface"):+ minimum = QUOTA_LIMITS[bucket]["min"]+ if minimum <= 0:+ continue+ predicate = _bucket_predicate(bucket)+ if bucket == "good_ai_list":+ candidate_list = gal_candidates+ elif bucket == "paper":+ candidate_list = paper_candidates+ else:+ candidate_list = sorted_items+ picked = 0+ for item in candidate_list:+ if len(selected) >= top_n or picked >= minimum:+ break+ if not predicate(item):+ continue+ if _try_add(item):+ picked += 1++ 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":+ continue+ if not _is_eligible_for_digest(item):+ continue+ _try_add(item)++ for item in paper_candidates:+ if len(selected) >= top_n:+ break+ key = _item_key(item)+ if key in selected_keys:+ continue+ _try_add(item)++ for item in gal_candidates:+ if len(selected) >= top_n:+ break+ key = _item_key(item)+ if key in selected_keys:+ continue+ _try_add(item)++ return selected+++def _boost_good_ai_list_scores(items: List[Dict]) -> None:+ """Prioritize curated Good AI List repos in selection ranking."""+ for item in items:+ if not _is_good_ai_list(item):+ continue+ boosted = item.get("importance", 0) + GOOD_AI_LIST_IMPORTANCE_BOOST+ item["importance"] = round(min(10.0, boosted), 1)+++def _good_ai_list_item_status(+ item: Dict,+ *,+ filtered_keys: set,+ selected_keys: set,+) -> Tuple[str, float]:+ """Return exclusion reason and effective score for a Good AI List audit line."""+ key = _item_key(item)+ base_score = item.get("importance", 0)+ boosted_score = round(min(10.0, base_score + GOOD_AI_LIST_IMPORTANCE_BOOST), 1)++ fresh, stale_skipped, _ = filter_stale_items([item])+ if stale_skipped:+ return "excluded: stale date filter", base_score++ recent = _load_recent_delivered_urls()+ kept, dedup_skipped = filter_already_delivered(fresh, recent)+ if dedup_skipped and not _is_good_ai_list(item):+ return "excluded: delivered-log dedup (14d)", base_score++ if _is_skipped_repo_content(item):+ return "excluded: repo skip policy", base_score++ if _is_frequency_capped(item):+ count = _repo_delivery_count(item)+ return f"excluded: frequency cap ({count}/{REPO_FREQUENCY_CAP} in {REPO_FREQUENCY_LOOKBACK_DAYS}d)", base_score++ if _is_maintenance_repo_release(item):+ return "excluded: maintenance/plugin filter", base_score++ if not _is_qualifying_good_ai_list(item):+ return "excluded: failed eligibility", base_score++ if key not in filtered_keys:+ return "excluded: removed before selection", boosted_score++ if key in selected_keys:+ 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+++def _print_good_ai_list_audit(+ raw_items: List[Dict],+ filtered_items: List[Dict],+ selected_items: List[Dict],+) -> None:+ """Print all Good AI List items with scores and keep/exclude reasons."""+ gal_items = [item for item in raw_items if _is_good_ai_list(item)]+ if not gal_items:+ print("Good AI List audit: no items in collection")+ return++ filtered_keys = {_item_key(item) for item in filtered_items}+ selected_keys = {_item_key(item) for item in selected_items}++ print(f"Good AI List audit ({len(gal_items)} collected):")+ print(f" {'Score':>6} {'Boost':>6} Status")+ for item in sorted(gal_items, key=lambda row: -row.get("importance", 0)):+ base = item.get("importance", 0)+ boosted = round(min(10.0, base + GOOD_AI_LIST_IMPORTANCE_BOOST), 1)+ status, _ = _good_ai_list_item_status(+ item,+ filtered_keys=filtered_keys,+ selected_keys=selected_keys,+ )+ title = (item.get("title") or "")[:48]+ print(f" {base:6.1f} {boosted:6.1f} {status:<40} {title}")++ selected_gal = sum(1 for item in gal_items if _item_key(item) in selected_keys)+ print(f"Good AI List selected: {selected_gal}/{len(gal_items)}")+ _print_good_ai_list_selection_breakdown(selected_items)+++def _print_good_ai_list_selection_breakdown(selected_items: List[Dict]) -> None:+ """Show which selected Good AI List repos were fresh vs previously delivered."""+ gal_selected = [item for item in selected_items if _is_good_ai_list(item)]+ if not gal_selected:+ print("Good AI List selection breakdown: none selected")+ return++ fresh: List[Dict] = []+ redelivered: List[Dict] = []+ for item in gal_selected:+ if _was_recently_delivered(item):+ redelivered.append(item)+ else:+ fresh.append(item)++ print(f"Good AI List selection breakdown: {len(fresh)} fresh, {len(redelivered)} previously delivered")+ if fresh:+ print(" Fresh (priority):")+ for item in fresh:+ print(f" [{item.get('importance', 0):.1f}] {item.get('title', '')}")+ if redelivered:+ print(" Previously delivered (fallback):")+ for item in redelivered:+ entry = _recent_delivery_entry(item)+ delivered_on = entry.get("date", "?") if entry else "?"+ 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):+ """Read the full collection JSON and output diverse top-N scored items."""++ input_file = Path(input_path)+ if not input_file.exists():+ print(f"Error: Input file not found: {input_path}")+ sys.exit(1)++ with open(input_file, "r", encoding="utf-8") as f:+ data = json.load(f)++ items = data.get("items", [])++ if not items:+ print("No items found in data file")+ sys.exit(1)++ print(f"Total items before filtering: {len(items)}")++ _load_morning_ai_env()+ score_papers_with_llm(items)++ items, stale_count, source_counts = filter_stale_items(items)+ 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]}")++ recent_delivered = _load_recent_delivered_urls()+ match_total, match_url, match_repo = _count_delivered_candidate_matches(items)+ print(+ f"Delivered-log matches among candidates before selection: "+ f"{match_total} total ({match_url} by URL, {match_repo} by GitHub repo key)"+ )+ 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)+ )+ paper_redeliverable = sum(+ 1 for item in items+ if item.get("source") == "arxiv" and _was_recently_delivered(item)+ )+ if gal_redeliverable:+ print(+ f"Good AI List: retained {gal_redeliverable} previously-delivered repos "+ f"for freshness-priority selection"+ )+ if paper_redeliverable:+ print(+ f"Papers: retained {paper_redeliverable} previously-delivered papers "+ f"for freshness-priority minimum quota"+ )+ 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)"+ )++ items, freq_skipped, freq_capped = filter_frequency_capped(items)+ if freq_skipped:+ print(+ f"Skipped {freq_skipped} repos at frequency cap "+ f"({REPO_FREQUENCY_CAP}+ deliveries in {REPO_FREQUENCY_LOOKBACK_DAYS}d):"+ )+ for title in sorted(set(freq_capped)):+ print(f" - {title}")++ _boost_good_ai_list_scores(items)++ top_items = select_diverse_items(items, top_n)++ _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)++ 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")+ else:+ print("No memory spine entries; skipping LLM verify step")++ _print_top_items_list(f"Top {len(verified_items)} items AFTER LLM verify:", verified_items)++ print("Category counts:")+ for category, count in sorted(_category_counts(verified_items).items()):+ print(f" {category}: {count}")++ output_data = {+ "date": data.get("date", datetime.now().strftime("%Y-%m-%d")),+ "generated_at": data.get("generated_at", ""),+ "items": verified_items,+ "stats": {+ "total_collected": len(items),+ "total_in_digest": len(verified_items),+ "before_verify": len(top_items),+ "removed_by_verify": len(top_items) - len(verified_items),+ "by_category": _category_counts(verified_items),+ },+ }++ output_file = Path(output_path)+ output_file.parent.mkdir(parents=True, exist_ok=True)++ with open(output_file, "w", encoding="utf-8") as f:+ json.dump(output_data, f, ensure_ascii=False, indent=2)++ delivery_date = output_data["date"]+ _append_delivered_items(verified_items, delivery_date)++ print(f"Filtered digest input saved to: {output_path}")+ print(f"File size: {output_file.stat().st_size / 1024:.1f}KB")+++def _category_counts(items: List[Dict]) -> Dict[str, int]:+ counts: Dict[str, int] = {}+ for item in items:+ cat = _digest_category(item)+ counts[cat] = counts.get(cat, 0) + 1+ return counts+++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)")+ args = parser.parse_args()++ filter_top_items(args.input, args.output, args.top)+++if __name__ == "__main__":+ main()diff --git a/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txt b/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txtnew file mode 100644index 0000000..ad9c019--- /dev/null+++ b/ai_agents/devable_research_agent/scripts/openclaw_digest_prompt.txt@@ -0,0 +1,179 @@+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.+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.++FORBIDDEN ACTIONS (will break delivery):+- sessions_send / message / slack_* tools (channel IDs are not session keys)+- 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++---++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."++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)++Follow the inclusion/exclusion rules in:++C:\Users\HP\.config\morning-ai\editorial_profile.md++(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.++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 qualifying items - no fixed total cap and no fixed per-section cap+- Skip sections with no qualifying items entirely (do not show empty headers)++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."++---++STEP 4 - OUTPUT (your final reply IS the Slack message)++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",+"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.++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>++Nothing more. No second sentence. No line breaks inside an item. No trailing text after the 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:+- 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}++📄 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++---++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.+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/refresh_digest_input.bat b/ai_agents/devable_research_agent/scripts/refresh_digest_input.batnew file mode 100644index 0000000..547ae30--- /dev/null+++ b/ai_agents/devable_research_agent/scripts/refresh_digest_input.bat@@ -0,0 +1,18 @@+@echo off+REM Refresh digest_input_today.json from existing data_today.json (no re-collection).+REM Run this before a manual OpenClaw cron digest if the filter rules changed.++cd /d "%~dp0.."+set PYTHONIOENCODING=utf-8+set PYTHONUTF8=1++if not exist data_today.json (+ echo ERROR: data_today.json missing. Run scripts\run_pipeline.bat first.+ exit /b 1+)++py -3 scripts\filter_top_items.py data_today.json digest_input_today.json --top 20+if errorlevel 1 (+ python scripts\filter_top_items.py data_today.json digest_input_today.json --top 20+)+exit /b %ERRORLEVEL%diff --git a/ai_agents/devable_research_agent/scripts/run_pipeline.bat b/ai_agents/devable_research_agent/scripts/run_pipeline.batnew file mode 100644index 0000000..ea6c398--- /dev/null+++ b/ai_agents/devable_research_agent/scripts/run_pipeline.bat@@ -0,0 +1,24 @@+@echo off+setlocal EnableExtensions++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.."+cd /d "%PROJECT_ROOT%" || (+ echo ERROR: Could not change to project directory: %PROJECT_ROOT%+ exit /b 1+)++set "PYTHONIOENCODING=utf-8"+set "PYTHONUTF8=1"++REM Prefer the Python launcher; fall back to python on PATH.+where py >nul 2>&1+if %ERRORLEVEL%==0 (+ py -3 "%PROJECT_ROOT%\scripts\run_pipeline.py"+ exit /b %ERRORLEVEL%+)++python "%PROJECT_ROOT%\scripts\run_pipeline.py"+exit /b %ERRORLEVEL%diff --git a/ai_agents/devable_research_agent/scripts/run_pipeline.py b/ai_agents/devable_research_agent/scripts/run_pipeline.pynew file mode 100644index 0000000..0972ad6--- /dev/null+++ b/ai_agents/devable_research_agent/scripts/run_pipeline.py@@ -0,0 +1,137 @@+#!/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 subprocess+import sys+from datetime import datetime+from pathlib import Path++PROJECT_ROOT = 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"+++def _log(message: str) -> None:+ LOG_FILE.parent.mkdir(parents=True, exist_ok=True)+ timestamp = datetime.now().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",+ )+ 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 run_pipeline(date_str: str, depth: str = "default", top_n: int = 20) -> 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}")+ 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)")+ 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)",+ )+ 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)",+ )+ 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/update_openclaw_cron.py b/ai_agents/devable_research_agent/scripts/update_openclaw_cron.pynew file mode 100644index 0000000..361b513--- /dev/null+++ b/ai_agents/devable_research_agent/scripts/update_openclaw_cron.py@@ -0,0 +1,45 @@+#!/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.+"""++import json+import sys+from pathlib import Path++JOB_ID = "811ed28b-8ef8-45b5-a222-cb7d7150f1e0"+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+ if not JOBS_FILE.exists():+ print(f"Error: OpenClaw jobs file not found: {JOBS_FILE}", file=sys.stderr)+ return 1++ 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:+ job.setdefault("payload", {})["message"] = prompt+ updated = True+ break++ if not updated:+ print(f"Error: cron job not found: {JOB_ID}", file=sys.stderr)+ return 1++ 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+++if __name__ == "__main__":+ raise SystemExit(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.pynew file mode 100644index 0000000..45c737d--- /dev/null+++ b/ai_agents/devable_research_agent/skills/tracking-list/scripts/collect.py@@ -0,0 +1,307 @@+#!/usr/bin/env python3+"""devable-research-agent data collection orchestrator.++Runs all collectors concurrently, normalizes, scores, deduplicates,+and outputs a structured JSON report.++Usage:+ python3 skills/tracking-list/scripts/collect.py [--date YYYY-MM-DD] [--depth quick|default|deep] [--output PATH]+"""++import argparse+import json+import sys+import time+from concurrent.futures import ThreadPoolExecutor, as_completed+from datetime import datetime, timedelta, timezone+from pathlib import Path+from typing import Any, Dict, List, Optional++# Add project root to path for imports+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++from lib import env, cache+from lib.schema import TrackerItem, CollectionResult, DailyReport+from lib.score import score_items, apply_verification_bonus+from lib.dedupe import dedupe_by_source, cross_source_link+from lib.classify import classify_items+from lib import entities+from lib.util import log+++_log = lambda msg: log("collect", msg)+++def get_time_window(date_str: str) -> tuple:+ """Get 24-hour collection window (08:00 UTC+8 yesterday to 08:00 UTC+8 today).++ Returns:+ (from_date, to_date) as YYYY-MM-DD strings+ """+ dt = datetime.strptime(date_str, "%Y-%m-%d")+ from_date = (dt - timedelta(days=1)).strftime("%Y-%m-%d")+ to_date = date_str+ return from_date, to_date+++def collect_hackernews(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Collect from Hacker News."""+ from lib import hackernews+ return hackernews.collect(entities.HN_KEYWORDS, from_date, to_date, depth)+++def collect_github(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Collect from GitHub."""+ from lib import github++ token = env.get_key(config, "GITHUB_TOKEN")+ return github.collect(entities.GITHUB_SOURCES, from_date, to_date, token, depth)+++def collect_huggingface(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Collect from HuggingFace."""+ from lib import huggingface+ return huggingface.collect(entities.HUGGINGFACE_AUTHORS, from_date, to_date, depth)+++def collect_arxiv(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Collect from arXiv."""+ from lib import arxiv+ return arxiv.collect(entities.ARXIV_QUERIES, from_date, to_date, depth)+++def collect_tavily(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Collect X/Twitter and web signals via Tavily Search API."""+ from lib import tavily_collector++ api_key = env.get_key(config, "TAVILY_API_KEY")+ return tavily_collector.collect(+ entities.X_HANDLES_OFFICIAL,+ entities.X_HANDLES_KEY_PEOPLE,+ entities.WEB_QUERIES,+ from_date,+ to_date,+ api_key,+ depth,+ x_handles_kol=entities.X_HANDLES_KOL,+ )+++def collect_goodailist(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Scrape trending AI repos from Good AI List."""+ from lib import goodailist_scraper+ return goodailist_scraper.collect(+ entities.GITHUB_SOURCES,+ from_date,+ to_date,+ depth,+ )+++def collect_ainews(config: Dict[str, Any], from_date: str, to_date: str, depth: str) -> CollectionResult:+ """Collect AI engineering signals from AINews (smol.ai) RSS."""+ from lib import ainews_collector+ return ainews_collector.collect(from_date, to_date, depth)+++# All collectors with their names+COLLECTORS = {+ "tavily": collect_tavily,+ "goodailist": collect_goodailist,+ "ainews": collect_ainews,+ "hackernews": collect_hackernews,+ "github": collect_github,+ "huggingface": collect_huggingface,+ "arxiv": collect_arxiv,+}+++def run_collection(+ date_str: str,+ depth: str = "default",+ skip: Optional[List[str]] = None,+) -> DailyReport:+ """Run full data collection pipeline.++ Args:+ date_str: Target date YYYY-MM-DD+ depth: Collection depth (quick|default|deep)+ skip: Optional list of sources to skip (default: none — all collectors run).+ Deny-list semantics: forcing the caller to name what they skip+ ("--skip arxiv") makes the omission obvious in shell history.++ Returns:+ DailyReport with all collected, scored, and deduplicated items+ """+ config = env.get_config()+ from_date, to_date = get_time_window(date_str)+ available = env.get_available_sources(config)++ _log(f"Date: {date_str}, Window: {from_date} ~ {to_date}, Depth: {depth}")+ _log(f"Available sources: {[k for k, v in available.items() if v]}")++ # Determine which collectors to run (skip list is deny-list)+ skip_set = set(skip or [])+ unknown = skip_set - COLLECTORS.keys()+ if unknown:+ _log(f"Warning: unknown collector(s) in --skip (ignored): {sorted(unknown)}")+ known_skip = skip_set & COLLECTORS.keys()+ active_collectors = {+ name: func for name, func in COLLECTORS.items() if name not in known_skip+ }+ if known_skip:+ _log(f"Skipping collectors: {sorted(known_skip)}")+ if not active_collectors:+ raise ValueError(+ f"--skip excluded every collector. Valid sources: {sorted(COLLECTORS.keys())}"+ )++ # Run collectors concurrently+ start_time = time.time()+ collection_results = []+ all_items: List[TrackerItem] = []++ with ThreadPoolExecutor(max_workers=len(active_collectors)) as executor:+ futures = {+ executor.submit(func, config, from_date, to_date, depth): name+ for name, func in active_collectors.items()+ }++ for future in as_completed(futures):+ name = futures[future]+ try:+ result = future.result(timeout=600)+ collection_results.append(result)+ all_items.extend(result.items)+ _log(f"[{name}] Done: {len(result.items)} items, {len(result.errors)} errors")+ except Exception as e:+ _log(f"[{name}] Failed: {e}")+ collection_results.append(+ CollectionResult(source=name, errors=[str(e)])+ )++ collect_time = time.time() - start_time+ _log(f"Collection complete: {len(all_items)} raw items in {collect_time:.1f}s")++ # Pipeline: Classify → Score → Dedupe by source → Cross-source link → Verification bonus+ _log("Classifying content types...")+ all_items = classify_items(all_items)++ _log("Scoring items...")+ all_items = score_items(all_items)++ _log("Deduplicating within sources...")+ all_items = dedupe_by_source(all_items)+ _log(f"After source dedup: {len(all_items)} items")++ _log("Cross-source linking...")+ all_items = cross_source_link(all_items)++ _log("Applying verification bonus...")+ all_items = apply_verification_bonus(all_items)++ # Re-assign sequential IDs+ for i, item in enumerate(all_items):+ item.id = f"T{i + 1:03d}"++ # Build stats+ stats = {+ "total_raw": sum(len(r.items) for r in collection_results),+ "total_after_dedup": len(all_items),+ "by_source": {},+ "by_importance": {+ "9-10 (industry-changing)": len([i for i in all_items if i.importance >= 9]),+ "7-8 (important)": len([i for i in all_items if 7 <= i.importance < 9]),+ "5-6 (routine)": len([i for i in all_items if 5 <= i.importance < 7]),+ "3-4 (minor)": len([i for i in all_items if 3 <= i.importance < 5]),+ "1-2 (trivial)": len([i for i in all_items if i.importance < 3]),+ },+ "verified_count": len([i for i in all_items if i.verified]),+ "collection_time_seconds": round(collect_time, 1),+ "errors": [],+ }++ for r in collection_results:+ stats["by_source"][r.source] = {+ "items": len(r.items),+ "entities_checked": r.entities_checked,+ "entities_with_updates": r.entities_with_updates,+ "errors": r.errors,+ }+ stats["errors"].extend(r.errors)++ # Build report+ report = DailyReport(+ date=date_str,+ time_window=f"{from_date} 08:00 ~ {to_date} 08:00 UTC+8",+ generated_at=datetime.now(timezone.utc).isoformat(),+ items=all_items,+ collection_results=collection_results,+ stats=stats,+ )++ _log(f"Report ready: {len(all_items)} items, {stats['verified_count']} verified")+ return report+++def main():+ parser = argparse.ArgumentParser(description="devable-research-agent data collection")+ parser.add_argument("--date", default=datetime.now().strftime("%Y-%m-%d"),+ help="Target date (default: today)")+ parser.add_argument("--depth", default="default", choices=["quick", "default", "deep"],+ help="Collection depth")+ parser.add_argument("--skip", nargs="*", default=[],+ help="Sources to SKIP (default: none — all collectors run). "+ "Unknown names are ignored with a warning, "+ "e.g. --skip arxiv")+ parser.add_argument("--output", "-o", default=None,+ help="Output JSON file path (default: stdout)")+ parser.add_argument("--cache-ttl", type=int, default=1,+ help="Cache TTL in hours (default: 1, 0 to disable)")+ parser.add_argument("--no-cache", action="store_true",+ help="Skip cache entirely (equivalent to --cache-ttl 0)")+ parser.add_argument("--clear-cache", action="store_true",+ help="Clear all cached data and exit")+ args = parser.parse_args()++ # Clear cache and exit+ if args.clear_cache:+ cache.clear_cache()+ _log("Cache cleared")+ return++ # Check cache. Include the skip filter in the key so a partial run+ # (--skip arxiv) can't poison a subsequent full run.+ ttl = 0 if args.no_cache else args.cache_ttl+ skip_key = ",".join(sorted(args.skip)) if args.skip else "all"+ cache_key = cache.get_cache_key("daily", args.date, args.depth, skip_key)+ if ttl > 0:+ cached = cache.load_cache(cache_key, ttl)+ if cached:+ _log("Using cached report")+ if args.output:+ Path(args.output).write_text(json.dumps(cached, ensure_ascii=False, indent=2))+ else:+ json.dump(cached, sys.stdout, ensure_ascii=False, indent=2)+ return++ # Run collection+ report = run_collection(args.date, args.depth, args.skip)+ report_dict = report.to_dict()++ # Save cache+ if ttl > 0:+ cache.save_cache(cache_key, report_dict)++ # Output+ if args.output:+ output_path = Path(args.output)+ output_path.parent.mkdir(parents=True, exist_ok=True)+ output_path.write_text(json.dumps(report_dict, ensure_ascii=False, indent=2), encoding="utf-8")+ _log(f"Report saved to {args.output}")+ else:+ json.dump(report_dict, sys.stdout, ensure_ascii=False, indent=2)+++if __name__ == "__main__":+ main()