Discovery Agent — Technical Reference
Turns a raw scraped row into a decision-ready feed item.
Audience: engineers. Non-technical version: overview.md. Back to the agents index.
What it does
Two distinct jobs sit under "discovery":
- Finding — deciding what URLs to pull in at all (search-first query generation, provider selection, article-shape filtering).
- Enriching — reading each item that landed and writing the fields a human actually browses on: a clean summary, a category, a state, SEO keywords, and three scores with reasons.
Job 2 is the agent proper — it is the only part that runs an LLM per item, on a worker, unattended.
Where it lives
| Concern | File |
|---|---|
| Enrichment worker loop | apps/backend/src/jobs/feed-enrichment-worker.ts |
| Enrichment implementation | apps/backend/src/modules/news/feed.ts → enrichFeedItem() |
| Claim / fail / status | apps/backend/src/modules/news/feed.ts → claimNextFeedItem(), failFeedItem() |
| Enrichment prompt | apps/backend/src/ai/agents/discovery/prompt/enrich.ts |
| Scoring model | apps/backend/src/modules/news/services/scoring-model.ts |
| Search-first query building | apps/backend/src/modules/news/services/search-discovery.ts |
| Provider orchestration | apps/backend/src/modules/news/services/discovery.ts |
| Article-URL gate + canonicalization | apps/backend/src/modules/news/services/utils.ts → isArticleShapedUrl(), canonicalizeArticleUrl() |
| Source profiling worker | apps/backend/src/jobs/source-profile-worker.ts |
| Boot hook | apps/backend/src/worker.ts |
| UI | apps/admin-app/src/components/modules/discovery-feed-module.tsx |
| Routes | apps/backend/src/modules/news/routes.ts (/api/tenants/:tenantId/feed/** and news/**) |
Trigger
Automatic. No button.
- An in-process worker polls every
FEED_ENRICHMENT_WORKER_POLL_MS(default 2000 ms), started by the backend worker process (apps/backend/src/worker.ts) at boot. - It walks configured tenants, atomically claims one
pendingitem, enriches it, and moves on.inFlightguards the claim, not just the enrichment — claiming first would strand items inprocessingon every tick. - Stale
processingitems are swept back after 5 minutes;maxAttemptsis 3. - Kill it process-wide with
FEED_ENRICHMENT_WORKER_DISABLED=1.
A separate daily morning sweep (Coolify cron → /api/internal/news-fetch)
queues the fetch runs that produce the pending rows in the first place.
Two more things happen at ingest, before enrichment ever sees a row:
- Canonical-URL dedupe. Rows upsert on
{tenantId, canonicalUrl}— host case,www., fragments, tracking params and trailing slashes are normalised bycanonicalizeArticleUrl(), so a utm-tagged variant of a held article can no longer insert a duplicate Discovery row. - PDF / unreadable flagging. PDF links and rows whose title or summary is
raw page markup are flagged as unscraped documents
(
unscrapedDocReason: "pdf" | "unreadable") and can be hidden from the feed server-side, rather than surfacing as junk cards.
And upstream of the crawl itself, the Source Profiler
(jobs/source-profile-worker.ts — part of the Learning
Agent) maintains verified scrape rules per
source: a ready profile's feed URL skips autodiscovery, its URL patterns
override the generic link gate, and its selector leads extraction. Every rule
was tested against real pages before it may steer anything.
Per-tenant mode
source_config.feed_enrichment_mode in news settings:
| Mode | Behaviour |
|---|---|
full | Default. LLM writes the summary plus everything else |
no_summary | LLM call still runs; feedSummary stays the deterministic excerpt |
off | No LLM at all — deterministic authority, keywords and persona only |
Input
Per item: title, summary, first 5 000 characters of fullContent,
source, current_category.
Per tenant, loaded alongside: news source record (priority + weight), audience personas, news settings, enabled source domains, tenant categories, brand guidelines, compliance rules, compliance intelligence rulebook.
Output
Written back onto the feed doc; enrichmentStatus flips pending → processing → ready (or failed). The enrichment version is pinned as feed-v9 (prompt
discovery-v9); bumping either re-enriches every stored item.
| Field | Source |
|---|---|
feedSummary | LLM — 2 plain-text sentences, no markdown/links/boilerplate |
category | LLM, constrained to the tenant allow-list — invented labels are rejected and the crawl-time fallback is kept |
geoState | LLM — one Indian state/UT, National, or Global for foreign stories with no India angle; drives the Region facet |
seoKeywords | LLM — 5–10 phrases |
| relevance band | LLM picks a rubric band (A–E); the number inside the band is held deterministically |
| evidence inventory | LLM counts quotes, attributed figures, named sources, primary documents, wire/press-release markers — regex-inferred when enrichment is off |
brand_fit band + guideline_ids | LLM, citations validated against the stored rulebook |
| authority inputs | Deterministic — domain-tier prior, document signals captured at extraction, source priority, reviewer history |
| persona matches | Deterministic — matched from text, never model-guessed |
The deterministic/LLM split is deliberate: an article never states its reader's age or profession, so personas are matched, not inferred. Authority is a property of the source, not the text, so it is computed.
One composite: feedRank
Every displayed score is computed in
modules/news/services/scoring-model.ts from counted evidence — never
from a bare model number or a boolean lookup (a lookup could only produce ~8
values, which is how every item once scored 84 / 40 / 78):
feedRank = ( relevance × 0.35 bands blended 70/30 with term coverage
+ brandFit × 0.25 counted voice matches / avoid hits + rulebook delta
+ authority × 0.20 domain tier + doc signals + priority ± reviewer history
+ authenticity × 0.20 ) evidence inventory, not a vibe
× complianceGate blocked findings halve or zero it
× relevanceGate band E halves the composite; band D trims it
Scores keep two decimals — Math.round on the composite is what used to
manufacture ties — and feedRank is the one composite: Discovery "Best", the
Daily Studio and the News page all rank on it. Freshness is a read-time
multiplier (undated items count as 7 days old), so nothing is re-scored as it
ages. The "Best" sort also annotates each card with rank_top_percent
("Top 8%") arithmetically inside the keyset cursor.
Weights change on evidence, not taste: GET .../news/score-calibration
reports, per component, the mean for approved vs disapproved items and an
AUC-style separation.
Model & prompt
- OpenAI only — the agent (
ai/agents/discovery/agent.ts,runDiscoveryAgent) goes through the kernel'sinvokeText, but never the provider chain: Discovery must not silently fall through to Gemini or an NVIDIA-hosted model. - Prompts live in
ai/agents/discovery/prompt/—enrich.ts(discovery-v9) andsearch-query.ts(search-query-v2). v9 of the enrichment prompt adds asource_profilecontext line: what the Source Profiler learned about the publishing source; the search-query prompt gets the same profiles assourceNotes. - JSON mode, single call per item.
- Usage metered as feature
feed_enrichment, operationarticle_metadata, with the news item id attached so the spend attributes to the piece. - Query generation (
generateSearchQueries) uses a second, smaller OpenAI call capped at 700 output tokens (featurenews).
Failure mode
Fails open, never blocks the feed.
- LLM unavailable or
offmode → item still becomesreadywith deterministic authority, keywords and personas. It just has a rougher summary. - Query generation fails → falls back to
deterministicQueries()at the configured count, with a warning. (It used to collapse to a single query, which silently cut a tenant's discovered-URL volume to one query's worth.) - No discovery provider key →
getDiscoveryProviderStatus()returnsavailable: falsewith a message naming the missing env var. - Enrichment throws →
failFeedItem(), retried up to 3 times.
Known gaps
- The feedback loop is partial, no longer absent. Two Learning Agent sub-agents now close pieces of it: the Source Profiler learns verified scrape rules per source (and its usage feeds the enrichment and search-query prompts), and reviewer rejections — reason compulsory — land in a durable event log the compliance-feedback agent aggregates into pattern reports. Reviewer history also nudges the authority score. What is still open: nothing yet reweights the feed from what a team queues and publishes.
- Relevance is not personalised per reviewer, only per tenant.
- One item at a time. Serial worker, ~2 s poll — a large morning sweep drains slowly. No batching, no concurrency.
- 5 000-char content budget. A restricted claim that appears only deep in a long article is not seen.
- Competitor reel topics live in
ops_ca_*and are deliberately not merged into the feed — they are read-only and never selectable for generation, because reels do not pass the compliance scan every news item gets.