Course framing: Turn your knowledge base into an autonomous, budget-bounded research system: decompose multi-hop technical questions, iterate over 3-way hybrid retrieval with explicit iteration and USD cost caps, verify every research report with Week 5's deterministic and binary judges, publish an automated weekly newsletter digest on a cron schedule, and package the entire stack for production.
This guide is the capstone of The Substack Brain (Weeks 1–6). Every architectural primitive built in Weeks 1–5—durable step execution (ctx.step.run), CostCaptureMiddleware, the Asymmetry Principle (<50ms writes vs. <1s reads), the 5-node Memgraph ontology + 3-way RRF (hybrid_3way_rrf_k60), and our calibrated evaluation suite (FM-1–FM-6)—converges here.
The main README.md has the high-level course overview. This file is the full architectural and implementation walkthrough for Week 6.
Single-shot RAG (POST /ask) answers focused questions in under two seconds, but complex engineering investigations rarely fit into a single retrieval query:
- "Compare how The Neural Maze, Decoding AI, and Ahead of AI evaluate agent orchestration vs. test-time compute, including concrete latency/cost measurements and where the authors disagree."
At the same time, unconstrained "autonomous" agent loops fail in production for three predictable reasons:
- Runaway token and API loops: Re-querying the same concepts endlessly until a rate limit or timeout kills the worker—losing all intermediate progress.
- Context window pollution: Dumping duplicate chunks from multiple hops into the final prompt without deduplicating or preserving claim lineage.
- Unverified synthesis: Returning a long multi-hop report without checking whether inline citations
[k]are valid, active (valid_to IS NULL), and faithful to epistemicclaim_typeboundaries.
By the end of Week 6, you will have:
- A Bounded Research Agent (
run-research-agentinkb/functions/research.py):- Built directly on Inngest durable steps (
ctx.step.run) and our hand-written agent layer (kb/agents/core.py&kb/agents/roles/researcher.py)—with zero agent frameworks. - Enforces three hard termination guardrails:
max_iterations(default3),max_usd(default$0.25tracked across steps), and a zero-new-passages convergence check that stops immediately if a hop discovers no new uniquepassage_ids. - Evaluates its own synthesized report using Week 5's Level 1 deterministic checks (
FM-1–FM-3) and Level 2 binary judges (FM-4faithfulness,FM-5cross-publication disagreement coverage) before persisting toresearch_runs.
- Built directly on Inngest durable steps (
- An Automated Weekly Digest (
generate-weekly-digestinkb/functions/digest.py):- Runs every Monday at 08:00 UTC (
0 8 * * 1) or on-demand viaPOST /digests/run(kb/digest.requested). - Aggregates the week's ingested articles, quote-verified claims, and cross-publication
:Topichubs into a cited markdown briefing stored indigests.
- Runs every Monday at 08:00 UTC (
- HTTP & MCP Research Interfaces (
POST /research,GET /research/{id},kb_research,kb_research_result,kb_weekly_digest):- Honors Week 3's Asymmetry Principle: queuing a multi-hop research run takes
<50msand returns{research_id, event_id, trace_url, status: "queued"}; reading the completed report or weekly digest queries Postgres directly in<1s.
- Honors Week 3's Asymmetry Principle: queuing a multi-hop research run takes
- Production Deployment Packaging (
Dockerfile&infra/docker-compose.prod.yml):- A locked, multi-stage
uvcontainer image and production Compose stack (INNGEST_DEV=false, signing/event keys, health checks) ready to deploy.
- A locked, multi-stage
POST /research (or kb_research) ──▶ emits kb/research.requested (<50ms)
│
▼
run-research-agent (Inngest)
├─ 1. record-research-start (status="running")
├─ 2. plan-subqueries (QueryPlannerAgent)
├─ 3. hop-1-retrieve (3-way RRF + deduplication)
├─ 4. hop-1-reflect (CoverageCriticAgent: stop or follow-up)
├─ 5. hop-2-retrieve / hop-2-reflect (bounded by max_iterations & max_usd)
├─ 6. synthesize-report (ResearchSynthesizerAgent with [k] citations)
├─ 7. evaluate-report (Week 5 deterministic + binary judges)
├─ 8. persist-research-run (writes research_runs)
└─ 9. emit-research-completed (kb/research.completed)
Cron (0 8 * * 1) / POST /digests/run ──▶ generate-weekly-digest ──▶ writes digests + emits kb/digest.published
Run:
make start
make start brings up Postgres, Memgraph, Memgraph Lab, Adminer, and the Inngest Dev Server, runs uv run python -m alembic upgrade head (applying alembic/versions/b8d2e4f6a1c3_week_6_research_and_digest_tables.py to create research_runs and digests), and starts FastAPI on http://localhost:8000.
Verify the new tables exist in Postgres:
docker compose -f infra/docker-compose.yml exec -T postgres \ psql -U substack_brain -d substack_brain -c "\dt"
You will see research_runs and digests alongside publications, articles, passages, claims, snapshots, failures, eval_results, and eval_runs—each adhering strictly to our one writer per table invariant:
research_runsis written exclusively byrun-research-agent.digestsis written exclusively bygenerate-weekly-digest.
Step 2 — Inside the Bounded Research Agent (kb/agents/roles/researcher.py & kb/functions/research.py)
Instead of a monolithic prompt or an opaque graph framework, kb/agents/roles/researcher.py defines three single-purpose roles on top of kb/agents/core.py:Agent:
query_planner_agent(Agent[ResearchPlan]):- Outputs
{rationale: str, subqueries: list[str], target_topics: list[str]}. - Decomposes the user's question into
1..3initial search queries spanning lexical identifiers, semantic concepts, and canonical graph topics.
- Outputs
coverage_critic_agent(Agent[CoverageReflection]):- Outputs
{rationale: str, is_sufficient: bool, missing_aspects: list[str], followup_queries: list[str]}. - Inspects the cumulative deduplicated evidence pool after each hop and decides whether to stop (
is_sufficient=True) or issue1..2targeted follow-up queries that have not yet been executed.
- Outputs
research_synthesizer_agent:- Writes the final multi-section technical brief from the top deduplicated passages and claims, citing sources inline (
[1],[2]), respecting epistemicclaim_typeboundaries (measurement,opinion,prediction), and surfacing cross-publication disagreements.
- Writes the final multi-section technical brief from the top deduplicated passages and claims, citing sources inline (
Every hop in run-research-agent (kb/functions/research.py) checks three deterministic bounds before spending tokens on another iteration:
-
Iteration Cap (
max_iterations, default3, max5): The loop never exceedsmax_iterationsretrieval hops. -
USD Budget Cap (
max_usd, default$0.25): Every LLM call returns"usage": {"est_usd": ...}(andrun_agent_with_usagethreadsest_usdintobounded_loop). If accumulated step cost reachesmax_usd, the agent exits the loop immediately, synthesizes from the evidence gathered so far, and marksstop_reason = "budget_exceeded". -
Convergence Guard (
newly_added == 0):merge_hop_candidatesdeduplicates retrieved passages bypassage_id, keeping the highestrrf_scoreand merging anyclaim_id/claim_typemetadata. If hop$i > 1$ yields zero new unique passages, the loop halts immediately without paying for a critic LLM call.
Trigger a multi-hop research run over HTTP:
curl -X POST http://localhost:8000/research \ -H "Content-Type: application/json" \ -d '{ "question": "How do durable execution engines, hybrid RRF retrieval, and knowledge graphs work together in production AI systems?", "max_iterations": 3, "max_usd": 0.25 }'
What happens after running this:
-
Non-blocking dispatch (
<50ms): FastAPI generates ares_<12 chars>ID, emitskb/research.requested, and returns immediately:{ "research_id": "res_...", "event_id": "01J...", "trace_url": "http://localhost:8288/event/01J...", "status": "queued" } -
Durable multi-hop execution (
http://localhost:8288): Open the Inngest UI to watch each memoized step (record-research-start$\rightarrow$ plan-subqueries$\rightarrow$ hop-1-retrieve$\rightarrow$ hop-1-reflect$\rightarrow$ ...$\rightarrow$ synthesize-report$\rightarrow$ evaluate-report$\rightarrow$ persist-research-run). -
Fetch the completed research report (
<20ms):Returns the fullcurl http://localhost:8000/research/<research_id>
research_runsrecord:plan, per-hophopstrace (queries, newly added passage counts, critic rationale, step USD cost),reportmarkdown, inlinecitations,eval_summary(deterministic_passed,faithfulness_verdict,disagreement_verdict,failure_codes),confidence,iterations_used, andtotal_cost_usd.
generate-weekly-digest (kb/functions/digest.py) runs automatically every Monday at 08:00 UTC (cron: "0 8 * * 1") and can also be triggered on demand via HTTP:
curl -X POST http://localhost:8000/digests/run \ -H "Content-Type: application/json" \ -d '{"lookback_days": 7}'
Fetch the latest generated digest:
curl http://localhost:8000/digests/latest
What happens under the hood:
-
collect-weekly-windowqueries Postgres for articles published in the window (falling back to the 15 most recent articles when testing on a local corpus whose posts are older than 7 days), their active verified claims (valid_to IS NULL), and canonical:Topichubs shared across$\ge 2$ publications. -
synthesize-weekly-digestwrites a cited markdown briefing organized into Key Technical Claims & Measurements, Cross-Publication Threads & Disagreements, and Watchlist & Predictions. -
verify-and-persist-digestruns Week 5'srun_deterministic_checks(FM-1–FM-3) to verify every inline[k]citation against the digest's evidence list, upserts the digest intodigestsusing a deterministic UUIDv5 key for the date window, and emitskb/digest.published.
Week 6 adds three tools to kb/mcp/tools.py and kb/mcp/server.py, bringing the complete MCP server to 13 tools:
| Tool | Type | What it does |
|---|---|---|
kb_research(question, max_iterations, max_usd) |
Slow Write (<50ms) |
Queues run-research-agent in Inngest and returns {research_id, event_id, trace_url, status: "queued"}. |
kb_research_result(research_id) |
Fast Read (<1s) |
Queries research_runs in Postgres for the hop trace, cited markdown report, and evaluation verdicts. |
kb_weekly_digest() |
Fast Read (<1s) |
Returns the latest weekly digest, cross-publication topic threads, and citations from digests. |
Try asking Claude Code or Cursor:
- "Run a bounded research investigation (max 2 hops) on how different newsletters approach RAG retrieval and agent orchestration, then inspect the research result."
- "Fetch the latest weekly digest from our Substack knowledge base."
In Weeks 1–5, make start ran Postgres, Memgraph, and the Inngest Dev Server in Docker while running uvicorn kb.main:app --reload on your host machine for fast local iteration.
For production deployment, Week 6 ships two artifacts:
Dockerfile:- Uses
python:3.12-slimwithuv(ghcr.io/astral-sh/uv:0.5.29). - Installs locked dependencies (
uv sync --frozen --no-dev) with bytecode compilation enabled (UV_COMPILE_BYTECODE=1). - Runs
uv run python -m alembic upgrade headon startup before launchinguvicorn kb.main:app --host 0.0.0.0 --port 8000.
- Uses
infra/docker-compose.prod.yml:- Runs
postgres,memgraph, andkb-appwithrestart: alwaysand container health checks. - Sets
INNGEST_DEV=false(which flipsclient = inngest.Inngest(..., is_production=not settings.inngest_dev)inkb/inngest_client.pyinto production signature-verification mode) and requiresINNGEST_EVENT_KEYandINNGEST_SIGNING_KEY.
- Runs
make start in Makefile automatically inspects INNGEST_DEV in your .env and boots the matching mode:
- In
.env:INNGEST_DEV=1 INNGEST_BASE_URL=http://localhost:8288
- Run:
Starts
make start
postgres,adminer,inngest-dev(http://localhost:8288),memgraph, andmemgraph-lab, runsalembic upgrade head, and startsuvicorn kb.main:app --reload --port 8000. The localinngest-devcontainer auto-discovershttp://host.docker.internal:8000/api/inngest.
- In the Inngest Cloud Dashboard:
- Copy your Event Key from Manage
$\rightarrow$ Keys$\rightarrow$ Event Keys. - Copy your Signing Key (
signkey-prod-...) from Manage$\rightarrow$ Keys$\rightarrow$ Signing Key.
- Copy your Event Key from Manage
- In
.env:INNGEST_DEV=0 INNGEST_BASE_URL=https://api.inngest.com INNGEST_EVENT_KEY=<your-inngest-cloud-event-key> INNGEST_SIGNING_KEY=signkey-prod-<your-inngest-cloud-signing-key>
- Run:
make start
-
make startdetectsINNGEST_DEV=0, skips/stops the localinngest-devcontainer, startspostgres,adminer,memgraph, andmemgraph-lab, and launches FastAPI. - On startup, FastAPI's
_lifespaninkb/main.pyautomatically establishes an outbound WebSocket connection (inngest.connect) directly to Inngest Cloud using yourINNGEST_SIGNING_KEY. -
No
ngrok, nocloudflared, and no manual URL syncing are needed: yoursubstack-brainapp and all 9 durable functions appear automatically under Workflow$\rightarrow$ Apps in Inngest Cloud.
-
When deploying to a cloud VM (EC2, DigitalOcean, Hetzner, Railway, etc.) where FastAPI itself runs inside Docker:
docker compose -f infra/docker-compose.prod.yml --env-file .env up -d --build
Then sync https://<your-domain>/api/inngest in the Inngest Cloud dashboard.
Inngest registers all 9 durable functions (backfill-publication, ingest-article, extract-claims, poll-feeds, handle-function-failed, evaluate-answer, run-eval-suite, run-research-agent, and generate-weekly-digest) along with their concurrency limits, throttles, priorities, and cron schedules (poll-feeds every 5 minutes; generate-weekly-digest every Monday at 08:00 UTC).
Unit tests verify bounded_loop iteration and USD caps, multi-hop candidate deduplication (merge_hop_candidates), query planner / critic / synthesizer schemas and fallbacks, Inngest function triggers (run-research-agent, generate-weekly-digest), and the 13 MCP tools—with zero Docker containers or API keys required:
uv run python -m pytest tests/unit/test_research_agent.py tests/test_week6.py
Run the full lint, typecheck, and test suite across Weeks 1–6:
make check