Skip to content

Convert Claude Code or Codex into the most intelligent Deep Research Agent. Collect, search, and synthesize web research into a persistent, searchable wiki that builds on itself. Hosted API + MCP: hyperresearch.ai

Major v0.2.0: crawl4ai integration, deep research skill, auth crawling, auto-curation

Jordan6b62d4c96baf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f14f05..b3893fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,7 +10,7 @@ Initial release. Forked from [llm-kasten](https://github.com/jordan-gibbs/llm-ka
- **`hyperresearch fetch <url>`** — Fetch a URL, extract content, save as a research note with source tracking
- **`hyperresearch research <topic>`** — Deep research: web search, fetch results, follow links, save as linked notes, generate synthesis MOC
- **`hyperresearch sources list/check`** — List and query fetched web sources
-- **Web provider plugin system** — Pluggable backends: builtin (stdlib), crawl4ai, tavily, firecrawl, trafilatura
+- **Web provider plugin system** — Pluggable backends: builtin (stdlib), crawl4ai (local headless browser)
- **Agent hook system** — PreToolUse hooks that remind agents to check the research base before web searches
- **Sources table** — URL deduplication, domain tracking, fetch metadata
- **Extended frontmatter** — `source_domain`, `fetched_at`, `fetch_provider` fields
diff --git a/README.md b/README.md
index 766adc6..d534c9e 100644
--- a/README.md
+++ b/README.md
@@ -35,7 +35,7 @@ hyperresearch install --platform all # Hook all supported platforms
# Collect
hyperresearch fetch <url> --tag t -j # Save a URL as a note
-hyperresearch research "topic" --max 5 -j # Search → fetch → link → synthesize (needs tavily)
+hyperresearch research "topic" --max 5 -j # Search → fetch → link → synthesize (needs crawl4ai)
# Search & read
hyperresearch search "query" -j # Full-text search
@@ -70,19 +70,35 @@ The hook doesn't block — it reminds the agent to check the research base first
## Web providers
-By default, agents use their own web tools (WebSearch, WebFetch) and pipe content into hyperresearch. For standalone/headless use, optional providers add direct fetching:
+By default, agents use their own web tools (WebSearch, WebFetch) and pipe content into hyperresearch. For JS-rendered pages, blocked sites, or authenticated content, install crawl4ai (local headless Chromium):
```bash
-pip install hyperresearch[tavily] # Search + extract API ($0.008/credit, 1k free/mo)
-pip install hyperresearch[crawl4ai] # Free, open-source, JS rendering
-pip install hyperresearch[firecrawl] # AI-optimized markdown extraction
-pip install hyperresearch[trafilatura] # Lightweight text extraction
+pip install hyperresearch[crawl4ai]
+crawl4ai-setup # Install browser (one-time)
```
Configure in `.hyperresearch/config.toml`:
```toml
[web]
-provider = "tavily" # or "crawl4ai", "firecrawl", "trafilatura", "builtin"
+provider = "crawl4ai" # or "builtin" (stdlib urllib, no JS)
+profile = "" # Browser profile name for authenticated crawling (optional)
+magic = false # Anti-bot stealth mode (recommended for social media)
+```
+
+### Authenticated crawling
+
+Access login-gated content (LinkedIn, Twitter, paywalled sites) by creating a login profile:
+
+```bash
+hyperresearch setup # Choose option 1 — browser opens, log into your sites, done
+# Or manually:
+crwl profiles # Create profile, log in, press q when done
+```
+
+```toml
+# .hyperresearch/config.toml
+[web]
+profile = "research" # Your profile name
```
## MCP server
diff --git a/pyproject.toml b/pyproject.toml
index ab4aa9c..c199993 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,11 +32,8 @@ dependencies = [
[project.optional-dependencies]
crawl4ai = ["Crawl4AI>=0.4"]
-tavily = ["tavily-python>=0.5"]
-firecrawl = ["firecrawl>=1.0"]
-trafilatura = ["trafilatura>=2.0"]
mcp = ["mcp>=1.6"]
-all = ["hyperresearch[crawl4ai,tavily,firecrawl,trafilatura,mcp]"]
+all = ["hyperresearch[crawl4ai,mcp]"]
dev = [
"pytest>=7.4",
"pytest-cov>=4.1",
diff --git a/src/hyperresearch/__main__.py b/src/hyperresearch/__main__.py
index d357ec9..7ef33c3 100644
--- a/src/hyperresearch/__main__.py
+++ b/src/hyperresearch/__main__.py
@@ -1,5 +1,5 @@
"""Allow running as `python -m hyperresearch`."""
-from hyperresearch.cli import app
+from hyperresearch.cli import app # encoding fix runs in cli/__init__.py
app()
diff --git a/src/hyperresearch/cli/__init__.py b/src/hyperresearch/cli/__init__.py
index cd80dca..e7db281 100644
--- a/src/hyperresearch/cli/__init__.py
+++ b/src/hyperresearch/cli/__init__.py
@@ -1,5 +1,21 @@
"""Hyperresearch CLI — main typer application."""
+import os
+import sys
+
+# Fix Windows console encoding — crawl4ai's rich logger uses Unicode chars that
+# crash on Windows cp1252 consoles. Reconfigure streams to UTF-8 at startup.
+if sys.platform == "win32":
+ os.environ["PYTHONIOENCODING"] = "utf-8"
+ os.environ["PYTHONUTF8"] = "1"
+ for stream_name in ("stdout", "stderr"):
+ stream = getattr(sys, stream_name)
+ if hasattr(stream, "reconfigure"):
+ try:
+ stream.reconfigure(encoding="utf-8", errors="replace")
+ except Exception:
+ pass
+
import typer
from hyperresearch import __version__
@@ -44,11 +60,19 @@ from hyperresearch.cli.tag import tag_list as _tags
from hyperresearch.cli.watch import watch as _watch
app.command("install")(_install)
+
+from hyperresearch.cli.setup import setup as _setup
+
+app.command("setup")(_setup)
app.command("init")(_init)
app.command("status")(_status)
app.command("sync")(_sync)
app.command("search")(_search)
app.command("fetch")(_fetch)
+
+from hyperresearch.cli.fetch_batch import fetch_batch as _fetch_batch
+
+app.command("fetch-batch")(_fetch_batch)
app.command("research")(_research)
app.command("tags")(_tags)
app.command("show", hidden=True)(_show)
@@ -84,6 +108,10 @@ app.add_typer(template_app, name="template", help="Note templates.")
app.add_typer(git_app, name="git", help="Git integration.")
app.add_typer(tag_app, name="tag", help="Tag management.")
+from hyperresearch.cli.assets import app as assets_app
+from hyperresearch.cli.link import app as link_app
from hyperresearch.cli.sources import app as sources_app
app.add_typer(sources_app, name="sources", help="Fetched web sources.")
+app.add_typer(assets_app, name="assets", help="Downloaded images, screenshots, and media.")
+app.add_typer(link_app, name="link", help="Auto-discover and insert wiki-links.")
diff --git a/src/hyperresearch/cli/assets.py b/src/hyperresearch/cli/assets.py
new file mode 100644
index 0000000..0510b5a
--- /dev/null
+++ b/src/hyperresearch/cli/assets.py
@@ -0,0 +1,114 @@
+"""Assets CLI — list and view downloaded images, screenshots, and other media."""
+
+from __future__ import annotations
+
+import typer
+
+from hyperresearch.cli._output import console, output
+from hyperresearch.models.output import error, success
+
+app = typer.Typer()
+
+
+def assets_list(
+ note_id: str | None = typer.Option(None, "--note", "-n", help="Filter by note ID"),
+ asset_type: str | None = typer.Option(None, "--type", "-t", help="Filter by type: image|screenshot|pdf"),
+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
+) -> None:
+ """List downloaded assets (images, screenshots, PDFs)."""
+ from hyperresearch.core.vault import Vault, VaultError
+
+ try:
+ vault = Vault.discover()
+ except VaultError as e:
+ if json_output:
+ output(error(str(e), "NO_VAULT"), json_mode=True)
+ else:
+ console.print(f"[red]Error:[/] {e}")
+ raise typer.Exit(1)
+
+ vault.auto_sync()
+ conn = vault.db
+
+ query = "SELECT * FROM assets WHERE 1=1"
+ params: list = []
+ if note_id:
+ query += " AND note_id = ?"
+ params.append(note_id)
+ if asset_type:
+ query += " AND type = ?"
+ params.append(asset_type)
+ query += " ORDER BY created_at DESC"
+
+ rows = conn.execute(query, params).fetchall()
+ assets = [
+ {
+ "id": row["id"],
+ "note_id": row["note_id"],
+ "type": row["type"],
+ "filename": row["filename"],
+ "url": row["url"],
+ "alt_text": row["alt_text"],
+ "content_type": row["content_type"],
+ "size_bytes": row["size_bytes"],
+ }
+ for row in rows
+ ]
+
+ if json_output:
+ output(success(assets, count=len(assets), vault=str(vault.root)), json_mode=True)
+ else:
+ if not assets:
+ console.print("[dim]No assets found.[/]")
+ return
+ for a in assets:
+ size = f"{a['size_bytes'] / 1024:.0f}KB" if a["size_bytes"] else "?"
+ alt = f" — {a['alt_text'][:60]}" if a["alt_text"] else ""
+ console.print(
+ f" [{a['type']}] {a['note_id']}: {a['filename']} ({size}){alt}"
+ )
+ console.print(f"\n[dim]{len(assets)} assets total[/]")
+
+
+def asset_path(
+ note_id: str = typer.Argument(..., help="Note ID"),
+ asset_type: str = typer.Option("screenshot", "--type", "-t", help="Asset type: screenshot|image"),
+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
+) -> None:
+ """Get the file path for a note's asset (for viewing with Read tool)."""
+ from hyperresearch.core.vault import Vault, VaultError
+
+ try:
+ vault = Vault.discover()
+ except VaultError as e:
+ if json_output:
+ output(error(str(e), "NO_VAULT"), json_mode=True)
+ else:
+ console.print(f"[red]Error:[/] {e}")
+ raise typer.Exit(1)
+
+ conn = vault.db
+ rows = conn.execute(
+ "SELECT filename, alt_text, size_bytes FROM assets WHERE note_id = ? AND type = ? ORDER BY id",
+ (note_id, asset_type),
+ ).fetchall()
+
+ if not rows:
+ if json_output:
+ output(error(f"No {asset_type} assets for note '{note_id}'", "NOT_FOUND"), json_mode=True)
+ else:
+ console.print(f"[yellow]No {asset_type} assets for note '{note_id}'[/]")
+ raise typer.Exit(1)
+
+ paths = [
+ {"path": row["filename"], "alt_text": row["alt_text"], "size_bytes": row["size_bytes"]}
+ for row in rows
+ ]
+
+ if json_output:
+ output(success(paths, count=len(paths), vault=str(vault.root)), json_mode=True)
+ else:
+ for p in paths:
+ console.print(p["path"])
diff --git a/src/hyperresearch/cli/batch.py b/src/hyperresearch/cli/batch.py
index 289443c..7f5da31 100644
--- a/src/hyperresearch/cli/batch.py
+++ b/src/hyperresearch/cli/batch.py
@@ -225,7 +225,6 @@ def batch_set_status(
@app.command("deprecate")
def batch_deprecate(
- superseded_by: str | None = typer.Option(None, "--superseded-by", help="Note ID of replacement"),
status: str | None = typer.Option(None, "--status", "-s", help="Filter by status"),
tag: str | None = typer.Option(None, "--tag", "-t", help="Filter by tag"),
parent: str | None = typer.Option(None, "--parent", "-p", help="Filter by parent topic"),
@@ -239,7 +238,7 @@ def batch_deprecate(
if dry_run:
if json_output:
- output(success({"action": "deprecate", "superseded_by": superseded_by,
+ output(success({"action": "deprecate",
"would_modify": [n["id"] for n in notes]},
count=len(notes), vault=str(vault.root)), json_mode=True)
else:
@@ -247,8 +246,6 @@ def batch_deprecate(
return
updates = {"status": "deprecated", "deprecated": True}
- if superseded_by:
- updates["superseded_by"] = superseded_by
for n in notes:
_update_file_frontmatter(vault.root, n["path"], updates)
diff --git a/src/hyperresearch/cli/config_cmd.py b/src/hyperresearch/cli/config_cmd.py
index 9d46653..3c7b873 100644
--- a/src/hyperresearch/cli/config_cmd.py
+++ b/src/hyperresearch/cli/config_cmd.py
@@ -24,6 +24,9 @@ def config_show(
"vault_name": config.name,
"vault_path": str(vault.root),
"research_dir": config.research_dir,
+ "web_provider": config.web_provider,
+ "web_profile": config.web_profile or "(none)",
+ "web_magic": config.web_magic,
"auto_sync": config.auto_sync,
"auto_build_index": config.auto_build_index,
"search_boost_evergreen": config.search_boost_evergreen,
@@ -54,6 +57,9 @@ def config_set(
key_map = {
"vault.name": "name",
"vault.research_dir": "research_dir",
+ "web.provider": "web_provider",
+ "web.profile": "web_profile",
+ "web.magic": "web_magic",
"search.boost_evergreen": "search_boost_evergreen",
"search.penalize_deprecated": "search_penalize_deprecated",
"sync.auto_sync": "auto_sync",
@@ -67,7 +73,7 @@ def config_set(
raise typer.Exit(1)
# Type coercion
- if attr in ("auto_sync", "auto_build_index"):
+ if attr in ("auto_sync", "auto_build_index", "web_magic"):
value = value.lower() in ("true", "1", "yes")
setattr(config, attr, value)
@@ -93,6 +99,9 @@ def config_get(
key_map = {
"vault.name": "name",
"vault.research_dir": "research_dir",
+ "web.provider": "web_provider",
+ "web.profile": "web_profile",
+ "web.magic": "web_magic",
"search.boost_evergreen": "search_boost_evergreen",
"search.penalize_deprecated": "search_penalize_deprecated",
"sync.auto_sync": "auto_sync",
diff --git a/src/hyperresearch/cli/dedup.py b/src/hyperresearch/cli/dedup.py
index e961dc7..c97513b 100644
--- a/src/hyperresearch/cli/dedup.py
+++ b/src/hyperresearch/cli/dedup.py
@@ -1,13 +1,21 @@
-"""Content deduplication — find near-duplicate notes."""
+"""Content deduplication — find near-duplicate notes using MinHash+LSH."""
from __future__ import annotations
import typer
from hyperresearch.cli._output import console, output
-from hyperresearch.core.similarity import jaccard, shingle
+from hyperresearch.core.similarity import (
+ jaccard,
+ lsh_candidates,
+ minhash_signature,
+ shingle,
+)
from hyperresearch.models.output import success
+# Use MinHash+LSH for vaults above this size, O(n^2) below
+LSH_THRESHOLD = 200
+
def dedup(
threshold: float = typer.Option(0.6, "--threshold", "-t", help="Similarity threshold (0.0-1.0)"),
@@ -44,27 +52,23 @@ def dedup(
return
# Build shingle sets
- notes = []
+ notes = {}
for row in rows:
shingles = shingle(row["body_plain"])
- notes.append({
+ notes[row["id"]] = {
"id": row["id"],
"title": row["title"],
"word_count": row["word_count"],
"shingles": shingles,
- })
+ }
- # Compare all pairs
- pairs = []
- for i in range(len(notes)):
- for j in range(i + 1, len(notes)):
- sim = jaccard(notes[i]["shingles"], notes[j]["shingles"])
- if sim >= threshold:
- pairs.append({
- "similarity": round(sim, 3),
- "note_a": {"id": notes[i]["id"], "title": notes[i]["title"], "words": notes[i]["word_count"]},
- "note_b": {"id": notes[j]["id"], "title": notes[j]["title"], "words": notes[j]["word_count"]},
- })
+ # Choose algorithm based on vault size
+ if len(notes) >= LSH_THRESHOLD:
+ pairs = _dedup_lsh(notes, threshold)
+ method = "minhash+lsh"
+ else:
+ pairs = _dedup_brute(notes, threshold)
+ method = "brute-force"
pairs.sort(key=lambda p: p["similarity"], reverse=True)
pairs = pairs[:limit]
@@ -73,16 +77,18 @@ def dedup(
if json_output:
output(
- success({"pairs": pairs, "total_compared": total_compared, "threshold": threshold},
- count=len(pairs), vault=str(vault.root)),
+ success(
+ {"pairs": pairs, "total_compared": total_compared, "threshold": threshold, "method": method},
+ count=len(pairs), vault=str(vault.root),
+ ),
json_mode=True,
)
else:
if not pairs:
- console.print(f"[green]No duplicates found (threshold {threshold:.0%}, compared {total_compared} pairs).[/]")
+ console.print(f"[green]No duplicates found (threshold {threshold:.0%}, {method}).[/]")
return
- console.print(f"[bold]Similar notes (>{threshold:.0%}):[/]\n")
+ console.print(f"[bold]Similar notes (>{threshold:.0%}, {method}):[/]\n")
for p in pairs:
a, b = p["note_a"], p["note_b"]
console.print(
@@ -90,4 +96,43 @@ def dedup(
f"[cyan]{a['id']}[/] ({a['words']}w) "
f"<-> [cyan]{b['id']}[/] ({b['words']}w)"
)
- console.print(f"\n[dim]Compared {total_compared} pairs.[/]")
+ console.print(f"\n[dim]{len(notes)} notes, {method}.[/]")
+
+
+def _dedup_brute(notes: dict, threshold: float) -> list[dict]:
+ """O(n^2) brute-force comparison for small vaults."""
+ note_list = list(notes.values())
+ pairs = []
+ for i in range(len(note_list)):
+ for j in range(i + 1, len(note_list)):
+ sim = jaccard(note_list[i]["shingles"], note_list[j]["shingles"])
+ if sim >= threshold:
+ pairs.append(_make_pair(note_list[i], note_list[j], sim))
+ return pairs
+
+
+def _dedup_lsh(notes: dict, threshold: float) -> list[dict]:
+ """MinHash+LSH for large vaults — approximate but O(n)."""
+ # Compute signatures
+ signatures = {}
+ for nid, note in notes.items():
+ signatures[nid] = minhash_signature(note["shingles"])
+
+ # Find candidate pairs via LSH
+ candidates = lsh_candidates(signatures)
+
+ # Verify candidates with exact Jaccard
+ pairs = []
+ for id_a, id_b in candidates:
+ sim = jaccard(notes[id_a]["shingles"], notes[id_b]["shingles"])
+ if sim >= threshold:
+ pairs.append(_make_pair(notes[id_a], notes[id_b], sim))
+ return pairs
+
+
+def _make_pair(a: dict, b: dict, sim: float) -> dict:
+ return {
+ "similarity": round(sim, 3),
+ "note_a": {"id": a["id"], "title": a["title"], "words": a["word_count"]},
+ "note_b": {"id": b["id"], "title": b["title"], "words": b["word_count"]},
+ }
diff --git a/src/hyperresearch/cli/fetch.py b/src/hyperresearch/cli/fetch.py
index b56fac7..54f427e 100644
--- a/src/hyperresearch/cli/fetch.py
+++ b/src/hyperresearch/cli/fetch.py
@@ -3,6 +3,9 @@
from __future__ import annotations
import hashlib
+import re
+from datetime import UTC, datetime
+from pathlib import Path
from urllib.parse import urlparse
import typer
@@ -12,6 +15,20 @@ from hyperresearch.models.output import error, success
app = typer.Typer()
+# Max images to download per fetch
+MAX_IMAGES = 5
+# Skip small images (icons, logos, spacers, tracking pixels, nav elements)
+MIN_IMAGE_BYTES = 50_000
+# URL patterns that are almost never content images
+SKIP_URL_PATTERNS = (
+ "logo", "icon", "favicon", "badge", "avatar", "sprite", "banner",
+ "ad-", "ads/", "advert", "tracking", "pixel", "analytics",
+ "button", "arrow", "caret", "spinner", "loader",
+ "gravatar.com", "googleusercontent.com/a/", "shields.io",
+ "github.com/fluidicon", "platform-lookaside", "syndication",
+ "facebook.com", "twitter.com/favicon", "linkedin.com/li/",
+)
+
@app.command("fetch")
def fetch(
@@ -20,6 +37,8 @@ def fetch(
title: str | None = typer.Option(None, "--title", help="Override title"),
parent: str | None = typer.Option(None, "--parent", "-p", help="Parent topic"),
provider_name: str | None = typer.Option(None, "--provider", help="Web provider override"),
+ save_assets: bool = typer.Option(False, "--save-assets", "-a", help="Download images and screenshot"),
+ visible: bool = typer.Option(False, "--visible", "-V", help="Run browser visibly (for stubborn auth sites)"),
json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
) -> None:
"""Fetch a URL and save its content as a research note."""
@@ -53,8 +72,25 @@ def fetch(
console.print(f"[yellow]Already fetched:[/] {url} → note '{note_id}'")
raise typer.Exit(1)
+ # Auto-visible for sites that kill headless sessions on first contact
+ if not visible and vault.config.web_profile:
+ from urllib.parse import urlparse as _urlparse
+
+ domain = _urlparse(url).netloc.lower()
+ _auth_aggressive_domains = (
+ "linkedin.com", "twitter.com", "x.com", "facebook.com",
+ "instagram.com", "tiktok.com",
+ )
+ if any(d in domain for d in _auth_aggressive_domains):
+ visible = True
+
# Fetch content
- prov = get_provider(provider_name or vault.config.web_provider)
+ prov = get_provider(
+ provider_name or vault.config.web_provider,
+ profile=vault.config.web_profile,
+ magic=vault.config.web_magic,
+ headless=not visible,
+ )
if not json_output:
console.print(f"[dim]Fetching with {prov.name}...[/]")
@@ -67,6 +103,19 @@ def fetch(
console.print(f"[red]Fetch failed:[/] {e}")
raise typer.Exit(1)
+ # Detect login redirects — abort instead of saving login page junk
+ if result.looks_like_login_wall(url):
+ msg = (
+ f"Redirected to login page ({result.title}). "
+ "Try --visible flag (runs browser non-headless, sites are less aggressive). "
+ "If that fails, re-create your login profile with 'hyperresearch setup'."
+ )
+ if json_output:
+ output(error(msg, "AUTH_REQUIRED"), json_mode=True)
+ else:
+ console.print(f"[red]Auth required:[/] {msg}")
+ raise typer.Exit(1)
+
# Write note
note_title = title or result.title or urlparse(url).path.split("/")[-1] or "Untitled"
domain = result.domain
@@ -91,9 +140,19 @@ def fetch(
extra_frontmatter=extra_meta,
)
+ # Auto-enrich: add suggested tags and summary before sync
+ from hyperresearch.core.enrich import enrich_note_file
+
+ enrich_note_file(note_path, conn, tags)
+
+ # Sync first so the note exists in the notes table (needed for FK on sources/assets)
+ note_id = note_path.stem
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
# Record source in DB
content_hash = hashlib.sha256(result.content.encode("utf-8")).hexdigest()[:16]
- note_id = note_path.stem
conn.execute(
"""INSERT INTO sources (url, note_id, domain, fetched_at, provider, content_hash)
VALUES (?, ?, ?, ?, ?, ?)""",
@@ -101,10 +160,11 @@ def fetch(
)
conn.commit()
- # Sync to index the new note
- plan = compute_sync_plan(vault)
- if plan.to_add or plan.to_update:
- execute_sync(vault, plan)
+ # Save assets (screenshot + images) — only when requested
+ saved_assets: list[dict] = []
+ if save_assets:
+ assets_dir = vault.root / "research" / "assets" / note_id
+ saved_assets = _save_assets(conn, result, note_id, assets_dir)
data = {
"note_id": note_id,
@@ -114,6 +174,7 @@ def fetch(
"provider": prov.name,
"path": str(note_path.relative_to(vault.root)),
"word_count": len(result.content.split()),
+ "assets": saved_assets,
}
if json_output:
@@ -123,3 +184,111 @@ def fetch(
console.print(f" ID: {note_id}")
console.print(f" Source: {url}")
console.print(f" Words: {data['word_count']}")
+ if saved_assets:
+ console.print(f" Assets: {len(saved_assets)} saved to research/assets/{note_id}/")
+
+
+def _save_assets(conn, result, note_id: str, assets_dir: Path) -> list[dict]:
+ """Save screenshot and images to assets dir, record in DB. Returns list of saved asset info."""
+ saved: list[dict] = []
+ now = datetime.now(UTC).isoformat()
+
+ # Save screenshot
+ if result.screenshot:
+ assets_dir.mkdir(parents=True, exist_ok=True)
+ screenshot_path = assets_dir / "screenshot.png"
+ screenshot_path.write_bytes(result.screenshot)
+ conn.execute(
+ """INSERT INTO assets (note_id, type, filename, alt_text, content_type, size_bytes, created_at)
+ VALUES (?, 'screenshot', ?, 'Page screenshot', 'image/png', ?, ?)""",
+ (note_id, str(screenshot_path), len(result.screenshot), now),
+ )
+ saved.append({
+ "type": "screenshot",
+ "path": str(screenshot_path),
+ "size_bytes": len(result.screenshot),
+ })
+
+ # Download images — only content-relevant ones
+ if result.media:
+ # Filter out junk before sorting
+ candidates = []
+ for img in result.media:
+ img_url = img.get("src", "")
+ if not img_url or not img_url.startswith("http"):
+ continue
+ url_lower = img_url.lower()
+ if any(skip in url_lower for skip in SKIP_URL_PATTERNS):
+ continue
+ # Skip SVGs (usually icons/diagrams that don't render well saved)
+ if url_lower.endswith(".svg"):
+ continue
+ candidates.append(img)
+
+ # Sort by score descending, take top N
+ candidates.sort(key=lambda m: m.get("score", 0), reverse=True)
+ for img in candidates[:MAX_IMAGES]:
+ img_url = img.get("src", "")
+ alt = img.get("alt", "") or ""
+ asset_info = _download_image(conn, note_id, img_url, alt, assets_dir, now)
+ if asset_info:
+ saved.append(asset_info)
+
+ if saved:
+ conn.commit()
+
+ return saved
+
+
+def _download_image(conn, note_id: str, img_url: str, alt: str, assets_dir: Path, now: str) -> dict | None:
+ """Download a single image. Returns asset info dict or None if skipped."""
+ import urllib.request
+
+ # Generate filename from URL
+ parsed = urlparse(img_url)
+ url_path = parsed.path.rstrip("/")
+ ext = Path(url_path).suffix.lower() if url_path else ""
+ if ext not in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".avif"):
+ ext = ".jpg"
+
+ # Clean filename from URL path
+ raw_name = Path(url_path).stem if url_path else "image"
+ clean_name = re.sub(r"[^\w\-.]", "_", raw_name)[:80]
+ filename = f"{clean_name}{ext}"
+
+ assets_dir.mkdir(parents=True, exist_ok=True)
+ file_path = assets_dir / filename
+
+ # Handle collision
+ counter = 2
+ while file_path.exists():
+ file_path = assets_dir / f"{clean_name}-{counter}{ext}"
+ counter += 1
+
+ try:
+ req = urllib.request.Request(img_url, headers={"User-Agent": "hyperresearch/0.1"})
+ with urllib.request.urlopen(req, timeout=15) as resp:
+ data = resp.read()
+ content_type = resp.headers.get("Content-Type", "")
+ except Exception:
+ return None
+
+ # Skip tiny images (icons, spacers, tracking pixels)
+ if len(data) < MIN_IMAGE_BYTES:
+ return None
+
+ file_path.write_bytes(data)
+
+ conn.execute(
+ """INSERT INTO assets (note_id, type, filename, url, alt_text, content_type, size_bytes, created_at)
+ VALUES (?, 'image', ?, ?, ?, ?, ?, ?)""",
+ (note_id, str(file_path), img_url, alt, content_type, len(data), now),
+ )
+
+ return {
+ "type": "image",
+ "path": str(file_path),
+ "url": img_url,
+ "alt": alt,
+ "size_bytes": len(data),
+ }
diff --git a/src/hyperresearch/cli/fetch_batch.py b/src/hyperresearch/cli/fetch_batch.py
new file mode 100644
index 0000000..3f64262
--- /dev/null
+++ b/src/hyperresearch/cli/fetch_batch.py
@@ -0,0 +1,231 @@
+"""Batch fetch — fetch multiple URLs in one command with batched sync."""
+
+from __future__ import annotations
+
+import hashlib
+import sys
+from urllib.parse import urlparse
+
+import typer
+
+from hyperresearch.cli._output import console, output
+from hyperresearch.models.output import error, success
+
+
+def fetch_batch(
+ urls: list[str] = typer.Argument(None, help="URLs to fetch"),
+ stdin: bool = typer.Option(False, "--stdin", help="Read URLs from stdin (one per line)"),
+ tags: list[str] = typer.Option([], "--tag", "-t", help="Tags for all notes"),
+ parent: str | None = typer.Option(None, "--parent", "-p", help="Parent topic"),
+ provider_name: str | None = typer.Option(None, "--provider", help="Web provider override"),
+ save_assets: bool = typer.Option(False, "--save-assets", "-a", help="Download images and screenshots"),
+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
+) -> None:
+ """Fetch multiple URLs and save each as a research note. Batched sync for speed."""
+ from hyperresearch.core.enrich import enrich_note_file
+ from hyperresearch.core.note import write_note
+ from hyperresearch.core.sync import compute_sync_plan, execute_sync
+ from hyperresearch.core.vault import Vault, VaultError
+ from hyperresearch.web.base import get_provider
+
+ # Collect URLs from args and/or stdin
+ all_urls = list(urls or [])
+ if stdin:
+ for line in sys.stdin:
+ line = line.strip()
+ if line and line.startswith("http"):
+ all_urls.append(line)
+
+ if not all_urls:
+ if json_output:
+ output(error("No URLs provided", "NO_INPUT"), json_mode=True)
+ else:
+ console.print("[red]No URLs provided.[/] Pass URLs as arguments or use --stdin.")
+ raise typer.Exit(1)
+
+ try:
+ vault = Vault.discover()
+ except VaultError as e:
+ if json_output:
+ output(error(str(e), "NO_VAULT"), json_mode=True)
+ else:
+ console.print(f"[red]Error:[/] {e}")
+ raise typer.Exit(1)
+
+ vault.auto_sync()
+ conn = vault.db
+
+ _auth_aggressive = (
+ "linkedin.com", "twitter.com", "x.com", "facebook.com",
+ "instagram.com", "tiktok.com",
+ )
+
+ def _needs_visible(fetch_url: str) -> bool:
+ if not vault.config.web_profile:
+ return False
+ domain = urlparse(fetch_url).netloc.lower()
+ return any(d in domain for d in _auth_aggressive)
+
+ prov = get_provider(
+ provider_name or vault.config.web_provider,
+ profile=vault.config.web_profile,
+ magic=vault.config.web_magic,
+ )
+
+ # Filter out already-fetched URLs
+ new_urls = []
+ for url in all_urls:
+ existing = conn.execute("SELECT note_id FROM sources WHERE url = ?", (url,)).fetchone()
+ if existing:
+ if not json_output:
+ console.print(f" [dim]Skip:[/] {url} (already fetched as {existing['note_id']})")
+ else:
+ new_urls.append(url)
+
+ if not new_urls:
+ if json_output:
+ output(success({"notes_created": [], "skipped": len(all_urls)}, vault=str(vault.root)), json_mode=True)
+ else:
+ console.print("[dim]All URLs already fetched.[/]")
+ return
+
+ if not json_output:
+ console.print(f"[bold]Fetching {len(new_urls)} URLs with {prov.name}...[/]")
+
+ # Split URLs into normal (headless batch) and auth-aggressive (visible, sequential)
+ normal_urls = [u for u in new_urls if not _needs_visible(u)]
+ visible_urls = [u for u in new_urls if _needs_visible(u)]
+
+ results = []
+
+ # Batch fetch normal URLs
+ if normal_urls:
+ if hasattr(prov, "fetch_many"):
+ try:
+ results.extend(prov.fetch_many(normal_urls))
+ except Exception as e:
+ if not json_output:
+ console.print(f"[red]Batch fetch failed:[/] {e}")
+ else:
+ for url in normal_urls:
+ try:
+ results.append(prov.fetch(url))
+ except Exception as e:
+ if not json_output:
+ console.print(f" [red]Failed:[/] {url} — {e}")
+
+ # Fetch auth-aggressive URLs with visible browser (sequential)
+ if visible_urls:
+ visible_prov = get_provider(
+ provider_name or vault.config.web_provider,
+ profile=vault.config.web_profile,
+ magic=vault.config.web_magic,
+ headless=False,
+ )
+ for url in visible_urls:
+ try:
+ results.append(visible_prov.fetch(url))
+ except Exception as e:
+ if not json_output:
+ console.print(f" [red]Failed (visible):[/] {url} — {e}")
+
+ # Phase 1: Write all note files to disk (no sync yet)
+ note_files = [] # (note_path, url, result, domain, content_hash)
+ for result in results:
+ url = result.url
+
+ # Skip login redirects
+ if result.looks_like_login_wall(url):
+ if not json_output:
+ console.print(
+ f" [yellow]Auth required:[/] {url} — login page detected, skipping. "
+ "Run 'hyperresearch setup' to create a login profile."
+ )
+ continue
+
+ title = result.title or urlparse(url).path.split("/")[-1] or "Untitled"
+ domain = result.domain
+
+ extra_meta = {
+ "source": url,
+ "source_domain": domain,
+ "fetched_at": result.fetched_at.isoformat(),
+ "fetch_provider": prov.name,
+ }
+
+ note_path = write_note(
+ vault.notes_dir,
+ title=title,
+ body=result.content,
+ tags=tags,
+ status="draft",
+ source=url,
+ parent=parent,
+ extra_frontmatter=extra_meta,
+ )
+
+ # Auto-enrich before sync
+ enrich_note_file(note_path, conn, tags)
+
+ content_hash = hashlib.sha256(result.content.encode("utf-8")).hexdigest()[:16]
+ note_files.append((note_path, url, result, domain, content_hash))
+
+ if not json_output:
+ console.print(f" [green]+[/] {title}")
+
+ # Phase 2: ONE sync to index all notes
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
+ # Phase 3: Bulk-insert source records
+ created_notes = []
+ for note_path, url, result, domain, content_hash in note_files:
+ note_id = note_path.stem
+ conn.execute(
+ """INSERT OR IGNORE INTO sources (url, note_id, domain, fetched_at, provider, content_hash)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (url, note_id, domain, result.fetched_at.isoformat(), prov.name, content_hash),
+ )
+
+ # Save assets if requested
+ if save_assets:
+ from hyperresearch.cli.fetch import _save_assets
+
+ assets_dir = vault.root / "research" / "assets" / note_id
+ _save_assets(conn, result, note_id, assets_dir)
+
+ created_notes.append({
+ "note_id": note_id,
+ "title": result.title or "Untitled",
+ "url": url,
+ "domain": domain,
+ "word_count": len(result.content.split()),
+ })
+
+ conn.commit()
+
+ # Phase 4: Auto-link across all new notes
+ if created_notes:
+ from hyperresearch.core.linker import auto_link
+
+ note_ids = [n["note_id"] for n in created_notes]
+ link_report = auto_link(vault, note_ids)
+ if link_report:
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
+ data = {
+ "notes_created": created_notes,
+ "total_fetched": len(created_notes),
+ "skipped": len(all_urls) - len(new_urls),
+ }
+
+ if json_output:
+ output(success(data, count=len(created_notes), vault=str(vault.root)), json_mode=True)
+ else:
+ console.print(
+ f"\n[bold]Done:[/] {len(created_notes)} notes created, "
+ f"{len(all_urls) - len(new_urls)} skipped (already fetched)."
+ )
diff --git a/src/hyperresearch/cli/install.py b/src/hyperresearch/cli/install.py
index 0e90bce..21c1b6d 100644
--- a/src/hyperresearch/cli/install.py
+++ b/src/hyperresearch/cli/install.py
@@ -28,11 +28,22 @@ def install(
json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
) -> None:
"""Install hyperresearch: init vault + inject agent docs + install hooks."""
+ import sys
+
from hyperresearch.core.hooks import install_hooks
from hyperresearch.core.vault import Vault, VaultError
root = Path(path).resolve()
+ # First-time install in an interactive terminal → run the setup TUI instead
+ is_new = not (root / ".hyperresearch").exists()
+ is_interactive = not json_output and sys.stdin.isatty()
+ if is_new and is_interactive:
+ from hyperresearch.cli.setup import setup
+
+ setup(path=path, json_output=False)
+ return
+
# Step 1: Init vault (skip if already exists)
try:
vault = Vault.discover(root)
@@ -48,15 +59,28 @@ def install(
console.print(f"[red]Error:[/] {e}")
raise typer.Exit(1)
- # Step 2: Install hooks
- hook_actions = install_hooks(root, platforms=platforms)
+ # Step 2: Resolve the hyperresearch executable path
+ from hyperresearch.core.agent_docs import _resolve_executable, inject_agent_docs
+
+ hpr_path = _resolve_executable()
+
+ # Step 3: Always re-inject agent docs (updates CLAUDE.md etc. with latest blurb + path)
+ doc_actions = inject_agent_docs(root, agents=agents)
+
+ # Step 4: Install hooks (with resolved path baked in)
+ hook_actions = install_hooks(root, platforms=platforms, hpr_path=hpr_path)
- # Step 3: Report
+ # Step 3: Auto-configure crawl4ai if installed
+ crawl4ai_status = _setup_crawl4ai(vault)
+
+ # Step 5: Report
data = {
"vault_path": str(vault.root),
"vault": vault_action,
+ "agent_docs": doc_actions,
"hooks_installed": hook_actions,
"platforms": platforms,
+ "crawl4ai": crawl4ai_status,
}
if json_output:
@@ -67,6 +91,11 @@ def install(
else:
console.print(f"[dim]Vault exists:[/] {vault.root}")
+ if doc_actions:
+ console.print("[green]Agent docs:[/]")
+ for action in doc_actions:
+ console.print(f" {action}")
+
if hook_actions:
console.print("[green]Hooks installed:[/]")
for action in hook_actions:
@@ -74,4 +103,58 @@ def install(
else:
console.print("[dim]All hooks already installed.[/]")
+ if crawl4ai_status == "configured":
+ console.print("[green]crawl4ai:[/] detected, set as default provider + browser ready")
+ elif crawl4ai_status == "browser_installed":
+ console.print("[green]crawl4ai:[/] browser installed + set as default provider")
+ elif crawl4ai_status == "not_installed":
+ console.print(
+ "[dim]crawl4ai:[/] not installed. "
+ "For local headless browsing: pip install hyperresearch[crawl4ai]"
+ )
+
console.print("\n[bold]Ready.[/] Agents will now check the research base before web searches.")
+ console.print("[dim]Tip: Run 'hyperresearch setup' for interactive configuration (profile, stealth, etc.)[/]")
+
+
+def _setup_crawl4ai(vault) -> str:
+ """Detect crawl4ai, install browser if needed, set as default provider.
+
+ Returns: 'configured' (already ready), 'browser_installed' (just set up),
+ 'not_installed' (crawl4ai not available).
+ """
+ try:
+ import crawl4ai # noqa: F401
+ except ImportError:
+ return "not_installed"
+
+ # Set crawl4ai as the default provider if still on builtin
+ if vault.config.web_provider == "builtin":
+ vault.config.web_provider = "crawl4ai"
+ vault.config.save(vault.config_path)
+
+ # Check if browser is already installed
+ try:
+ from playwright.sync_api import sync_playwright
+
+ pw = sync_playwright().start()
+ browser = pw.chromium.launch(headless=True)
+ browser.close()
+ pw.stop()
+ return "configured"
+ except Exception:
+ pass
+
+ # Try to install the browser
+ import subprocess
+ import sys
+
+ try:
+ subprocess.run(
+ [sys.executable, "-m", "playwright", "install", "chromium"],
+ check=True,
+ capture_output=True,
+ )
+ return "browser_installed"
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ return "configured" # best effort — user can install manually
diff --git a/src/hyperresearch/cli/link.py b/src/hyperresearch/cli/link.py
new file mode 100644
index 0000000..70e5c18
--- /dev/null
+++ b/src/hyperresearch/cli/link.py
@@ -0,0 +1,81 @@
+"""Link command — auto-discover and insert wiki-links between related notes."""
+
+from __future__ import annotations
+
+import typer
+
+from hyperresearch.cli._output import console, output
+from hyperresearch.models.output import error, success
+
+app = typer.Typer()
+
+
[email protected](invoke_without_command=True)
+def link(
+ ctx: typer.Context,
+ auto: bool = typer.Option(False, "--auto", "-a", help="Auto-link all notes"),
+ tag: str | None = typer.Option(None, "--tag", "-t", help="Only process notes with this tag"),
+ note_ids: list[str] = typer.Option([], "--note", "-n", help="Only process specific notes"),
+ dry_run: bool = typer.Option(False, "--dry-run", help="Show what links would be added"),
+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
+) -> None:
+ """Auto-discover and insert wiki-links between related notes."""
+ if ctx.invoked_subcommand is not None:
+ return
+
+ from hyperresearch.core.linker import auto_link
+ from hyperresearch.core.sync import compute_sync_plan, execute_sync
+ from hyperresearch.core.vault import Vault, VaultError
+
+ try:
+ vault = Vault.discover()
+ except VaultError as e:
+ if json_output:
+ output(error(str(e), "NO_VAULT"), json_mode=True)
+ else:
+ console.print(f"[red]Error:[/] {e}")
+ raise typer.Exit(1)
+
+ vault.auto_sync()
+
+ # Determine which notes to process
+ ids_to_process = list(note_ids) if note_ids else None
+
+ if tag and not ids_to_process:
+ rows = vault.db.execute(
+ "SELECT note_id FROM tags WHERE tag = ?", (tag.lower(),)
+ ).fetchall()
+ ids_to_process = [r["note_id"] for r in rows]
+
+ if not auto and not ids_to_process:
+ if json_output:
+ output(error("Use --auto to link all notes, or --note/--tag to filter", "NO_INPUT"), json_mode=True)
+ else:
+ console.print("[yellow]Use --auto to link all notes, or --note/--tag to filter.[/]")
+ raise typer.Exit(1)
+
+ report = auto_link(vault, ids_to_process)
+
+ # Sync to pick up the modified files
+ if report and not dry_run:
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
+ total_links = sum(len(v) for v in report.values())
+
+ if json_output:
+ output(
+ success(
+ {"links_added": report, "notes_modified": len(report), "total_links": total_links},
+ vault=str(vault.root),
+ ),
+ json_mode=True,
+ )
+ else:
+ if report:
+ for nid, linked in report.items():
+ console.print(f" [green]+[/] {nid} → {', '.join(linked)}")
+ console.print(f"\n[bold]{total_links} links added across {len(report)} notes.[/]")
+ else:
+ console.print("[dim]No new links found.[/]")
diff --git a/src/hyperresearch/cli/lint.py b/src/hyperresearch/cli/lint.py
index d7a6404..3e683f1 100644
--- a/src/hyperresearch/cli/lint.py
+++ b/src/hyperresearch/cli/lint.py
@@ -22,9 +22,7 @@ RULES = {
"empty-notes": "Notes with no body content",
"stale-indexes": "Index pages that need rebuilding",
"expired-notes": "Notes past their expiry date",
- "deprecated-no-successor": "Deprecated notes without a superseded_by link",
"stale-reviews": "Notes not reviewed in over 90 days",
- "low-confidence": "Notes with confidence < 0.5",
}
@@ -168,19 +166,6 @@ def lint(
"message": f"Note expired on {row['expires']}. Review or update.",
})
- if "deprecated-no-successor" in rules_to_run:
- for row in conn.execute(
- "SELECT id, path FROM notes "
- "WHERE (deprecated = 1 OR status = 'deprecated') AND superseded_by IS NULL"
- ):
- issues.append({
- "rule": "deprecated-no-successor",
- "severity": "warning",
- "note_id": row["id"],
- "note_path": row["path"],
- "message": "Deprecated but no superseded_by link. What replaces this?",
- })
-
if "stale-reviews" in rules_to_run:
from datetime import datetime, timedelta
cutoff = (datetime.now(UTC) - timedelta(days=90)).isoformat()
@@ -197,19 +182,6 @@ def lint(
"message": f"Last reviewed {row['reviewed'][:10]}. Consider re-reviewing.",
})
- if "low-confidence" in rules_to_run:
- for row in conn.execute(
- "SELECT id, path, confidence FROM notes "
- "WHERE confidence IS NOT NULL AND confidence < 0.5 AND status != 'deprecated'"
- ):
- issues.append({
- "rule": "low-confidence",
- "severity": "info",
- "note_id": row["id"],
- "note_path": row["path"],
- "message": f"Low confidence ({row['confidence']:.1%}). Verify or flag.",
- })
-
summary = {
"errors": sum(1 for i in issues if i.get("severity") == "error"),
"warnings": sum(1 for i in issues if i.get("severity") == "warning"),
diff --git a/src/hyperresearch/cli/note.py b/src/hyperresearch/cli/note.py
index 8e4aa40..b4f443f 100644
--- a/src/hyperresearch/cli/note.py
+++ b/src/hyperresearch/cli/note.py
@@ -24,7 +24,6 @@ def note_new(
status: str = typer.Option("draft", "--status", "-s", help="Initial status"),
summary: str | None = typer.Option(None, "--summary", help="One-line summary"),
source: str | None = typer.Option(None, "--source", help="Source URL or path"),
- confidence: float | None = typer.Option(None, "--confidence", help="Confidence 0.0-1.0"),
template: str | None = typer.Option(None, "--template", "-T", help="Template: note|concept|reference|guide|comparison|moc"),
edit: bool = typer.Option(False, "--edit", "-e", help="Open in $EDITOR"),
json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
@@ -335,8 +334,6 @@ def note_update(
set_summary: str | None = typer.Option(None, "--summary", help="Set summary"),
set_parent: str | None = typer.Option(None, "--parent", "-p", help="Set parent topic"),
set_source: str | None = typer.Option(None, "--source", help="Set source URL/path"),
- set_confidence: float | None = typer.Option(None, "--confidence", help="Set confidence 0.0-1.0"),
- set_superseded_by: str | None = typer.Option(None, "--superseded-by", help="Mark as superseded"),
deprecate: bool = typer.Option(False, "--deprecate", help="Mark as deprecated"),
json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
) -> None:
@@ -383,12 +380,6 @@ def note_update(
if set_source is not None:
meta.source = set_source
changed.append("source")
- if set_confidence is not None:
- meta.confidence = set_confidence
- changed.append(f"confidence={set_confidence}")
- if set_superseded_by is not None:
- meta.superseded_by = set_superseded_by
- changed.append(f"superseded_by={set_superseded_by}")
if deprecate:
meta.deprecated = True
meta.status = "deprecated"
diff --git a/src/hyperresearch/cli/research.py b/src/hyperresearch/cli/research.py
index 930a5df..55aff1f 100644
--- a/src/hyperresearch/cli/research.py
+++ b/src/hyperresearch/cli/research.py
@@ -41,7 +41,11 @@ def research(
vault.auto_sync()
conn = vault.db
- prov = get_provider(provider_name or vault.config.web_provider)
+ prov = get_provider(
+ provider_name or vault.config.web_provider,
+ profile=vault.config.web_profile,
+ magic=vault.config.web_magic,
+ )
# Step 1: Search
if not json_output:
@@ -55,7 +59,7 @@ def research(
output(
error(
f"Provider '{prov.name}' does not support web search. "
- "Use --provider tavily or let your agent search and use 'hyperresearch fetch' instead.",
+ "Use your agent's built-in search, then pipe URLs into 'hyperresearch fetch'.",
"NO_SEARCH",
),
json_mode=True,
@@ -63,7 +67,7 @@ def research(
else:
console.print(
f"[red]Provider '{prov.name}' cannot search.[/] "
- "Use --provider tavily, or have your agent search and 'hyperresearch fetch' each URL."
+ "Use your agent's built-in search, then pipe URLs into 'hyperresearch fetch'."
)
raise typer.Exit(1)
@@ -175,6 +179,36 @@ def research(
if not json_output:
console.print(f"\n[bold green]Synthesis:[/] [[{moc_id}]]")
+ # Step 6: Holistic auto-linking across all new notes
+ if created_notes:
+ from hyperresearch.core.linker import auto_link
+
+ note_ids = [n["note_id"] for n in created_notes]
+ link_report = auto_link(vault, note_ids)
+ if link_report:
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+ if not json_output:
+ total_links = sum(len(v) for v in link_report.values())
+ console.print(f"[green]Auto-linked:[/] {total_links} connections across {len(link_report)} notes")
+
+ # Step 7: Surface hub notes
+ hubs = []
+ if created_notes:
+ hub_rows = conn.execute(
+ "SELECT target_id, COUNT(*) as cnt FROM links "
+ "WHERE target_id IS NOT NULL GROUP BY target_id ORDER BY cnt DESC LIMIT 5"
+ ).fetchall()
+ for row in hub_rows:
+ title_row = conn.execute("SELECT title FROM notes WHERE id = ?", (row["target_id"],)).fetchone()
+ if title_row:
+ hubs.append({"id": row["target_id"], "title": title_row["title"], "inbound_links": row["cnt"]})
+ if hubs and not json_output:
+ console.print("\n[bold]Hub notes[/] (most connected):")
+ for h in hubs:
+ console.print(f" [{h['inbound_links']} links] [[{h['id']}]] {h['title']}")
+
# Output
data = {
"topic": topic,
@@ -182,6 +216,7 @@ def research(
"notes_created": created_notes,
"total_fetched": pages_fetched,
"depth": depth,
+ "hubs": hubs,
}
if json_output:
@@ -199,6 +234,10 @@ def _save_result(vault, conn, prov, result, tags, parent) -> dict | None:
url = result.url
+ # Skip login redirects
+ if result.looks_like_login_wall(url):
+ return None
+
# Skip if already fetched
existing = conn.execute("SELECT note_id FROM sources WHERE url = ?", (url,)).fetchone()
if existing:
@@ -226,7 +265,19 @@ def _save_result(vault, conn, prov, result, tags, parent) -> dict | None:
extra_frontmatter=extra_meta,
)
+ # Auto-enrich: add suggested tags and summary before sync
+ from hyperresearch.core.enrich import enrich_note_file
+
+ enrich_note_file(note_path, conn, tags)
+
+ # Sync so the note exists in the notes table (needed for FK on sources)
+ from hyperresearch.core.sync import compute_sync_plan, execute_sync
+
note_id = note_path.stem
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
conn.execute(
"""INSERT OR IGNORE INTO sources (url, note_id, domain, fetched_at, provider, content_hash)
VALUES (?, ?, ?, ?, ?, ?)""",
diff --git a/src/hyperresearch/cli/search.py b/src/hyperresearch/cli/search.py
index ea191dc..66ec6e1 100644
--- a/src/hyperresearch/cli/search.py
+++ b/src/hyperresearch/cli/search.py
@@ -27,6 +27,7 @@ def search(
no_body: bool = typer.Option(False, "--no-body", help="Disable auto body inclusion in JSON mode"),
limit: int = typer.Option(20, "--limit", "-l", help="Max results"),
offset: int = typer.Option(0, "--offset", help="Offset for pagination"),
+ max_tokens: int | None = typer.Option(None, "--max-tokens", help="Truncate results to fit token budget (1 token ~ 4 chars)"),
json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),
) -> None:
"""Full-text search across all notes."""
@@ -80,6 +81,26 @@ def search(
).fetchone()
r["body"] = row["body"] if row else ""
+ # Token budget: truncate results to fit within limit
+ if max_tokens and results:
+ budget_chars = max_tokens * 4 # ~4 chars per token
+ used = 0
+ trimmed = []
+ for r in results:
+ overhead = 200 + len(r.get("title", "")) + len(r.get("id", ""))
+ body = r.get("body", "")
+ remaining = budget_chars - used - overhead
+ if remaining <= 0:
+ break
+ if body and len(body) > remaining:
+ r["body"] = body[:remaining] + "\n... [truncated]"
+ r["truncated"] = True
+ trimmed.append(r)
+ break
+ used += overhead + len(body)
+ trimmed.append(r)
+ results = trimmed
+
if json_output:
output(
success(
diff --git a/src/hyperresearch/cli/setup.py b/src/hyperresearch/cli/setup.py
new file mode 100644
index 0000000..b5887a4
--- /dev/null
+++ b/src/hyperresearch/cli/setup.py
@@ -0,0 +1,356 @@
+"""Interactive setup TUI — first-time onboarding and settings configuration."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import typer
+from rich.console import Console
+from rich.panel import Panel
+from rich.prompt import Confirm, Prompt
+from rich.rule import Rule
+from rich.table import Table
+
+console = Console()
+
+
+def setup(
+ path: str = typer.Argument(".", help="Path to set up"),
+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output (non-interactive)"),
+) -> None:
+ """Interactive setup — configure hyperresearch step by step."""
+ if json_output or not sys.stdin.isatty():
+ import subprocess
+
+ cmd = [sys.executable, "-m", "hyperresearch", "install", path]
+ if json_output:
+ cmd.append("--json")
+ raise typer.Exit(subprocess.call(cmd))
+
+ root = Path(path).resolve()
+
+ console.print()
+ console.print(
+ Panel(
+ "[bold cyan]hyperresearch[/]\n"
+ "[dim]Agent-driven research knowledge base[/]\n\n"
+ "[dim]Your AI agents will collect, search, and synthesize\n"
+ "web research into a persistent, searchable wiki.[/]",
+ border_style="cyan",
+ padding=(1, 4),
+ )
+ )
+
+ vault_name = "Research Base"
+
+ # ── Step 1: Web Provider ──────────────────────────────────────
+ console.print()
+ console.print(Rule("[bold]Step 1[/] Web Provider", style="cyan"))
+ console.print()
+
+ has_crawl4ai = _check_crawl4ai()
+ if has_crawl4ai:
+ console.print(" [green]crawl4ai detected[/] — local headless Chromium browser")
+ console.print()
+ console.print(" crawl4ai fetches web pages using a real browser. It handles")
+ console.print(" JavaScript, bypasses bot detection, and saves full content.")
+ console.print()
+ console.print(" [dim]Without it, your agent's built-in WebFetch is used instead —[/]")
+ console.print(" [dim]which often gets blocked, returns incomplete content,[/]")
+ console.print(" [dim]and doesn't persist across sessions.[/]")
+ console.print()
+ use_crawl4ai = Confirm.ask(" Use crawl4ai as the default web provider?", default=True)
+ else:
+ console.print(" [yellow]crawl4ai not installed[/]")
+ console.print(" Your agent's built-in WebFetch will be used instead.")
+ console.print(" [dim]For headless browser support: pip install hyperresearch[crawl4ai][/]")
+ use_crawl4ai = False
+
+ provider = "crawl4ai" if use_crawl4ai else "builtin"
+
+ # ── Step 2: Browser Profile ───────────────────────────────────
+ profile = ""
+ if use_crawl4ai:
+ console.print()
+ console.print(Rule("[bold]Step 2[/] Browser Profile", style="cyan"))
+ console.print()
+ console.print(" A login profile lets hyperresearch access sites you're")
+ console.print(" logged into — LinkedIn, Twitter, paywalled news, etc.")
+ console.print()
+
+ existing_profiles = _list_profiles()
+
+ table = Table(show_header=False, box=None, padding=(0, 2, 0, 4))
+ table.add_column(style="bold cyan", width=3)
+ table.add_column()
+
+ opt_num = 1
+ use_existing_opt = None
+ if existing_profiles:
+ use_existing_opt = str(opt_num)
+ table.add_row(use_existing_opt, "Use an existing profile")
+ opt_num += 1
+ create_opt = str(opt_num)
+ table.add_row(create_opt, "Create a new profile [dim]— opens browser, ~2 min[/]")
+ opt_num += 1
+ skip_opt = str(opt_num)
+ table.add_row(skip_opt, "Skip [dim]— public pages only[/]")
+ console.print(table)
+ console.print()
+
+ valid = [create_opt, skip_opt]
+ if use_existing_opt:
+ valid.insert(0, use_existing_opt)
+ default = use_existing_opt if existing_profiles else skip_opt
+
+ choice = Prompt.ask(" Choose", choices=valid, default=default)
+
+ if choice == use_existing_opt and existing_profiles:
+ profile = _pick_existing_profile(existing_profiles)
+ elif choice == create_opt:
+ profile = _create_profile_interactive()
+ # else: skip, profile stays ""
+
+ # ── Step 3: Agent Hooks ───────────────────────────────────────
+ console.print()
+ console.print(Rule("[bold]Step 3[/] Agent Hooks", style="cyan"))
+ console.print()
+ console.print(" Hooks remind your AI agent to check the research base")
+ console.print(" before searching the web. Select your platforms:")
+ console.print()
+
+ platforms_available = [
+ ("claude", "Claude Code"),
+ ("codex", "Codex"),
+ ("cursor", "Cursor"),
+ ("gemini", "Gemini CLI"),
+ ]
+
+ table = Table(show_header=False, box=None, padding=(0, 2, 0, 4))
+ table.add_column(style="bold cyan", width=3)
+ table.add_column()
+ for i, (_key, name) in enumerate(platforms_available, 1):
+ table.add_row(str(i), name)
+ all_opt = str(len(platforms_available) + 1)
+ table.add_row(all_opt, "All of the above")
+ console.print(table)
+ console.print()
+
+ platform_input = Prompt.ask(" Select (comma-separated)", default="1")
+
+ if platform_input.strip() == all_opt:
+ platforms = ["all"]
+ else:
+ selected = []
+ for part in platform_input.split(","):
+ part = part.strip()
+ if part.isdigit() and 1 <= int(part) <= len(platforms_available):
+ selected.append(platforms_available[int(part) - 1][0])
+ platforms = selected or ["claude"]
+
+ # ── Execute ───────────────────────────────────────────────────
+ console.print()
+ console.print(Rule("[bold]Setting up", style="green"))
+ console.print()
+
+ from hyperresearch.core.agent_docs import _resolve_executable, inject_agent_docs
+ from hyperresearch.core.hooks import install_hooks
+ from hyperresearch.core.vault import Vault, VaultError
+
+ agents = ["claude"]
+ for key, filename in [("agents", "AGENTS.md"), ("gemini", "GEMINI.md")]:
+ if (root / filename).exists() or (root / filename.lower()).exists():
+ agents.append(key)
+
+ # Init vault
+ try:
+ vault = Vault.discover(root)
+ console.print(f" [dim]Vault:[/] {vault.root}")
+ except VaultError:
+ vault = Vault.init(root, name=vault_name, agents=agents)
+ console.print(f" [green]Vault created:[/] {vault.root}")
+
+ # Write config — magic always on when crawl4ai is used
+ magic = use_crawl4ai
+ vault.config.web_provider = provider
+ vault.config.web_profile = profile
+ vault.config.web_magic = magic
+ vault.config.name = vault_name
+ vault.config.save(vault.config_path)
+
+ # Inject agent docs
+ hpr_path = _resolve_executable()
+ doc_actions = inject_agent_docs(root, agents=agents)
+ for action in doc_actions:
+ console.print(f" [green]Docs:[/] {action}")
+
+ # Install hooks
+ hook_actions = install_hooks(root, platforms=platforms, hpr_path=hpr_path)
+ for action in hook_actions:
+ console.print(f" [green]Hook:[/] {action}")
+ if not hook_actions:
+ console.print(" [dim]Hooks already installed[/]")
+
+ # Install browser if needed
+ if use_crawl4ai:
+ _ensure_browser()
+
+ # ── Summary ───────────────────────────────────────────────────
+ console.print()
+ profile_desc = profile or "none (public pages only)"
+ platform_names = (
+ "all" if "all" in platforms
+ else ", ".join(name for key, name in platforms_available if key in platforms)
+ )
+
+ summary = Table(show_header=False, box=None, padding=(0, 2))
+ summary.add_column(style="dim", width=12)
+ summary.add_column()
+ summary.add_row("Provider", f"[bold]{provider}[/]")
+ summary.add_row("Profile", f"[bold]{profile_desc}[/]")
+ summary.add_row("Stealth", "[bold]on[/]" if magic else "[dim]off[/]")
+ summary.add_row("Hooks", f"[bold]{platform_names}[/]")
+ summary.add_row("CLI", f"[dim]{hpr_path}[/]")
+
+ console.print(
+ Panel(
+ summary,
+ title="[green bold]Setup complete[/]",
+ border_style="green",
+ padding=(1, 2),
+ )
+ )
+ console.print()
+ console.print(f" [dim]Start researching:[/] {hpr_path} fetch \"https://...\" --tag topic -j")
+ console.print(" [dim]Change settings:[/] hyperresearch config show")
+ console.print(" [dim]Re-run setup:[/] hyperresearch setup")
+ console.print()
+
+
+# ── Helpers ─────────────────────────────────────────────────────
+
+
+def _pick_existing_profile(profiles: list[str]) -> str:
+ """Show a numbered list of profiles and let the user pick one."""
+ console.print()
+ table = Table(show_header=False, box=None, padding=(0, 2, 0, 4))
+ table.add_column(style="bold cyan", width=3)
+ table.add_column()
+ for i, name in enumerate(profiles, 1):
+ table.add_row(str(i), name)
+ console.print(table)
+ console.print()
+
+ choices = [str(i) for i in range(1, len(profiles) + 1)]
+ choice = Prompt.ask(" Select profile", choices=choices, default="1")
+ selected = profiles[int(choice) - 1]
+ console.print(f" [green]Using profile:[/] {selected}")
+ return selected
+
+
+def _list_profiles() -> list[str]:
+ """List existing crawl4ai browser profiles."""
+ profiles_dir = Path.home() / ".crawl4ai" / "profiles"
+ if not profiles_dir.exists():
+ return []
+ return sorted(
+ d.name for d in profiles_dir.iterdir()
+ if d.is_dir() and (d / "Default").exists()
+ )
+
+
+def _create_profile_interactive() -> str:
+ """Walk the user through creating a crawl4ai browser profile."""
+ import subprocess
+
+ profile_name = Prompt.ask(" Profile name", default="research")
+
+ console.print()
+ console.print(
+ Panel(
+ "[bold]A browser window will open.[/]\n\n"
+ "Log in to the sites you want hyperresearch to access:\n\n"
+ " [cyan]linkedin.com[/] profiles, posts, company pages\n"
+ " [cyan]x.com / twitter.com[/] tweets, threads, profiles\n"
+ " [cyan]reddit.com[/] full thread content, user profiles\n"
+ " [cyan]medium.com[/] paywalled articles\n"
+ " [cyan]news sites[/] any paywalled publications you subscribe to\n"
+ " [cyan]github.com[/] private repos (if needed)\n\n"
+ "Take your time. Log into as many sites as you want.\n"
+ "[bold]When finished, press q in the terminal to save.[/]\n\n"
+ "[dim]Sessions are saved permanently. You only do this once per site.[/]",
+ title="[cyan bold]Login Profile Setup[/]",
+ border_style="cyan",
+ padding=(1, 2),
+ )
+ )
+
+ ready = Confirm.ask(" Ready to open the browser?", default=True)
+ if not ready:
+ console.print(" [dim]Skipped. Run 'hyperresearch setup' later to create a profile.[/]")
+ return ""
+
+ try:
+ result = subprocess.run(
+ [sys.executable, "-c", f"""
+import asyncio
+from crawl4ai import BrowserProfiler
+async def main():
+ profiler = BrowserProfiler()
+ path = await profiler.create_profile("{profile_name}")
+ print(f"PROFILE_PATH={{path}}")
+asyncio.run(main())
+"""],
+ capture_output=False,
+ timeout=600,
+ )
+ if result.returncode == 0:
+ console.print(f" [green]Profile '{profile_name}' saved.[/]")
+ return profile_name
+ else:
+ console.print(" [yellow]Profile creation exited. Run 'hyperresearch setup' to retry.[/]")
+ return ""
+ except subprocess.TimeoutExpired:
+ console.print(" [yellow]Timed out. Run 'hyperresearch setup' to try again.[/]")
+ return ""
+ except Exception as e:
+ console.print(f" [red]Error:[/] {e}")
+ console.print(" [dim]Run 'crwl profiles' manually to create a profile.[/]")
+ return ""
+
+
+def _check_crawl4ai() -> bool:
+ try:
+ import crawl4ai # noqa: F401
+ return True
+ except ImportError:
+ return False
+
+
+def _ensure_browser() -> None:
+ """Check if Chromium is installed, install if needed."""
+ try:
+ from playwright.sync_api import sync_playwright
+
+ pw = sync_playwright().start()
+ browser = pw.chromium.launch(headless=True)
+ browser.close()
+ pw.stop()
+ console.print(" [dim]Browser ready[/]")
+ except Exception:
+ console.print(" [yellow]Installing Chromium browser...[/]")
+ import subprocess
+
+ try:
+ subprocess.run(
+ [sys.executable, "-m", "playwright", "install", "chromium"],
+ check=True,
+ capture_output=True,
+ )
+ console.print(" [green]Chromium installed[/]")
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ console.print(
+ " [red]Could not install browser automatically.[/]\n"
+ " Run: playwright install chromium"
+ )
diff --git a/src/hyperresearch/core/agent_docs.py b/src/hyperresearch/core/agent_docs.py
index f582f18..b07d96d 100644
--- a/src/hyperresearch/core/agent_docs.py
+++ b/src/hyperresearch/core/agent_docs.py
@@ -18,59 +18,199 @@ HYPERRESEARCH_BLURB = """\
{marker}
## Research Base (hyperresearch)
+**CLI path: `{hpr}`** — use this exact path for all hyperresearch commands below. It may not be on your system PATH.
+
This project uses hyperresearch as an agent-driven research knowledge base. The `research/` directory contains markdown notes collected from web sources and original research. Append `--json` to any command for structured output.
-### Search and read
+### MANDATORY: How to do research
+
+When the user asks you to research a topic, **you MUST follow this workflow**. Do NOT use WebFetch for source pages — use `{hpr} fetch` instead. It runs a real headless browser, handles JavaScript, bypasses bot detection, saves full content with screenshots and images, and indexes everything for future sessions.
+
+**This is a deep research tool.** Your job is to go down rabbit holes, cast a wide net, and collect as much raw source material as possible. **Over-collect, then prune.** It is always better to have too many sources than too few — you can deprecate notes later, but you can't un-skip a source you never fetched.
+**Step 1: Check what's already known**
```bash
-hyperresearch search "query" --json # Full-text search
-hyperresearch search "query" --tag ml --json # Filter by tag, status, date, parent
-hyperresearch search "query" --include-body --json # Include full note bodies in results
-hyperresearch note show <id> --json # Read a note
-hyperresearch note show <id1> <id2> <id3> --json # Read multiple notes at once
-hyperresearch note list --json # List all notes with summaries
+{hpr} search "topic" --include-body -j
+{hpr} sources list -j
```
-### Collect research
+**Step 2: Search broadly** — Use WebSearch with multiple queries. Don't stop at one search. Try different phrasings, related terms, and specific sub-topics. Cast a wide net.
-When you find useful information via web search or browsing, save it as a note:
+**Step 3: Fetch EVERYTHING relevant** — A `hyperresearch-fetcher` subagent is installed in `.claude/agents/`. It uses a **cheap, fast model (Haiku)** to do the actual URL fetching. **Delegate all fetching to it** — do NOT fetch URLs yourself or use WebFetch.
+For each URL or batch of URLs, spawn the fetcher agent:
+```
+Use the hyperresearch-fetcher agent to fetch these URLs with tag "<topic>":
+- https://example.com/article1
+- https://example.com/article2
+```
+
+**Spawn multiple fetcher agents in parallel** — one per URL or small batch. They run on Haiku, so this is fast and cheap. Err on the side of fetching too many pages.
+
+If the `hyperresearch-fetcher` agent is not available (other platforms), fall back to running the command directly:
```bash
-hyperresearch note new "Title" --tag t1 --body-file /tmp/content.md --source "https://..." --summary "One-liner" --json
-hyperresearch note update <id> --status evergreen --add-tag ml --summary "Updated" --json
+{hpr} fetch "<url>" --tag <topic> -j
```
-**Always check the research base BEFORE searching the web** — the answer may already be here.
+**Step 4: Go down rabbit holes** — After fetching, read the notes:
+```bash
+{hpr} note show <note-id> -j
+```
+Look for links in the content that point to **primary sources, references, related papers, deeper material, or tangentially related topics**. Fetch those too. Then read THOSE notes and follow THEIR links.
+
+**Keep going aggressively:**
+- A blog post about a paper? Fetch the paper.
+- A news article about a tool? Fetch the docs AND the GitHub repo.
+- A paper cites 3 key references? Fetch all 3.
+- A profile mentions a company? Fetch the company page.
+- Found a related topic that might be relevant? Fetch it. You can always deprecate it later.
+
+**The goal is exhaustive collection.** You are building a knowledge base that future agents will rely on. Missing a source is worse than having one extra note. Prune later during curation.
+
+**Step 5: Synthesize** — Once you have the raw sources indexed, search and read them to build your synthesis:
+```bash
+{hpr} search "topic" --include-body -j
+```
+
+**Step 6: Prune** — After synthesis, deprecate notes that turned out to be irrelevant:
+```bash
+{hpr} note update <id> --status deprecated -j
+```
+This keeps the KB clean without losing anything permanently.
+
+### Why {hpr} fetch, not WebFetch
+
+`{hpr} fetch` runs a real headless Chromium browser — it bypasses bot detection, saves full content with formatting, persists across sessions, and tracks URLs to prevent re-fetching. **Use WebFetch only for quick one-off lookups you don't need to save.**
+
+### Raw content is king
+
+**Save raw source material with original formatting** — not rewritten summaries. Future agents need the full context to draw their own conclusions. Preserve headings, tables, code blocks, and technical details. Follow links to primary sources (the paper, not the blog post about the paper). Connect related notes with `[[note-id]]` wiki-links.
+
+For manually written notes:
+```bash
+{hpr} note new "Title" --tag t1 --body-file /tmp/content.md --source "https://..." --summary "One-liner" --json
+```
+
+### Searching the research base
+
+```bash
+{hpr} search "query" --json # Full-text search
+{hpr} search "query" --tag ml --json # Filter by tag, status, date, parent
+{hpr} search "query" --include-body --json # Include full note bodies in results
+{hpr} note show <id> --json # Read a note
+{hpr} note show <id1> <id2> <id3> --json # Read multiple notes at once
+{hpr} note list --json # List all notes with summaries
+```
+
+### Images, screenshots, and assets
+
+Use `--save-assets` / `-a` when you need to capture visual content from a page:
+
+```bash
+{hpr} fetch "<url>" --tag <topic> --save-assets -j # Saves screenshot + top images
+```
-### Knowledge graph and maintenance
+This saves a screenshot of the rendered page and downloads the top content images (skipping icons, logos, ads). Only use this flag when visual content matters — diagrams, charts, figures, architecture images. For text-only pages, skip it.
```bash
-hyperresearch graph backlinks <id> --json # What links TO this note
-hyperresearch graph hubs --json # Most linked-to notes
-hyperresearch graph broken --json # Broken [[links]]
-hyperresearch lint --json # Health check
-hyperresearch repair --json # Full rebuild + fix broken links + promote notes
-hyperresearch status --json # Vault overview
+{hpr} assets list --json # List all downloaded assets
+{hpr} assets list --note <note-id> --json # Assets for a specific note
+{hpr} assets path <note-id> --type screenshot -j # Get screenshot path (viewable with Read)
+{hpr} assets path <note-id> --type image -j # Get image paths
```
-### Note quality requirements
+**To view an image or screenshot**, use the path from `{hpr} assets path` with your Read tool — it supports PNG, JPG, and other image formats directly.
-Every note MUST have:
-- At least one tag (`--tag`). REUSE existing tags from `hyperresearch tags -j` -- do not invent new ones unless necessary.
-- A summary (`--summary`). One sentence, under 120 characters.
-- A body with meaningful content (50+ words).
-- A source URL (`--source`) when the content comes from the web.
-- Use `--body-file` instead of `--body` to avoid shell escaping issues.
+### Authenticated crawling (social media, paywalled sites, etc.)
-Run `hyperresearch lint -j` to check quality, `hyperresearch repair -j` to auto-fix.
+To access login-gated content (LinkedIn, Twitter, paywalled news), the user must create a login profile.
+This is done once via `crwl profiles` or during `hyperresearch setup`.
+
+```toml
+# .hyperresearch/config.toml
+[web]
+provider = "crawl4ai"
+profile = "research" # Name of the login profile
+magic = true
+```
+
+**If no profile is configured**, crawl4ai still works for public pages. If a fetch returns a login wall or "sign in to view" content, tell the user they need to set up a login profile:
+
+```
+To access login-gated sites, run: hyperresearch setup
+Choose option 1 to create a login profile — a browser opens, you log into your sites, done.
+```
+
+**If fetches fail with browser crash / "failed to launch":**
+The profile may be corrupted or the browser binary missing. Tell the user to run `crwl profiles`
+to recreate the profile, or `playwright install chromium` to reinstall the browser.
+
+### MANDATORY: Curate after every research session
+
+The research base is a **long-lived knowledge investment**, not a scratchpad. Every future agent session benefits from well-organized notes. **After fetching sources, you MUST do a curation pass.**
+
+**Step 1: Tag and summarize every new note**
+Fetched notes arrive as drafts with no summary. Fix each one:
+```bash
+{hpr} note list --status draft -j # Find unprocessed notes
+{hpr} note update <id> --summary "One-line summary" -j # Add summary
+{hpr} note update <id> --add-tag <topic> -j # Add tags
+```
+- REUSE existing tags: `{hpr} tags -j` — do not invent new ones unless truly novel
+- Every note MUST have: at least one tag, a summary (under 120 chars), a source URL
+- Summaries should be specific and searchable, not generic ("Overview of X" is useless; "X achieves Y by doing Z" is useful)
+
+**Step 2: Connect related notes with wiki-links**
+Read through new notes and add `[[other-note-id]]` links to connect related material:
+```bash
+{hpr} search "related topic" -j # Find related notes
+{hpr} note show <id> -j # Read a note
+```
+Then edit the markdown file directly to add links like `See also: [[other-note-id]]` at the bottom. This builds the knowledge graph.
+
+**Step 3: Promote quality notes**
+Move notes through the lifecycle based on their value:
+```bash
+{hpr} note update <id> --status review -j # Needs review but has good content
+{hpr} note update <id> --status evergreen -j # High-quality, lasting reference
+```
+- `draft` — just fetched, unprocessed
+- `review` — has tags/summary, content looks good, needs human review
+- `evergreen` — verified, high-quality, lasting value
+- `stale` → `deprecated` → `archive` — for outdated material
+
+**Step 4: Run health checks**
+```bash
+{hpr} lint -j # Find notes missing tags, summaries, or with broken links
+{hpr} repair -j # Auto-fix broken links, rebuild indexes, promote eligible notes
+{hpr} status -j # Overall vault health
+```
+
+**Step 5: Check the knowledge graph**
+```bash
+{hpr} graph hubs -j # Most linked-to notes (key topics)
+{hpr} graph backlinks <id> -j # What links TO this note
+{hpr} graph broken -j # Broken [[links]] to fix
+```
+
+### This is an investment, not a dump
+
+The research base compounds across sessions. A well-curated note that three future agents can find and use is worth 10x a raw dump nobody can navigate. When doing research:
+
+- **Tag consistently** — use the existing tag vocabulary, not ad-hoc variations
+- **Write real summaries** — "Mamba achieves linear-time sequence modeling via selective state spaces" not "Paper about Mamba"
+- **Link aggressively** — every note should link to related notes via `[[note-id]]`
+- **Promote good notes** — move quality content from `draft` to `review` to `evergreen`
+- **Deprecate stale content** — if a note is outdated, mark it `deprecated` rather than leaving it to mislead future agents
+- **Build MOC (map of content) notes** — for major topics, create a synthesis note that links to all related sources with `type: moc`
### Key conventions
- Notes live in `research/notes/` as markdown with YAML frontmatter
- Link between notes with `[[note-id]]` syntax
-- After editing .md files directly, run `hyperresearch sync` to update the index
+- After editing .md files directly, run `{hpr} sync` to update the index
- Statuses: draft -> review -> evergreen -> stale -> deprecated -> archive
-- Run `hyperresearch --help` for the full command list
+- Run `{hpr} --help` for the full command list
{end_marker}
"""
@@ -83,6 +223,32 @@ AGENT_FILES = {
}
+def _resolve_executable() -> str:
+ """Find the absolute path to the hyperresearch executable."""
+ import shutil
+ import sys
+
+ # Check if it's on PATH already
+ which = shutil.which("hyperresearch")
+ if which:
+ return which
+
+ # Find it relative to the current Python interpreter (works for venv installs)
+ python_dir = Path(sys.executable).parent
+ for name in ("hyperresearch", "hyperresearch.exe"):
+ candidate = python_dir / name
+ if candidate.exists():
+ return str(candidate)
+ # Also check Scripts/ subdirectory (Windows venv layout)
+ for name in ("hyperresearch", "hyperresearch.exe"):
+ candidate = python_dir / "Scripts" / name
+ if candidate.exists():
+ return str(candidate)
+
+ # Fallback — bare name, hope it's on PATH
+ return "hyperresearch"
+
+
def inject_agent_docs(
vault_root: Path,
agents: list[str] | None = None,
@@ -98,7 +264,14 @@ def inject_agent_docs(
if agents is None:
agents = ["claude"]
- blurb = HYPERRESEARCH_BLURB.format(marker=HYPERRESEARCH_SECTION_MARKER, end_marker=HYPERRESEARCH_SECTION_END)
+ hpr_path = _resolve_executable()
+ # Use forward slashes — bash on Windows eats backslashes
+ hpr_path = hpr_path.replace("\\", "/")
+ blurb = HYPERRESEARCH_BLURB.format(
+ marker=HYPERRESEARCH_SECTION_MARKER,
+ end_marker=HYPERRESEARCH_SECTION_END,
+ hpr=hpr_path,
+ )
modified = []
# Determine which files to handle
@@ -142,7 +315,7 @@ def _inject_into_file(filepath: Path, blurb: str, filename: str) -> str | None:
re.escape(HYPERRESEARCH_SECTION_MARKER) + r".*?" + re.escape(HYPERRESEARCH_SECTION_END),
re.DOTALL,
)
- new_content = pattern.sub(blurb.strip(), content)
+ new_content = pattern.sub(lambda _: blurb.strip(), content)
if new_content != content:
filepath.write_text(new_content, encoding="utf-8")
return f"{filename} (updated)"
diff --git a/src/hyperresearch/core/config.py b/src/hyperresearch/core/config.py
index 8d530f1..1ac73f2 100644
--- a/src/hyperresearch/core/config.py
+++ b/src/hyperresearch/core/config.py
@@ -33,6 +33,8 @@ class VaultConfig:
# Web provider
web_provider: str = "builtin"
+ web_profile: str = "" # crawl4ai browser profile name (created via `crwl profiles`)
+ web_magic: bool = False # crawl4ai magic mode (anti-bot stealth)
# Index
auto_build_index: bool = True
@@ -65,6 +67,8 @@ class VaultConfig:
search_penalize_deprecated=search.get("penalize_deprecated", cls.search_penalize_deprecated),
search_penalize_stale=search.get("penalize_stale", cls.search_penalize_stale),
web_provider=web.get("provider", cls.web_provider),
+ web_profile=web.get("profile", cls.web_profile),
+ web_magic=web.get("magic", cls.web_magic),
auto_sync=sync.get("auto_sync", cls.auto_sync),
exclude_patterns=sync.get("exclude_patterns", cls().exclude_patterns),
auto_build_index=index.get("auto_build", cls.auto_build_index),
@@ -94,6 +98,8 @@ class VaultConfig:
"",
"[web]",
f'provider = "{self.web_provider}"',
+ f'profile = "{self.web_profile}"',
+ f"magic = {'true' if self.web_magic else 'false'}",
"",
"[sync]",
f"auto_sync = {'true' if self.auto_sync else 'false'}",
diff --git a/src/hyperresearch/core/db.py b/src/hyperresearch/core/db.py
index ff4c0a9..e387a29 100644
--- a/src/hyperresearch/core/db.py
+++ b/src/hyperresearch/core/db.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import sqlite3
from pathlib import Path
-SCHEMA_VERSION = 3
+SCHEMA_VERSION = 5
SCHEMA_SQL = """
PRAGMA journal_mode=WAL;
@@ -26,14 +26,9 @@ CREATE TABLE IF NOT EXISTS notes (
CHECK (type IN ('note','raw','index','moc')),
source TEXT,
parent TEXT,
- confidence REAL,
- superseded_by TEXT,
deprecated INTEGER NOT NULL DEFAULT 0,
reviewed TEXT,
expires TEXT,
- llm_compiled INTEGER NOT NULL DEFAULT 0,
- llm_model TEXT,
- compile_source TEXT,
word_count INTEGER NOT NULL DEFAULT 0,
summary TEXT,
created TEXT NOT NULL,
@@ -113,6 +108,21 @@ CREATE TABLE IF NOT EXISTS sources (
CREATE INDEX IF NOT EXISTS idx_sources_domain ON sources(domain);
CREATE INDEX IF NOT EXISTS idx_sources_note ON sources(note_id);
+CREATE TABLE IF NOT EXISTS assets (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
+ type TEXT NOT NULL CHECK (type IN ('image', 'screenshot', 'pdf', 'other')),
+ filename TEXT NOT NULL,
+ url TEXT,
+ alt_text TEXT,
+ content_type TEXT,
+ size_bytes INTEGER,
+ created_at TEXT NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_assets_note ON assets(note_id);
+CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type);
+
"""
FTS_SQL = """
diff --git a/src/hyperresearch/core/enrich.py b/src/hyperresearch/core/enrich.py
index 87ba706..3bafa68 100644
--- a/src/hyperresearch/core/enrich.py
+++ b/src/hyperresearch/core/enrich.py
@@ -1,8 +1,10 @@
-"""Auto-enrichment: keyword-based tagging and first-line summary extraction."""
+"""Auto-enrichment: keyword-based tagging, summary extraction, and note enrichment."""
from __future__ import annotations
import re
+import sqlite3
+from pathlib import Path
def auto_tag(body_plain: str, existing_tags: list[dict]) -> list[str]:
@@ -68,3 +70,41 @@ def auto_summary(body: str) -> str | None:
return clean[:117] + "..."
return clean
return None
+
+
+def enrich_note_file(note_path: Path, conn: sqlite3.Connection, user_tags: list[str]) -> bool:
+ """Auto-enrich a note file with tags and summary. Rewrites frontmatter in place.
+
+ Called after write_note() but before sync. Returns True if the file was modified.
+ """
+ from hyperresearch.core.frontmatter import parse_frontmatter, serialize_frontmatter
+
+ content = note_path.read_text(encoding="utf-8-sig")
+ meta, body = parse_frontmatter(content)
+
+ changed = False
+
+ # Auto-tag: merge user tags with auto-suggested tags (cap at 8 total)
+ tag_vocab = [
+ {"tag": row["tag"], "count": row["c"]}
+ for row in conn.execute("SELECT tag, COUNT(*) as c FROM tags GROUP BY tag ORDER BY c DESC")
+ ]
+ body_plain = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", body) # strip markdown links
+ body_plain = re.sub(r"[*_`#]", "", body_plain)
+ suggested = auto_tag(body_plain, tag_vocab)
+ merged = list(dict.fromkeys(user_tags + suggested))[:8]
+ if set(merged) != set(meta.tags):
+ meta.tags = merged
+ changed = True
+
+ # Auto-summary: only if not already set
+ if not meta.summary:
+ summary = auto_summary(body)
+ if summary:
+ meta.summary = summary
+ changed = True
+
+ if changed:
+ note_path.write_text(serialize_frontmatter(meta) + "\n" + body, encoding="utf-8")
+
+ return changed
diff --git a/src/hyperresearch/core/fetcher.py b/src/hyperresearch/core/fetcher.py
new file mode 100644
index 0000000..4b7994a
--- /dev/null
+++ b/src/hyperresearch/core/fetcher.py
@@ -0,0 +1,127 @@
+"""Core fetch logic — reusable by CLI and MCP server."""
+
+from __future__ import annotations
+
+import hashlib
+from urllib.parse import urlparse
+
+
+def fetch_and_save(
+ vault,
+ url: str,
+ tags: list[str] | None = None,
+ title: str | None = None,
+ parent: str | None = None,
+ provider_name: str | None = None,
+ save_assets: bool = False,
+ visible: bool = False,
+) -> dict:
+ """Fetch a URL and save as a research note. Returns result dict.
+
+ Raises:
+ ValueError: If URL is already fetched.
+ RuntimeError: If fetch fails.
+ """
+ from hyperresearch.core.enrich import enrich_note_file
+ from hyperresearch.core.note import write_note
+ from hyperresearch.core.sync import compute_sync_plan, execute_sync
+ from hyperresearch.web.base import get_provider
+
+ tags = tags or []
+ conn = vault.db
+
+ # Check if URL already fetched
+ existing = conn.execute("SELECT note_id FROM sources WHERE url = ?", (url,)).fetchone()
+ if existing:
+ raise ValueError(f"URL already fetched as note '{existing['note_id']}'")
+
+ # Auto-visible for sites that kill headless sessions on first contact
+ if not visible and vault.config.web_profile:
+ from urllib.parse import urlparse as _urlparse
+
+ domain = _urlparse(url).netloc.lower()
+ _auth_aggressive = (
+ "linkedin.com", "twitter.com", "x.com", "facebook.com",
+ "instagram.com", "tiktok.com",
+ )
+ if any(d in domain for d in _auth_aggressive):
+ visible = True
+
+ # Fetch content
+ prov = get_provider(
+ provider_name or vault.config.web_provider,
+ profile=vault.config.web_profile,
+ magic=vault.config.web_magic,
+ headless=not visible,
+ )
+
+ result = prov.fetch(url)
+
+ # Detect login redirects — abort instead of saving junk
+ if result.looks_like_login_wall(url):
+ raise RuntimeError(
+ f"Redirected to login page ({result.title}). "
+ "Your browser profile session may have expired. "
+ "Run 'hyperresearch setup' and create a new login profile."
+ )
+
+ # Write note
+ note_title = title or result.title or urlparse(url).path.split("/")[-1] or "Untitled"
+ domain = result.domain
+
+ extra_meta = {
+ "source": url,
+ "source_domain": domain,
+ "fetched_at": result.fetched_at.isoformat(),
+ "fetch_provider": prov.name,
+ }
+ if result.metadata.get("author"):
+ extra_meta["author"] = result.metadata["author"]
+
+ note_path = write_note(
+ vault.notes_dir,
+ title=note_title,
+ body=result.content,
+ tags=tags,
+ status="draft",
+ source=url,
+ parent=parent,
+ extra_frontmatter=extra_meta,
+ )
+
+ # Auto-enrich
+ enrich_note_file(note_path, conn, tags)
+
+ # Sync
+ note_id = note_path.stem
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
+ # Record source
+ content_hash = hashlib.sha256(result.content.encode("utf-8")).hexdigest()[:16]
+ conn.execute(
+ """INSERT INTO sources (url, note_id, domain, fetched_at, provider, content_hash)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (url, note_id, domain, result.fetched_at.isoformat(), prov.name, content_hash),
+ )
+ conn.commit()
+
+ # Save assets if requested
+ saved_assets: list[dict] = []
+ if save_assets:
+ from hyperresearch.cli.fetch import _save_assets
+
+ assets_dir = vault.root / "research" / "assets" / note_id
+ saved_assets = _save_assets(conn, result, note_id, assets_dir)
+
+ return {
+ "note_id": note_id,
+ "title": note_title,
+ "url": url,
+ "domain": domain,
+ "provider": prov.name,
+ "path": str(note_path.relative_to(vault.root)),
+ "word_count": len(result.content.split()),
+ "assets": saved_assets,
+ }
diff --git a/src/hyperresearch/core/hooks.py b/src/hyperresearch/core/hooks.py
index b6a8016..240de2c 100644
--- a/src/hyperresearch/core/hooks.py
+++ b/src/hyperresearch/core/hooks.py
@@ -1,6 +1,7 @@
"""Agent hook installer — injects PreToolUse hooks for Claude Code, Codex, Cursor, Gemini CLI.
These hooks remind agents to check the research base before doing raw web searches.
+Also installs a research subagent that uses a cheap model for URL fetching.
"""
from __future__ import annotations
@@ -8,8 +9,72 @@ from __future__ import annotations
import json
from pathlib import Path
+# Subagent definition for Claude Code — uses haiku for cheap URL fetching
+RESEARCHER_AGENT = """\
+---
+name: hyperresearch-fetcher
+description: >
+ Use this agent to fetch web URLs into the research base. Delegate to this agent
+ whenever you need to fetch one or more URLs with hyperresearch. It runs on a cheap,
+ fast model — spawn multiple in parallel for bulk research. Do NOT do URL fetching
+ yourself when this agent is available.
+model: haiku
+tools: Bash, Read
+color: blue
+---
+
+You are a research fetcher. Your job is to fetch URLs and save them to the
+hyperresearch knowledge base using the CLI.
+
+## Error handling
+
+If you get AUTH_REQUIRED or "Redirected to login page":
+- The browser profile session has expired.
+- Tell the parent agent: "Auth expired for this site. User needs to run
+ 'hyperresearch setup' and re-create their login profile."
+- Do NOT retry — the session is dead.
+
+Note: LinkedIn, Twitter, Facebook, Instagram, and TikTok automatically use a
+visible browser window to avoid session kills. No --visible flag needed.
+
+If you get a browser crash or "failed to launch" error:
+- Tell the parent agent the exact error message.
+- Do NOT retry — it will fail the same way.
+
+## Commands
+
+On Windows, ALWAYS prefix commands with `PYTHONIOENCODING=utf-8`:
+
+```bash
+PYTHONIOENCODING=utf-8 {hpr_path} fetch "<url>" --tag <topic> -j
+```
+
+For each URL you are given:
+
+1. Check if it's already fetched:
+ PYTHONIOENCODING=utf-8 {hpr_path} sources check "<url>" -j
+
+2. If not already fetched, fetch it:
+ PYTHONIOENCODING=utf-8 {hpr_path} fetch "<url>" --tag <topic> -j
+
+3. After fetching, read the note and look for links worth following:
+ PYTHONIOENCODING=utf-8 {hpr_path} note show <note-id> -j
+
+4. Report back: the note ID, title, word count, AND a list of links found
+ in the content that look like they lead to primary sources, references,
+ related material, or deeper content. Be aggressive — list anything that
+ might be worth fetching. The parent agent will decide what to pursue.
+
+If the first fetch fails with a browser error, stop and report the error.
+Do not attempt remaining URLs.
+
+If given multiple URLs and fetching works, process them sequentially. Report results for each.
+
+Keep your responses short — just the facts. The parent agent will synthesize.
+"""
+
# The hook script that gets installed
-HOOK_SCRIPT = """\
+HOOK_SCRIPT_TEMPLATE = """\
#!/usr/bin/env node
/**
* hyperresearch PreToolUse hook — reminds agent to check research base first.
@@ -18,28 +83,37 @@ HOOK_SCRIPT = """\
const fs = require('fs');
const path = require('path');
+const HPR = '{hpr_path}';
+
// Check if a .hyperresearch directory exists (vault is initialized)
-function findVault() {
+function findVault() {{
let dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
- while (true) {
+ while (true) {{
if (fs.existsSync(path.join(dir, '.hyperresearch'))) return dir;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
- }
-}
+ }}
+}}
const vault = findVault();
-if (vault) {
+if (vault) {{
const msg = [
'HYPERRESEARCH: A research knowledge base exists in this project.',
- 'Before searching the web, check existing research:',
- ' hyperresearch search "<your query>" -j',
- 'Save useful findings back:',
- ' hyperresearch note new "Title" --tag t --body-file /tmp/content.md --source "url" -j',
+ '',
+ 'BEFORE searching the web, check existing research:',
+ ' ' + HPR + ' search "<your query>" -j',
+ '',
+ 'DO NOT use WebFetch for source pages. Use hyperresearch fetch instead:',
+ ' ' + HPR + ' fetch "<url>" --tag <topic> -j',
+ 'It runs a real headless browser, saves full content + screenshot, and indexes for future sessions.',
+ '',
+ 'After fetching, READ the content and FOLLOW LINKS to primary sources. Keep fetching until you have the real sources, not just summaries.',
+ '',
+ 'For multiple URLs, use subagents to fetch in parallel.',
].join('\\n');
process.stderr.write(msg + '\\n');
-}
+}}
"""
# Cursor rule file content
@@ -51,17 +125,21 @@ alwaysApply: true
# Research Base (hyperresearch)
-This project has a hyperresearch research base. Before searching the web or browsing URLs:
+This project has a hyperresearch research base.
-1. **Check existing research first**: `hyperresearch search "<query>" -j`
-2. **Save useful findings**: `hyperresearch note new "Title" --tag t --body-file /tmp/content.md --source "url" -j`
-3. **Browse the knowledge graph**: `hyperresearch graph hubs -j` for key topics
+**When researching, ALWAYS follow this workflow:**
-The research base persists across sessions. Don't duplicate work — check before fetching.
+1. **Check existing research**: `hyperresearch search "<query>" -j`
+2. **Fetch source pages** using a cheap subagent or lower-tier model — do NOT use your main context for fetching. Use `hyperresearch fetch "<url>" --tag <topic> -j`
+3. **Read fetched content and follow links** to primary sources — fetch the paper, not the blog post about it
+4. **Keep going** until you have the real sources, not summaries
+5. **Delegate fetching to cheaper/faster models** when your platform supports subagents
+
+The research base persists across sessions. Raw source material with formatting > rewritten summaries.
"""
-def install_hooks(vault_root: Path, platforms: list[str] | None = None) -> list[str]:
+def install_hooks(vault_root: Path, platforms: list[str] | None = None, hpr_path: str = "hyperresearch") -> list[str]:
"""Install agent hooks for specified platforms. Returns list of actions taken."""
if platforms is None:
platforms = ["claude"]
@@ -69,12 +147,18 @@ def install_hooks(vault_root: Path, platforms: list[str] | None = None) -> list[
actions = []
if "claude" in platforms or "all" in platforms:
- result = _install_claude_hook(vault_root)
+ result = _install_claude_hook(vault_root, hpr_path)
+ if result:
+ actions.append(result)
+ result = _install_research_skill(vault_root)
+ if result:
+ actions.append(result)
+ result = _install_researcher_agent(vault_root, hpr_path)
if result:
actions.append(result)
if "codex" in platforms or "all" in platforms:
- result = _install_codex_hook(vault_root)
+ result = _install_codex_hook(vault_root, hpr_path)
if result:
actions.append(result)
@@ -84,25 +168,27 @@ def install_hooks(vault_root: Path, platforms: list[str] | None = None) -> list[
actions.append(result)
if "gemini" in platforms or "all" in platforms:
- result = _install_gemini_hook(vault_root)
+ result = _install_gemini_hook(vault_root, hpr_path)
if result:
actions.append(result)
return actions
-def _write_hook_script(vault_root: Path) -> Path:
+def _write_hook_script(vault_root: Path, hpr_path: str) -> Path:
"""Write the hook JS script to .hyperresearch/hook.js."""
hook_dir = vault_root / ".hyperresearch"
hook_dir.mkdir(parents=True, exist_ok=True)
hook_path = hook_dir / "hook.js"
- hook_path.write_text(HOOK_SCRIPT, encoding="utf-8")
+ # Escape backslashes for JS string literal
+ js_path = hpr_path.replace("\\", "\\\\")
+ hook_path.write_text(HOOK_SCRIPT_TEMPLATE.format(hpr_path=js_path), encoding="utf-8")
return hook_path
-def _install_claude_hook(vault_root: Path) -> str | None:
+def _install_claude_hook(vault_root: Path, hpr_path: str) -> str | None:
"""Install PreToolUse hook into .claude/settings.json."""
- hook_path = _write_hook_script(vault_root)
+ hook_path = _write_hook_script(vault_root, hpr_path)
settings_dir = vault_root / ".claude"
settings_dir.mkdir(exist_ok=True)
@@ -138,9 +224,9 @@ def _install_claude_hook(vault_root: Path) -> str | None:
return "Claude Code: .claude/settings.json (PreToolUse hook)"
-def _install_codex_hook(vault_root: Path) -> str | None:
+def _install_codex_hook(vault_root: Path, hpr_path: str) -> str | None:
"""Install hook into .codex/hooks.json."""
- hook_path = _write_hook_script(vault_root)
+ hook_path = _write_hook_script(vault_root, hpr_path)
codex_dir = vault_root / ".codex"
codex_dir.mkdir(exist_ok=True)
@@ -185,9 +271,9 @@ def _install_cursor_rule(vault_root: Path) -> str | None:
return "Cursor: .cursor/rules/hyperresearch.mdc (alwaysApply rule)"
-def _install_gemini_hook(vault_root: Path) -> str | None:
+def _install_gemini_hook(vault_root: Path, hpr_path: str) -> str | None:
"""Install BeforeTool hook into .gemini/settings.json."""
- hook_path = _write_hook_script(vault_root)
+ hook_path = _write_hook_script(vault_root, hpr_path)
gemini_dir = vault_root / ".gemini"
gemini_dir.mkdir(exist_ok=True)
@@ -218,3 +304,55 @@ def _install_gemini_hook(vault_root: Path) -> str | None:
settings_path.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
return "Gemini CLI: .gemini/settings.json (BeforeTool hook)"
+
+
+def _install_researcher_agent(vault_root: Path, hpr_path: str) -> str | None:
+ """Install the hyperresearch-fetcher subagent for Claude Code."""
+ agents_dir = vault_root / ".claude" / "agents"
+ agents_dir.mkdir(parents=True, exist_ok=True)
+ agent_path = agents_dir / "hyperresearch-fetcher.md"
+
+ # Use forward slashes for bash compatibility on Windows
+ hpr_posix = hpr_path.replace("\\", "/")
+ content = RESEARCHER_AGENT.format(hpr_path=hpr_posix)
+
+ # Always overwrite to keep in sync with latest version
+ if agent_path.exists():
+ existing = agent_path.read_text(encoding="utf-8")
+ if existing == content:
+ return None
+
+ agent_path.write_text(content, encoding="utf-8")
+ return "Claude Code: .claude/agents/hyperresearch-fetcher.md (haiku research agent)"
+
+
+def _install_research_skill(vault_root: Path) -> str | None:
+ """Install the /research skill for Claude Code."""
+ import importlib.resources
+
+ # Read the skill file from the package
+ try:
+ skill_content = (
+ importlib.resources.files("hyperresearch.skills")
+ .joinpath("research.md")
+ .read_text(encoding="utf-8")
+ )
+ except Exception:
+ # Fallback: read from source tree relative to this file
+ skill_src = Path(__file__).parent.parent / "skills" / "research.md"
+ if not skill_src.exists():
+ return None
+ skill_content = skill_src.read_text(encoding="utf-8")
+
+ # Install to project .claude/skills/
+ skill_dir = vault_root / ".claude" / "skills" / "hyperresearch"
+ skill_dir.mkdir(parents=True, exist_ok=True)
+ skill_path = skill_dir / "SKILL.md"
+
+ if skill_path.exists():
+ existing = skill_path.read_text(encoding="utf-8")
+ if existing == skill_content:
+ return None
+
+ skill_path.write_text(skill_content, encoding="utf-8")
+ return "Claude Code: .claude/skills/hyperresearch/SKILL.md (/research skill)"
diff --git a/src/hyperresearch/core/linker.py b/src/hyperresearch/core/linker.py
new file mode 100644
index 0000000..84d1f66
--- /dev/null
+++ b/src/hyperresearch/core/linker.py
@@ -0,0 +1,138 @@
+"""Auto-linker: discover and insert wiki-links between related notes."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+# Minimum title length to consider for auto-linking (avoids false positives on short generic titles)
+MIN_TITLE_LEN = 15
+
+
+def auto_link(vault, note_ids: list[str] | None = None) -> dict:
+ """Scan notes for mentions of other notes' titles and add wiki-links.
+
+ Args:
+ vault: The Vault instance.
+ note_ids: If given, only process these notes. Otherwise process all.
+
+ Returns:
+ Dict mapping note_id -> list of note_ids that were linked to.
+ """
+ conn = vault.db
+
+ # Build reference vocabulary: {lowercase_title: note_id, lowercase_alias: note_id}
+ ref_vocab: dict[str, str] = {}
+ for row in conn.execute("SELECT id, title FROM notes WHERE type != 'index'"):
+ title = row["title"]
+ nid = row["id"]
+ if len(title) >= MIN_TITLE_LEN:
+ ref_vocab[title.lower()] = nid
+ # Always include note IDs as matchable references
+ ref_vocab[nid.lower()] = nid
+
+ for row in conn.execute("SELECT note_id, alias FROM aliases"):
+ alias = row["alias"]
+ if len(alias) >= MIN_TITLE_LEN:
+ ref_vocab[alias.lower()] = row["note_id"]
+
+ if not ref_vocab:
+ return {}
+
+ # Determine which notes to process
+ if note_ids:
+ placeholders = ",".join("?" for _ in note_ids)
+ rows = conn.execute(
+ f"SELECT id, path FROM notes WHERE id IN ({placeholders})", note_ids
+ ).fetchall()
+ else:
+ rows = conn.execute("SELECT id, path FROM notes WHERE type != 'index'").fetchall()
+
+ # Process each note
+ report: dict[str, list[str]] = {}
+ for row in rows:
+ nid = row["id"]
+ note_path = vault.root / row["path"]
+ if not note_path.exists():
+ continue
+
+ linked = _link_note(note_path, nid, ref_vocab)
+ if linked:
+ report[nid] = linked
+
+ return report
+
+
+def _link_note(note_path: Path, note_id: str, ref_vocab: dict[str, str]) -> list[str]:
+ """Scan a single note for mentions of other notes and append a Related section.
+
+ Returns list of note IDs that were linked.
+ """
+ content = note_path.read_text(encoding="utf-8-sig")
+
+ # Split frontmatter and body
+ parts = content.split("---", 2)
+ body = parts[2] if len(parts) >= 3 else content
+
+ body_lower = body.lower()
+
+ # Find existing wiki-links so we don't duplicate
+ existing_links = set(re.findall(r"\[\[([^\]|]+)(?:\|[^\]]+)?\]\]", body))
+
+ # Find mentions of other notes' titles in the body
+ found_links: list[str] = []
+ for ref_text, ref_id in ref_vocab.items():
+ # Skip self-references
+ if ref_id == note_id:
+ continue
+ # Skip if already linked
+ if ref_id in existing_links:
+ continue
+ # Check for whole-word match (not inside code blocks or existing links)
+ # Use word boundary matching
+ pattern = r"(?<!\[\[)\b" + re.escape(ref_text) + r"\b"
+ if re.search(pattern, body_lower):
+ # Verify it's not inside a code block
+ match = re.search(pattern, body_lower)
+ if match and not _in_code_block(body, match.start()):
+ found_links.append(ref_id)
+
+ if not found_links:
+ return []
+
+ # Deduplicate (multiple refs can point to same note)
+ found_links = list(dict.fromkeys(found_links))
+
+ # Append Related section if we found new links
+ related_lines = "\n".join(f"- [[{nid}]]" for nid in found_links)
+ related_section = f"\n\n## Related\n\n{related_lines}\n"
+
+ # Check if there's already a ## Related section
+ if re.search(r"^## Related\s*$", body, re.MULTILINE):
+ # Append to existing Related section
+ body_with_links = re.sub(
+ r"(^## Related\s*\n)",
+ rf"\1{related_lines}\n",
+ body,
+ count=1,
+ flags=re.MULTILINE,
+ )
+ else:
+ body_with_links = body.rstrip() + related_section
+
+ # Reconstruct the file
+ if len(parts) >= 3:
+ new_content = parts[0] + "---" + parts[1] + "---" + body_with_links
+ else:
+ new_content = body_with_links
+
+ note_path.write_text(new_content, encoding="utf-8")
+ return found_links
+
+
+def _in_code_block(text: str, pos: int) -> bool:
+ """Check if a position in text is inside a fenced code block."""
+ # Count ``` before this position
+ fences_before = text[:pos].count("```")
+ # Odd number means we're inside a code block
+ return fences_before % 2 == 1
diff --git a/src/hyperresearch/core/migrations.py b/src/hyperresearch/core/migrations.py
index 8a9156d..0b65aca 100644
--- a/src/hyperresearch/core/migrations.py
+++ b/src/hyperresearch/core/migrations.py
@@ -26,6 +26,26 @@ CREATE TABLE IF NOT EXISTS sources (
);
CREATE INDEX IF NOT EXISTS idx_sources_domain ON sources(domain);
CREATE INDEX IF NOT EXISTS idx_sources_note ON sources(note_id);
+""",
+ 4: """
+CREATE TABLE IF NOT EXISTS assets (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
+ type TEXT NOT NULL CHECK (type IN ('image', 'screenshot', 'pdf', 'other')),
+ filename TEXT NOT NULL,
+ url TEXT,
+ alt_text TEXT,
+ content_type TEXT,
+ size_bytes INTEGER,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_assets_note ON assets(note_id);
+CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type);
+""",
+ 5: """
+-- Dead fields (confidence, superseded_by, llm_compiled, llm_model, compile_source)
+-- removed from code. Left as vestigial columns in existing DBs for compatibility.
+-- New vaults won't have them. No structural changes needed.
""",
}
diff --git a/src/hyperresearch/core/similarity.py b/src/hyperresearch/core/similarity.py
index 8b4982e..2735f67 100644
--- a/src/hyperresearch/core/similarity.py
+++ b/src/hyperresearch/core/similarity.py
@@ -1,7 +1,13 @@
-"""Content similarity — shingle-based Jaccard for dedup and create-time checks."""
+"""Content similarity — shingle-based Jaccard + MinHash/LSH for dedup."""
from __future__ import annotations
+import hashlib
+import struct
+from collections import defaultdict
+
+_MAX_HASH = (1 << 32) - 1
+
def shingle(text: str, n: int = 3) -> set[str]:
"""Extract word-level n-grams (shingles) from text."""
@@ -18,3 +24,58 @@ def jaccard(a: set, b: set) -> float:
intersection = len(a & b)
union = len(a | b)
return intersection / union if union else 0.0
+
+
+def minhash_signature(shingles: set[str], num_perm: int = 128) -> list[int]:
+ """Compute a MinHash signature for a set of shingles.
+
+ Uses SHA-256 with different salts as the hash family.
+ """
+ if not shingles:
+ return [_MAX_HASH] * num_perm
+
+ sig = [_MAX_HASH] * num_perm
+ for s in shingles:
+ s_bytes = s.encode("utf-8")
+ for i in range(num_perm):
+ h = struct.unpack("<I", hashlib.sha256(
+ i.to_bytes(2, "little") + s_bytes
+ ).digest()[:4])[0]
+ if h < sig[i]:
+ sig[i] = h
+ return sig
+
+
+def lsh_candidates(
+ signatures: dict[str, list[int]],
+ bands: int = 16,
+) -> set[tuple[str, str]]:
+ """Find candidate duplicate pairs using Locality-Sensitive Hashing.
+
+ Divides each signature into `bands` bands. Items sharing a band bucket
+ are candidate pairs.
+ """
+ if not signatures:
+ return set()
+
+ num_perm = len(next(iter(signatures.values())))
+ rows_per_band = num_perm // bands
+
+ candidates: set[tuple[str, str]] = set()
+ for band_idx in range(bands):
+ buckets: dict[int, list[str]] = defaultdict(list)
+ start = band_idx * rows_per_band
+ end = start + rows_per_band
+
+ for doc_id, sig in signatures.items():
+ band_hash = hash(tuple(sig[start:end]))
+ buckets[band_hash].append(doc_id)
+
+ for bucket_items in buckets.values():
+ if len(bucket_items) > 1:
+ for i in range(len(bucket_items)):
+ for j in range(i + 1, len(bucket_items)):
+ a, b = bucket_items[i], bucket_items[j]
+ candidates.add((min(a, b), max(a, b)))
+
+ return candidates
diff --git a/src/hyperresearch/core/sync.py b/src/hyperresearch/core/sync.py
index f5f7c5a..7df9805 100644
--- a/src/hyperresearch/core/sync.py
+++ b/src/hyperresearch/core/sync.py
@@ -155,19 +155,15 @@ def _upsert_note_to_db(conn, note, synced_at: str, file_mtime: float = 0) -> Non
conn.execute(
"""
INSERT INTO notes
- (id, title, path, status, type, source, parent, confidence,
- superseded_by, deprecated, reviewed, expires,
- llm_compiled, llm_model, compile_source, word_count, summary,
+ (id, title, path, status, type, source, parent,
+ deprecated, reviewed, expires, word_count, summary,
created, updated, file_mtime, content_hash, synced_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
title=excluded.title, path=excluded.path, status=excluded.status,
type=excluded.type, source=excluded.source, parent=excluded.parent,
- confidence=excluded.confidence,
- superseded_by=excluded.superseded_by, deprecated=excluded.deprecated,
+ deprecated=excluded.deprecated,
reviewed=excluded.reviewed, expires=excluded.expires,
- llm_compiled=excluded.llm_compiled,
- llm_model=excluded.llm_model, compile_source=excluded.compile_source,
word_count=excluded.word_count, summary=excluded.summary,
created=excluded.created, updated=excluded.updated,
file_mtime=excluded.file_mtime, content_hash=excluded.content_hash,
@@ -175,10 +171,8 @@ def _upsert_note_to_db(conn, note, synced_at: str, file_mtime: float = 0) -> Non
""",
(
meta.id, meta.title, note.path, meta.status, meta.type,
- meta.source, meta.parent, meta.confidence,
- meta.superseded_by, 1 if meta.deprecated else 0,
+ meta.source, meta.parent, 1 if meta.deprecated else 0,
reviewed_iso, expires_iso,
- 1 if meta.llm_compiled else 0, meta.llm_model, meta.compile_source,
note.word_count, meta.summary, created_iso, updated_iso,
file_mtime, note.content_hash, synced_at,
),
@@ -194,13 +188,6 @@ def _upsert_note_to_db(conn, note, synced_at: str, file_mtime: float = 0) -> Non
pass
for tag in meta.tags:
resolved = alias_map.get(tag, tag)
- # Auto-normalize plurals: "transformers" -> "transformer" if singular exists
- if resolved.endswith("s") and len(resolved) > 3:
- singular = resolved[:-1]
- if singular in alias_map.values() or conn.execute(
- "SELECT 1 FROM tags WHERE tag = ? LIMIT 1", (singular,)
- ).fetchone():
- resolved = singular
conn.execute("INSERT OR IGNORE INTO tags (note_id, tag) VALUES (?, ?)", (meta.id, resolved))
# Update aliases
diff --git a/src/hyperresearch/core/templates.py b/src/hyperresearch/core/templates.py
index 98a6375..45352ec 100644
--- a/src/hyperresearch/core/templates.py
+++ b/src/hyperresearch/core/templates.py
@@ -56,7 +56,6 @@ status: draft
type: raw
source: ""
summary: ""
-confidence: 0.7
created: {{ created }}
---
diff --git a/src/hyperresearch/mcp/server.py b/src/hyperresearch/mcp/server.py
index b4fa87d..3fb392f 100644
--- a/src/hyperresearch/mcp/server.py
+++ b/src/hyperresearch/mcp/server.py
@@ -274,3 +274,131 @@ def list_sources(domain: str = "", limit: int = 50) -> str:
(limit,),
).fetchall()
return json.dumps([dict(r) for r in rows])
+
+
+def fetch_url(url: str, tags: str = "", provider: str = "") -> str:
+ """Fetch a URL and save it as a research note.
+
+ Args:
+ url: The URL to fetch
+ tags: Comma-separated tags (e.g. "ml,transformers")
+ provider: Web provider override (leave empty for default)
+ """
+ from hyperresearch.core.fetcher import fetch_and_save
+
+ vault = _get_vault()
+ vault.auto_sync()
+ tag_list = [t.strip() for t in tags.split(",") if t.strip()]
+
+ try:
+ result = fetch_and_save(
+ vault, url, tags=tag_list,
+ provider_name=provider or None,
+ )
+ return json.dumps({"ok": True, "data": result})
+ except ValueError as e:
+ return json.dumps({"ok": False, "error": str(e), "error_code": "DUPLICATE_URL"})
+ except Exception as e:
+ return json.dumps({"ok": False, "error": str(e), "error_code": "FETCH_ERROR"})
+
+
+def create_note(title: str, body: str, tags: str = "", source: str = "", summary: str = "") -> str:
+ """Create a new research note.
+
+ Args:
+ title: Note title
+ body: Note body content (markdown)
+ tags: Comma-separated tags
+ source: Source URL (if from the web)
+ summary: One-line summary (auto-generated if empty)
+ """
+ from hyperresearch.core.enrich import enrich_note_file
+ from hyperresearch.core.note import write_note
+ from hyperresearch.core.sync import compute_sync_plan, execute_sync
+
+ vault = _get_vault()
+ vault.auto_sync()
+ tag_list = [t.strip() for t in tags.split(",") if t.strip()]
+
+ extra = {}
+ if source:
+ extra["source"] = source
+
+ note_path = write_note(
+ vault.notes_dir,
+ title=title,
+ body=body,
+ tags=tag_list,
+ status="draft",
+ source=source or None,
+ summary=summary or None,
+ extra_frontmatter=extra if extra else None,
+ )
+
+ enrich_note_file(note_path, vault.db, tag_list)
+
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
+ note_id = note_path.stem
+ return json.dumps({"ok": True, "data": {
+ "note_id": note_id,
+ "title": title,
+ "path": str(note_path.relative_to(vault.root)),
+ }})
+
+
+def update_note(note_id: str, status: str = "", add_tags: str = "", remove_tags: str = "", summary: str = "") -> str:
+ """Update a note's metadata.
+
+ Args:
+ note_id: The note ID to update
+ status: New status (draft/review/evergreen/stale/deprecated/archive)
+ add_tags: Comma-separated tags to add
+ remove_tags: Comma-separated tags to remove
+ summary: New summary text
+ """
+ from hyperresearch.core.frontmatter import parse_frontmatter, serialize_frontmatter
+ from hyperresearch.core.sync import compute_sync_plan, execute_sync
+
+ vault = _get_vault()
+ vault.auto_sync()
+
+ row = vault.db.execute("SELECT path FROM notes WHERE id = ?", (note_id,)).fetchone()
+ if not row:
+ return json.dumps({"ok": False, "error": f"Note not found: {note_id}", "error_code": "NOT_FOUND"})
+
+ file_path = vault.root / row["path"]
+ content = file_path.read_text(encoding="utf-8-sig")
+ meta, body = parse_frontmatter(content)
+
+ changed = []
+ if status:
+ meta.status = status
+ changed.append(f"status={status}")
+ for t in [t.strip() for t in add_tags.split(",") if t.strip()]:
+ if t.lower() not in meta.tags:
+ meta.tags.append(t.lower())
+ changed.append(f"+tag:{t}")
+ for t in [t.strip() for t in remove_tags.split(",") if t.strip()]:
+ if t.lower() in meta.tags:
+ meta.tags.remove(t.lower())
+ changed.append(f"-tag:{t}")
+ if summary:
+ meta.summary = summary
+ changed.append("summary")
+
+ if not changed:
+ return json.dumps({"ok": True, "data": {"note_id": note_id, "changes": []}})
+
+ file_path.write_text(serialize_frontmatter(meta) + "\n" + body, encoding="utf-8")
+
+ plan = compute_sync_plan(vault)
+ if plan.to_add or plan.to_update:
+ execute_sync(vault, plan)
+
+ return json.dumps({"ok": True, "data": {"note_id": note_id, "changes": changed}})
diff --git a/src/hyperresearch/models/note.py b/src/hyperresearch/models/note.py
index b293eb7..e9e8cbe 100644
--- a/src/hyperresearch/models/note.py
+++ b/src/hyperresearch/models/note.py
@@ -36,6 +36,9 @@ def slugify(text: str) -> str:
# Fallback for titles with only special/non-ASCII characters
import hashlib
result = "note-" + hashlib.sha256(text.encode()).hexdigest()[:8]
+ # Truncate to avoid Windows MAX_PATH issues (keep well under 260 chars total)
+ if len(result) > 80:
+ result = result[:80].rstrip("-")
return result
@@ -55,14 +58,9 @@ class NoteMeta(BaseModel):
type: NoteType = NoteType.NOTE
aliases: list[str] = Field(default_factory=list)
parent: str | None = None
- confidence: float | None = None
- superseded_by: str | None = None # Note ID that replaces this one
deprecated: bool = False # Explicitly marked as outdated
reviewed: datetime | None = None # Last time a human verified accuracy
expires: datetime | None = None # Auto-stale after this date
- llm_compiled: bool = False
- llm_model: str | None = None
- compile_source: str | None = None
summary: str | None = None
@field_validator("tags", mode="before")
@@ -77,7 +75,7 @@ class NoteMeta(BaseModel):
return slugify(v)
return v
- model_config = {"use_enum_values": True}
+ model_config = {"use_enum_values": True, "extra": "ignore"}
class Note(BaseModel):
diff --git a/src/hyperresearch/skills/__init__.py b/src/hyperresearch/skills/__init__.py
new file mode 100644
index 0000000..9679813
--- /dev/null
+++ b/src/hyperresearch/skills/__init__.py
@@ -0,0 +1 @@
+"""Bundled skills for hyperresearch."""
diff --git a/src/hyperresearch/skills/research.md b/src/hyperresearch/skills/research.md
new file mode 100644
index 0000000..4dfa6e0
--- /dev/null
+++ b/src/hyperresearch/skills/research.md
@@ -0,0 +1,172 @@
+---
+name: research
+description: >
+ Deep research on any topic. Searches the web, fetches sources with a headless browser,
+ follows links to primary sources, builds a searchable knowledge base, and synthesizes
+ findings. Use when the user asks to research, investigate, or learn about a topic.
+ Trigger: /research
+---
+
+# Deep Research Skill
+
+## Step 0: Clarify the request
+
+Before doing ANY research, evaluate the user's request. If it is vague, ambiguous, or could go in multiple directions, **ask clarifying questions first**. Do not guess — ask. Examples:
+
+- "Research AI models" → Ask: "Which aspect? Training techniques, specific architectures, benchmarks, a particular company's models, deployment strategies?"
+- "Find out about this company" → Ask: "What specifically? Financials, leadership, products, tech stack, culture, recent news?"
+- "Look into transformers" → Ask: "The neural network architecture, or a specific variant? Are you interested in the theory, practical implementation, or recent alternatives like Mamba?"
+
+Ask 1-3 focused questions. Once you understand the scope, proceed. If the request is already specific and clear, skip this step and start researching immediately.
+
+---
+
+When invoked, follow these steps **in order**. Do not skip steps. The CLI path will be provided by the CLAUDE.md — look for the "CLI path:" line in the Research Base section.
+
+If you can't find the CLI path, check for the hyperresearch executable:
+```bash
+which hyperresearch 2>/dev/null || where hyperresearch 2>/dev/null || find . -path "*/.venv/*/hyperresearch*" -type f 2>/dev/null | head -1
+```
+Store it in a variable: `HPR="<path>"` for the rest of this workflow.
+
+## Step 1: Check existing knowledge
+
+Before searching the web, check what's already in the research base:
+
+```bash
+$HPR search "<topic>" --include-body -j
+$HPR sources list -j
+```
+
+If there's already substantial coverage, tell the user what's known and ask if they want deeper research or a specific angle.
+
+## Step 2: Search broadly
+
+Run **multiple web searches** with different phrasings. Don't stop at one query:
+
+```
+WebSearch("<topic>")
+WebSearch("<topic> research paper 2025 2026")
+WebSearch("<topic> deep dive technical")
+WebSearch("<related angle or subtopic>")
+```
+
+Collect ALL promising URLs — aim for 10-20 sources minimum. More is better. You'll prune later.
+
+## Step 3: Fetch everything
+
+Spawn `hyperresearch-fetcher` subagents to fetch URLs in parallel. They run on Haiku (cheap).
+
+```
+Spawn hyperresearch-fetcher agents for each URL batch:
+- Batch 1: [url1, url2, url3, url4, url5]
+- Batch 2: [url6, url7, url8, url9, url10]
+```
+
+Each fetcher will report back with note IDs and interesting links found in the content.
+
+**Over-collect.** It is always better to have too many sources than too few. You can deprecate notes later.
+
+## Step 4: Go down rabbit holes
+
+Read the fetched notes and follow links to deeper material:
+
+```bash
+$HPR note show <note-id> -j
+```
+
+For each note, look for:
+- **Papers cited** → fetch them
+- **Documentation linked** → fetch it
+- **GitHub repos mentioned** → fetch the README
+- **Related topics referenced** → search and fetch
+- **People/companies mentioned** → fetch their pages
+
+Spawn more fetcher agents for these secondary sources. Keep going until you've exhausted the link trail or have 20+ sources.
+
+## Step 5: Auto-link and curate
+
+Run the auto-linker to connect related notes:
+
+```bash
+$HPR link --auto -j
+```
+
+Check what tags exist and ensure consistency:
+
+```bash
+$HPR tags -j
+```
+
+Update any notes missing summaries (auto-curation handles most, but fix any gaps):
+
+```bash
+$HPR lint -j
+$HPR repair -j
+```
+
+## Step 6: Discover the knowledge graph
+
+Find the hub notes and key connections:
+
+```bash
+$HPR graph hubs -j
+$HPR graph backlinks <most-linked-note-id> -j
+```
+
+## Step 7: Synthesize and report
+
+Search the full research base with bodies:
+
+```bash
+$HPR search "<topic>" --include-body -j
+```
+
+Read the top notes and build a comprehensive synthesis. Then **save the synthesis as a note**:
+
+Write your synthesis to a temp file and save it:
+```bash
+cat > /tmp/synthesis.md << 'SYNTHESIS'
+# <Topic> — Research Synthesis
+
+## Key Findings
+<your synthesis here>
+
+## Sources
+<wiki-links to all source notes: [[note-id-1]], [[note-id-2]], etc.>
+
+## Open Questions
+<what wasn't answered, what needs more research>
+SYNTHESIS
+
+$HPR note new "Synthesis: <topic>" --tag <topic> --tag synthesis --type moc --status review --body-file /tmp/synthesis.md --summary "<one-line summary of findings>" -j
+```
+
+## Step 8: Present to user
+
+Present your findings with:
+
+1. **Executive summary** — 2-3 sentence answer to their question
+2. **Key findings table** — the most important discoveries
+3. **Sources collected** — how many notes, from which domains
+4. **Hub notes** — the most-referenced/important notes in the graph
+5. **Open questions** — what you didn't find or what needs more research
+6. **How to explore** — tell them they can ask follow-up questions and you'll search the KB
+
+Example closing:
+```
+Research complete. 15 sources collected on "<topic>":
+- 3 primary papers, 5 technical blogs, 4 documentation pages, 3 news articles
+- Hub notes: [[key-note-1]], [[key-note-2]]
+- All sources are saved and searchable across sessions.
+
+Ask me anything about this topic — I'll search the research base first.
+```
+
+## Important rules
+
+- **NEVER use WebFetch for source pages.** Always use `$HPR fetch` or the fetcher subagent.
+- **Over-collect, then prune.** Fetch aggressively. Deprecate irrelevant notes after synthesis.
+- **Save raw content.** Don't rewrite or summarize sources before saving. The full text is the value.
+- **Follow links.** A blog post about a paper is not the paper. Fetch the paper.
+- **Save your synthesis.** Every research session should produce a synthesis note that future agents can find.
diff --git a/src/hyperresearch/web/base.py b/src/hyperresearch/web/base.py
index 84b707c..ee2afbe 100644
--- a/src/hyperresearch/web/base.py
+++ b/src/hyperresearch/web/base.py
@@ -17,6 +17,9 @@ class WebResult:
fetched_at: datetime = field(default_factory=lambda: datetime.now(UTC))
raw_html: str | None = None
metadata: dict = field(default_factory=dict) # author, date, domain, etc.
+ media: list[dict] = field(default_factory=list) # images: {src, alt, score, ...}
+ links: list[dict] = field(default_factory=list) # {href, text, type}
+ screenshot: bytes | None = None # PNG screenshot of the rendered page
@property
def domain(self) -> str:
@@ -24,6 +27,33 @@ class WebResult:
return urlparse(self.url).netloc
+ def looks_like_login_wall(self, original_url: str) -> bool:
+ """Check if the result appears to be a login/signup redirect rather than real content."""
+ login_signals = (
+ "sign in", "sign up", "log in", "login", "create account",
+ "auth", "register", "sso", "verify your identity",
+ )
+ title_lower = (self.title or "").lower()
+ content_lower = (self.content or "")[:500].lower()
+
+ # Title contains login language
+ title_match = any(s in title_lower for s in login_signals)
+
+ # Content is mostly login form (very short with login keywords)
+ content_match = (
+ len(self.content or "") < 1000
+ and any(s in content_lower for s in login_signals)
+ )
+
+ # URL changed to a login/auth path
+ from urllib.parse import urlparse
+
+ result_path = urlparse(self.url).path.lower()
+ auth_paths = ("/login", "/signin", "/signup", "/auth", "/sso", "/register")
+ url_redirected = any(p in result_path for p in auth_paths)
+
+ return title_match or content_match or url_redirected
+
@runtime_checkable
class WebProvider(Protocol):
@@ -44,7 +74,12 @@ class WebProvider(Protocol):
...
-def get_provider(name: str | None = None) -> WebProvider:
+def get_provider(
+ name: str | None = None,
+ profile: str | None = None,
+ magic: bool = False,
+ headless: bool = True,
+) -> WebProvider:
"""Load a web provider by name. Falls back to builtin if none specified."""
if name is None or name == "builtin":
from hyperresearch.web.builtin import BuiltinProvider
@@ -55,34 +90,12 @@ def get_provider(name: str | None = None) -> WebProvider:
try:
from hyperresearch.web.crawl4ai_provider import Crawl4AIProvider
- return Crawl4AIProvider()
+ return Crawl4AIProvider(
+ profile=profile or None,
+ magic=magic,
+ headless=headless,
+ )
except ImportError:
raise ImportError("crawl4ai provider requires: pip install hyperresearch[crawl4ai]")
- if name == "tavily":
- try:
- from hyperresearch.web.tavily_provider import TavilyProvider
-
- return TavilyProvider()
- except ImportError:
- raise ImportError("tavily provider requires: pip install hyperresearch[tavily]")
-
- if name == "firecrawl":
- try:
- from hyperresearch.web.firecrawl_provider import FirecrawlProvider
-
- return FirecrawlProvider()
- except ImportError:
- raise ImportError("firecrawl provider requires: pip install hyperresearch[firecrawl]")
-
- if name == "trafilatura":
- try:
- from hyperresearch.web.trafilatura_provider import TrafilaturaProvider
-
- return TrafilaturaProvider()
- except ImportError:
- raise ImportError(
- "trafilatura provider requires: pip install hyperresearch[trafilatura]"
- )
-
- raise ValueError(f"Unknown web provider: {name!r}")
+ raise ValueError(f"Unknown web provider: {name!r}. Available: builtin, crawl4ai")
diff --git a/src/hyperresearch/web/builtin.py b/src/hyperresearch/web/builtin.py
index de7b24b..c359fea 100644
--- a/src/hyperresearch/web/builtin.py
+++ b/src/hyperresearch/web/builtin.py
@@ -66,8 +66,7 @@ class BuiltinProvider:
def search(self, query: str, max_results: int = 5) -> list[WebResult]:
raise NotImplementedError(
"Builtin provider does not support web search. "
- "Install a search-capable provider: pip install hyperresearch[tavily] "
- "or pip install hyperresearch[crawl4ai]"
+ "Use your agent's built-in search, then pipe URLs into 'hyperresearch fetch'."
)
def _download(self, url: str) -> tuple[str, str]:
diff --git a/src/hyperresearch/web/crawl4ai_provider.py b/src/hyperresearch/web/crawl4ai_provider.py
index 0c796ca..a6353bf 100644
--- a/src/hyperresearch/web/crawl4ai_provider.py
+++ b/src/hyperresearch/web/crawl4ai_provider.py
@@ -1,34 +1,253 @@
-"""Crawl4AI web provider — free, open-source, handles JS rendering."""
+"""Crawl4AI web provider — free, open-source, local headless browser, returns clean markdown.
+
+Supports authenticated crawling via crawl4ai browser profiles:
+ 1. Run `crwl profiles` or `hyperresearch setup` to create a profile and log in
+ 2. Set `profile = "profile-name"` in .hyperresearch/config.toml
+ 3. All fetches now use your authenticated session (cookies, localStorage, etc.)
+"""
from __future__ import annotations
+import asyncio
+import os
+import pathlib
+import sys
from datetime import UTC, datetime
-from crawl4ai import WebCrawler
+from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
from hyperresearch.web.base import WebResult
+# Fix Windows encoding before crawl4ai's managed browser tries to log Unicode
+if sys.platform == "win32":
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
+ os.environ.setdefault("PYTHONUTF8", "1")
+ for _stream in (sys.stdout, sys.stderr):
+ if hasattr(_stream, "reconfigure"):
+ try:
+ _stream.reconfigure(encoding="utf-8", errors="replace")
+ except Exception:
+ pass
+
class Crawl4AIProvider:
name = "crawl4ai"
- def __init__(self):
- self._crawler = WebCrawler()
- self._crawler.warmup()
+ def __init__(
+ self,
+ headless: bool = True,
+ user_data_dir: str | None = None,
+ profile: str | None = None,
+ cookies: list[dict] | None = None,
+ magic: bool = False,
+ ):
+ # Resolve profile name to path (crawl4ai stores profiles in ~/.crawl4ai/profiles/)
+ data_dir = user_data_dir
+ if profile and not data_dir:
+ data_dir = str(pathlib.Path.home() / ".crawl4ai" / "profiles" / profile)
+
+ self._data_dir = data_dir
+ self._headless = headless
+ self._cookies = cookies
+
+ browser_kwargs: dict = {"headless": headless}
+ if data_dir:
+ browser_kwargs["use_managed_browser"] = True
+ browser_kwargs["user_data_dir"] = data_dir
+ if cookies:
+ browser_kwargs["cookies"] = cookies
+
+ self._browser_config = BrowserConfig(**browser_kwargs)
+
+ # Smart wait: 2s initial + poll until content stabilizes (10s ceiling)
+ self._wait_js = (
+ "js:() => new Promise(r => {"
+ " setTimeout(() => {"
+ " let last = document.body.innerText.length;"
+ " let stable = 0;"
+ " let checks = 0;"
+ " const interval = setInterval(() => {"
+ " const now = document.body.innerText.length;"
+ " if (now === last) { stable++; } else { stable = 0; }"
+ " if (stable >= 2 || checks > 16) { clearInterval(interval); r(true); }"
+ " last = now; checks++;"
+ " }, 500);"
+ " }, 2000);"
+ "})"
+ )
+ self._run_config = CrawlerRunConfig(
+ magic=magic,
+ simulate_user=True,
+ screenshot=True,
+ page_timeout=30000,
+ wait_for=self._wait_js,
+ )
def fetch(self, url: str) -> WebResult:
- result = self._crawler.run(url=url)
+ # When visible + profile: use Playwright directly (crawl4ai managed browser ignores headless=False)
+ if not self._headless and self._data_dir:
+ return asyncio.run(self._fetch_visible(url))
+ return asyncio.run(self._fetch_async(url))
+
+ async def _fetch_visible(self, url: str) -> WebResult:
+ """Fetch using Playwright directly with a visible browser window.
+
+ crawl4ai's managed browser always forces headless. For sites like LinkedIn
+ that detect headless mode and kill sessions, we need a truly visible browser.
+ """
+ from playwright.async_api import async_playwright
+
+ async with async_playwright() as pw:
+ context = await pw.chromium.launch_persistent_context(
+ user_data_dir=self._data_dir,
+ headless=False,
+ viewport={"width": 1280, "height": 900},
+ ignore_https_errors=True,
+ )
+ page = context.pages[0] if context.pages else await context.new_page()
+ await page.goto(url, wait_until="domcontentloaded", timeout=30000)
+
+ # Smart wait — same logic as crawl4ai config
+ await page.evaluate("""() => new Promise(r => {
+ setTimeout(() => {
+ let last = document.body.innerText.length;
+ let stable = 0;
+ let checks = 0;
+ const interval = setInterval(() => {
+ const now = document.body.innerText.length;
+ if (now === last) { stable++; } else { stable = 0; }
+ if (stable >= 2 || checks > 16) { clearInterval(interval); r(true); }
+ last = now; checks++;
+ }, 500);
+ }, 2000);
+ })""")
+
+ html = await page.content()
+ title = await page.title()
+ screenshot_bytes = await page.screenshot(type="png")
+ final_url = page.url
+
+ await context.close()
+
+ # Convert HTML to markdown using crawl4ai's markdown generator
+ from crawl4ai import DefaultMarkdownGenerator
+
+ md_gen = DefaultMarkdownGenerator()
+ md_result = md_gen.generate_markdown(html, base_url=final_url)
+ content = ""
+ if md_result and hasattr(md_result, "raw_markdown"):
+ content = md_result.raw_markdown or ""
+ elif isinstance(md_result, str):
+ content = md_result
+
return WebResult(
- url=url,
- title=result.metadata.get("title", "") if result.metadata else "",
- content=result.markdown or result.extracted_content or "",
- raw_html=result.html,
+ url=final_url,
+ title=title,
+ content=content,
+ raw_html=html,
fetched_at=datetime.now(UTC),
- metadata=result.metadata or {},
+ metadata={"title": title},
+ screenshot=screenshot_bytes,
)
+ async def _fetch_async(self, url: str) -> WebResult:
+ async with AsyncWebCrawler(config=self._browser_config) as crawler:
+ result = await crawler.arun(url=url, config=self._run_config)
+ metadata = result.metadata or {}
+
+ # result.markdown is a MarkdownGenerationResult with .raw_markdown,
+ # .fit_markdown, .markdown_with_citations, etc.
+ md = result.markdown
+ if md and hasattr(md, "raw_markdown"):
+ content = md.raw_markdown or ""
+ elif isinstance(md, str):
+ content = md
+ else:
+ content = ""
+
+ # Extract media (images) — crawl4ai returns dict with 'images' key
+ media_raw = result.media or {}
+ media = media_raw.get("images", []) if isinstance(media_raw, dict) else []
+
+ # Extract links — crawl4ai returns dict with 'internal'/'external' keys
+ links_raw = result.links or {}
+ links = []
+ if isinstance(links_raw, dict):
+ for link in links_raw.get("internal", []):
+ links.append({**link, "type": "internal"})
+ for link in links_raw.get("external", []):
+ links.append({**link, "type": "external"})
+
+ # Decode screenshot from base64 if present
+ screenshot_bytes = None
+ if result.screenshot:
+ import base64
+
+ try:
+ screenshot_bytes = base64.b64decode(result.screenshot)
+ except Exception:
+ pass
+
+ return WebResult(
+ url=result.url or url,
+ title=metadata.get("title", ""),
+ content=content,
+ raw_html=result.html,
+ fetched_at=datetime.now(UTC),
+ metadata=metadata,
+ media=media,
+ links=links,
+ screenshot=screenshot_bytes,
+ )
+
+ def fetch_many(self, urls: list[str]) -> list[WebResult]:
+ """Fetch multiple URLs concurrently using crawl4ai's arun_many."""
+ return asyncio.run(self._fetch_many_async(urls))
+
+ async def _fetch_many_async(self, urls: list[str]) -> list[WebResult]:
+ async with AsyncWebCrawler(config=self._browser_config) as crawler:
+ results = await crawler.arun_many(urls=urls, config=self._run_config)
+ web_results = []
+ for cr, url in zip(results, urls, strict=False):
+ if not cr.success:
+ continue
+ metadata = cr.metadata or {}
+ md = cr.markdown
+ if md and hasattr(md, "raw_markdown"):
+ content = md.raw_markdown or ""
+ elif isinstance(md, str):
+ content = md
+ else:
+ content = ""
+
+ media_raw = cr.media or {}
+ media = media_raw.get("images", []) if isinstance(media_raw, dict) else []
+
+ screenshot_bytes = None
+ if cr.screenshot:
+ import base64
+
+ try:
+ screenshot_bytes = base64.b64decode(cr.screenshot)
+ except Exception:
+ pass
+
+ web_results.append(WebResult(
+ url=cr.url or url,
+ title=metadata.get("title", ""),
+ content=content,
+ raw_html=cr.html,
+ fetched_at=datetime.now(UTC),
+ metadata=metadata,
+ media=media,
+ screenshot=screenshot_bytes,
+ ))
+ return web_results
+
def search(self, query: str, max_results: int = 5) -> list[WebResult]:
raise NotImplementedError(
- "crawl4ai does not support web search directly. "
- "Use tavily for search: pip install hyperresearch[tavily]"
+ "crawl4ai does not support web search. "
+ "Use your agent's built-in search, then pipe URLs into 'hyperresearch fetch'."
)
+
+
diff --git a/src/hyperresearch/web/firecrawl_provider.py b/src/hyperresearch/web/firecrawl_provider.py
deleted file mode 100644
index 82cba9e..0000000
--- a/src/hyperresearch/web/firecrawl_provider.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Firecrawl web provider — AI-optimized scraping, returns clean markdown."""
-
-from __future__ import annotations
-
-import os
-from datetime import UTC, datetime
-
-from firecrawl import FirecrawlApp
-
-from hyperresearch.web.base import WebResult
-
-
-class FirecrawlProvider:
- name = "firecrawl"
-
- def __init__(self, api_key: str | None = None, api_url: str | None = None):
- key = api_key or os.environ.get("FIRECRAWL_API_KEY", "")
- url = api_url or os.environ.get("FIRECRAWL_API_URL")
- kwargs = {}
- if key:
- kwargs["api_key"] = key
- if url:
- kwargs["api_url"] = url
- self._app = FirecrawlApp(**kwargs)
-
- def fetch(self, url: str) -> WebResult:
- result = self._app.scrape_url(url, params={"formats": ["markdown"]})
- return WebResult(
- url=url,
- title=result.get("metadata", {}).get("title", ""),
- content=result.get("markdown", ""),
- raw_html=result.get("html"),
- fetched_at=datetime.now(UTC),
- metadata=result.get("metadata", {}),
- )
-
- def search(self, query: str, max_results: int = 5) -> list[WebResult]:
- raise NotImplementedError(
- "Firecrawl does not support web search directly. "
- "Use tavily for search: pip install hyperresearch[tavily]"
- )
diff --git a/src/hyperresearch/web/tavily_provider.py b/src/hyperresearch/web/tavily_provider.py
deleted file mode 100644
index 01a75ee..0000000
--- a/src/hyperresearch/web/tavily_provider.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Tavily web provider — search + extract API for LLM agents."""
-
-from __future__ import annotations
-
-import os
-from datetime import UTC, datetime
-
-from tavily import TavilyClient
-
-from hyperresearch.web.base import WebResult
-
-
-class TavilyProvider:
- name = "tavily"
-
- def __init__(self, api_key: str | None = None):
- key = api_key or os.environ.get("TAVILY_API_KEY", "")
- if not key:
- raise ValueError(
- "Tavily API key required. Set TAVILY_API_KEY env var "
- "or configure in .hyperresearch/config.toml"
- )
- self._client = TavilyClient(api_key=key)
-
- def fetch(self, url: str) -> WebResult:
- result = self._client.extract(urls=[url])
- if result and result.get("results"):
- r = result["results"][0]
- return WebResult(
- url=url,
- title=r.get("title", ""),
- content=r.get("raw_content", r.get("text", "")),
- fetched_at=datetime.now(UTC),
- metadata={"source": "tavily-extract"},
- )
- raise RuntimeError(f"Tavily extract returned no results for {url}")
-
- def search(self, query: str, max_results: int = 5) -> list[WebResult]:
- response = self._client.search(
- query=query,
- max_results=max_results,
- include_raw_content=True,
- )
- results = []
- for r in response.get("results", []):
- results.append(
- WebResult(
- url=r["url"],
- title=r.get("title", ""),
- content=r.get("raw_content", r.get("content", "")),
- fetched_at=datetime.now(UTC),
- metadata={"score": r.get("score", 0), "source": "tavily-search"},
- )
- )
- return results
diff --git a/src/hyperresearch/web/trafilatura_provider.py b/src/hyperresearch/web/trafilatura_provider.py
deleted file mode 100644
index a9386ea..0000000
--- a/src/hyperresearch/web/trafilatura_provider.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""Trafilatura web provider — lightweight text extraction, no JS rendering."""
-
-from __future__ import annotations
-
-from datetime import UTC, datetime
-
-import trafilatura
-
-from hyperresearch.web.base import WebResult
-
-
-class TrafilaturaProvider:
- name = "trafilatura"
-
- def fetch(self, url: str) -> WebResult:
- downloaded = trafilatura.fetch_url(url)
- if downloaded is None:
- raise RuntimeError(f"Failed to download {url}")
-
- content = trafilatura.extract(
- downloaded,
- output_format="txt",
- include_links=True,
- include_tables=True,
- ) or ""
-
- metadata = trafilatura.extract_metadata(downloaded)
- title = metadata.title if metadata and metadata.title else ""
- meta_dict = {}
- if metadata:
- if metadata.author:
- meta_dict["author"] = metadata.author
- if metadata.date:
- meta_dict["date"] = metadata.date
-
- return WebResult(
- url=url,
- title=title,
- content=content,
- raw_html=downloaded,
- fetched_at=datetime.now(UTC),
- metadata=meta_dict,
- )
-
- def search(self, query: str, max_results: int = 5) -> list[WebResult]:
- raise NotImplementedError(
- "Trafilatura does not support web search. "
- "Use tavily for search: pip install hyperresearch[tavily]"
- )