Documentation · English and Portuguese · Open source
Language: English

All docs Architecture

Project

Herald — Architecture

Herald builds an AI-curated morning briefing from hundreds of sources: Brazil first, with full US and global coverage. It runs once a day (cron, Docker or GitHub Actions), writes a Markdown briefing in pt-BR and English (or any of output.languages: pt-BR, en, es, fr, it, de), and delivers it through pluggable notifiers.

Design goals, in order:

  1. Cost scales with stories, not with items. Most of the work is done without an LLM. Only a few hundred candidates reach a cheap model, and only the final ~30 stories reach a strong model.
  2. Smallest design that works. Plain functions over a list of items, one protocol per extension point (source, AI provider, notifier, calendar), no framework.
  3. Inspectable. Every stage is a pure-ish function whose output can be persisted, replayed and exposed over MCP.
  4. Honest with sources. No paywall bypassing, robots.txt respected, per-host rate limits, descriptive User-Agent.

1. Pipeline

           sources/*.yaml + config.json
                        │
   ┌────────────────────▼─────────────────────┐
   │ 1. fetch      plugins → Item[]           │  network, no LLM
   │ 2. normalize  canonical URL, lang, wire  │
   │ 3. seen       drop items already shown   │  SQLite history
   │ 4. prefilter  rules + embeddings + caps  │  no LLM
   │ 5. cluster    same story → one Story     │  embeddings / lexical
   │ 6. score      batched LLM, per profile   │  cheap model
   │ 7. select     thresholds + caps          │
   │ 8. enrich     headline/summary/why, x2   │  strong model, 1 call/story
   │ 9. render     Markdown pt-BR + en        │  + upcoming calendar
   │10. deliver    notifiers, static site     │
   │11. record     history + run report       │
   └──────────────────────────────────────────┘

Clustering runs before LLM scoring so that a story covered by twelve outlets is scored once. Wire-copy collapse (syndication) is part of clustering.

Each stage has the signature stage(ctx: RunContext, items) -> items and appends its counters to ctx.stats. RunContext carries config, profiles, the HTTP client, the AI clients, the store and the time window. pipeline.run() is a straight sequence of calls; there is no DAG engine. Each stage logs its start and end with counts and duration, and the long ones (fetch, embedding, scoring, enrichment) log progress at least every 30 s (progress.py), so a run is never silent for long.

1.1 Time window

  • since = now - hours, default 24, CLI --hours overrides config.
  • All timestamps stored in UTC; rendering and "business day" logic use America/Sao_Paulo.
  • Optional schedule.skip_non_business_days: exit early (status skipped) on B3/ANBIMA holidays and weekends. Holiday calendar from the holidays package financial calendar for B3 when available, otherwise a shipped static list. Verified: holidays.financial_holidays("BVMF") covers B3.

1.2 Fetch

  • All source plugins share one httpx.AsyncClient wrapped by herald.http.Fetcher:
    • descriptive User-Agent: Herald/<version> (+https://github.com/felipebossolani/herald);
    • robots.txt check per host (cached per run, urllib.robotparser);
    • per-host concurrency 2 and minimum interval (default 1 s, configurable);
    • at most rate_limit.max_concurrency sources (default 64) fetched at once. The connection pool has the same size, so no request waits in it. A source's timeout starts once it has a slot;
    • retries with jittered backoff on 429/5xx, honoring Retry-After.
  • Calendars and notifiers use a second Fetcher (ctx.http) with its own client and pool. A heavy fetch can't starve the Upcoming section or delivery.
  • Sources whose robots.txt or server refuses automated access are marked blocked in the catalog and skipped. Official APIs (Reddit OAuth, SEC, FRED) are used through their sanctioned endpoints with the identification they require.
  • A source failure never fails the run; it is recorded in the fetch report. Sources whose credentials are not configured are reported as skipped. The run fails only when every attempted source fails.
  • Full-text extraction (trafilatura) only for non-paywalled sources and only for items that survive the pre-filter (lazy). Paywalled sources keep headline + lede + metadata from the feed, nothing more.

1.3 Normalize

  • Canonical URL: lowercase host, strip tracking params (utm_*, gclid, fbclid, xtor, cmpid, ...), strip AMP variants, resolve Google News redirect URLs, drop fragments.
  • Item id = sha1(canonical_url); exact duplicates merged here.
  • Language detection by source default, overridden by feed language field.
  • Wire detection (see §5.2) sets item.wire.

1.4 Seen filter

Drops items whose canonical URL was already published in a digest within history.repeat_window_days (default 3). Near-duplicate suppression of stories (same event, new URL) happens after clustering by comparing the cluster centroid against recently published stories (§1.6).

1.5 Pre-filter (no LLM)

Goal: cut ~3–5k raw items to a few hundred candidates.

For each item, in order:

  1. Recency: outside the window → drop. A URL whose path carries a date (/2023/06/16/) more than 2 days before the feed's date counts from the URL's date, because feeds re-date updated or recycled pages (Valor re-dates a 2023 live-blog permalink every day). Reader polls and quizzes → drop: a title that opens by asking the reader's opinion and ends in "?" (Para você, …?, In your opinion, …?, Selon vous, …?, Was meinen Sie …?, and the like in Spanish and Italian), a Quiz: title or a /quiz/ path. Words such as "poll", "Umfrage" or "sondage" do not count, since they also head reporting on opinion surveys.
  2. Routing → candidate profiles (§3.2).
  3. Hard rules per profile (from profile front matter):
    • exclude keywords/regex → drop for that profile;
    • require_any keywords (optional) → must match at least one.
  4. Watchlist boost: item mentions a watchlist ticker/company/person/keyword → must_keep = true (bypasses steps 5–6, still scored by LLM).
  5. Relevance score r ∈ [0,1] per candidate profile: r = w_emb · cos(item, profile) + w_kw · keyword_hits + w_tier · tier_bonus, where cos is embedding similarity between the item (title + lede) and the profile description. Items below prefilter.min_relevance (per profile) drop. Keyword lists are written in a few languages, declared per profile in keyword_languages (default [en, pt]; the Latin America profiles add es). For an item in any other language a keyword miss is not evidence: with embeddings the keyword term becomes max(keyword_hits, cos), so a German or Polish story is ranked by meaning, like its English version.
  6. Per-source caps: keep the top caps.max_items per source by r (tier defaults: t1 = 30, t2 = 10, t3 = 5).
  7. Global cap: keep at most prefilter.max_candidates (default 400) by r, stratified per profile so no profile starves.

Embeddings: fastembed with a small multilingual model (paraphrase-multilingual-MiniLM-L12-v2, CPU, ~235 MB download, 50+ languages) by default, or an OpenAI-compatible /embeddings endpoint. If embeddings are disabled the pre-filter falls back to keyword + tier only; then an item in a language its profile's keywords do not cover only passes on a fixed route or a keyword that survives translation (names, tickers, acronyms). Profile description embeddings are computed once per run. Embedding every item is most of a no-AI run's CPU time. ONNX Runtime gets as many threads as the process may use CPUs (its affinity, or a container's cgroup CPU quota) instead of one per host core: more threads than CPUs wait on each other and run several times slower. A limit on a parent cgroup (Docker inside a container, many LXC/OpenVZ VPSes) is invisible, so with no quota in sight it takes at most 4: on a 12-core host that is within a quarter of the best time with every CPU free, and 1.3x the best instead of 4x under a hidden 2-CPU limit. embeddings.threads sets the number, and the embeddings: loading log line says how many and why. Texts go in batches of 8 of similar length, and a text shared by several items is embedded once. About 40 items a second on 2 vCPUs, ~0.8 GB peak memory (the tokenizer and the model take ~650 MB of it).

1.6 Cluster

  1. Exact: same canonical URL (already merged).
  2. Near-duplicate: greedy single-pass clustering over candidates sorted by relevance; join a cluster when cosine(title+lede) ≥ cluster.threshold (default 0.86) and published within 36 h of each other. Without embeddings: Jaccard over normalized title shingles ≥ 0.6 (stop words for pt, en, es, fr, it, de, nl, pl and sv are ignored). Across languages the multilingual model scores a story and its translation lower than two same-language copies, so items whose lang differs join at cluster.threshold − 0.08 when their headlines also share at least two anchors (names, acronyms, numbers: "Lagarde", "2"). Looser cross-language pairs are merged by the LLM in §1.8.
  3. Wire collapse: items with the same wire and near-identical title join the same cluster regardless of outlet (§5.2).
  4. Representative ("best source"): canonical original (wire's own outlet or the outlet that broke it) > lower tier number > not paywalled > has full text > earliest. Other members become "also covered by".
  5. Cross-day repeat: if the cluster centroid matches a story published in the last history.repeat_window_days (cosine ≥ 0.9), drop unless a member is marked must_keep (watchlist).

Different angles of the same event that stay in separate clusters are handled at selection time by a diversity check (§1.8).

1.7 Score (LLM, cheap model)

  • Input: one row per cluster representative: id, title, source, outlet count, lede (≤ 400 chars), published time, watchlist hits.
  • Batches grouped by profile, scoring.batch_size (default 25). The system prompt is the profile's Markdown (relevance, ignore, rubric) + a fixed output contract: [{"id", "score": 0-10, "reason": "<= 20 words"}]. The profile part of the prompt is identical across batches, which makes provider prompt caching effective.
  • Items routed to two candidate profiles (ambiguous auto-match) are scored in both; the higher score wins and fixes the item's profile.
  • Robustness: JSON-schema / JSON mode when the provider supports it; one repair re-prompt on invalid output; missing ids in the reply are retried once in a smaller batch; then fall back to score = null (dropped unless must_keep).
  • Scoring results are cached in SQLite by (cluster_rep_id, profile, prompt_hash) so re-runs within the day cost nothing.
  • Items may be in any language; the prompt tells the model to judge what an item reports, never its language, and each row carries its lang. Entries are always written in output.languages (§1.9).
  • A fixed rule caps items with no concrete fact at 3 (question headlines, newsletter teasers, claims with no actor, decision, number or date), whatever their topical relevance.
  • If every scoring call fails (expired sign-in, no credit), the run fails instead of producing an empty briefing; the same holds when enrichment fails for every selected story.

1.8 Select

  1. Drop clusters below the profile threshold (except must_keep with score ≥ 4).
  2. Sort by score, tie-break by outlet count then tier.
  3. Merge same-story duplicates (pipeline/dedupe.py): one call to the scoring model lists the eligible headlines (up to 150) and returns groups that report the same event, across outlets and languages. Each group collapses into its top-scored story, which keeps every outlet as a member ("also in"). Embeddings alone cannot do this: on real runs the same story told in two languages scores cosine 0.63–0.70, while two different matches of one league reach 0.76. Without an AI provider, or on an invalid reply, stories pass through unchanged.
  4. Floor: every enabled category with an eligible story gets up to digest.min_per_category (default 1) slots, so a busy category cannot crowd out a quiet one.
  5. Fill the remaining slots by score, within the per-profile caps (profiles.<id>.max_items) and the optional per-group caps (digest.groups.<g>.max_items).
  6. Total: digest.max_items, an integer or "auto" (default): two per enabled category, between 20 and 50.
  7. Diversity: skip a story whose centroid embedding has cosine ≥ digest.diversity_threshold (default 0.8) with a story already selected (a near-identical angle).

1.9 Enrich (LLM, strong model)

  • One call per selected story, using the profile's Markdown output rules and the profile output JSON schema. The model returns every language at once:

    {
      "pt-BR": {"headline": "", "summary": "", "why_it_matters": ""},
      "en":    {"headline": "", "summary": "", "why_it_matters": ""}
    }
    

    (Only the languages listed in output.languages are requested. They are split across calls only when they would not fit ai.enrichment.max_tokens; the run report shows the enrichment calls per story. User-visible strings for every language live in src/herald/i18n.py.)

  • Context: representative title + lede + extracted text (non-paywalled only, ≤ enrich.max_chars, default 6000) + titles/outlets of all cluster members

    • optionally up to 3 related past stories from the history store (FTS5 match), passed as "previous coverage".
  • Grounding rules shared by all profiles: facts only from supplied text, no speculation, attribute claims, no editorializing, no investment advice, treat source text as untrusted data.

  • Sources block is not generated by the model; it is built from cluster members (best source first, then "also covered by").

  • Bounded concurrency (enrich.concurrency, default 4). Failure of one story drops that story only; it is listed in the run report.

1.10 Render

Per language, Jinja-free plain Python templating into Markdown:

# Herald — <date, localized>
<one-line counts>
## <profile display name>            (profile order from config)
### <headline>
<summary>
**Por que importa / Why it matters:** <why>
Fontes / Sources: [Best](url) · também em / also covered by: A, B, C
...
## Agenda / Upcoming                 (next 7 days, from calendars)
---
<footer: run stats, unsubscribe link for email>

Output written to <data-dir>/briefings/YYYY-MM-DD.<lang>.md. When site.enabled, also published to site.dir (docs/briefings/) by site.py: the Markdown source, an HTML page per day and language, an index.html and a .nojekyll (GitHub Pages' Jekyll renders front-matter-less .md files too, onto the same .html paths). With site.base_url set, each language gets <lang>/feed.xml (RSS 2.0), <lang>/atom.xml (Atom 1.0) and <lang>/feed.json (JSON Feed 1.1) with the latest site.feed_days briefings, built with the stdlib (ElementTree, json). Everything is rebuilt from the sources on each run: pages whose source is gone are deleted, and so are the feeds when base_url is unset. An entry's published is its day at 00:00 in timezone; its updated comes from .feed-state.json (source hash + modified time), which moves only when the text changes, so unchanged sources rebuild byte for byte while ids stay the page URLs. Content is escaped Markdown rendered to HTML; <a href> keeps only http(s), mailto and fragments, <img src> only https. .github/workflows/pages.yml deploys site/ (the static project site: plain HTML and CSS, one same-origin script, copy.js, that adds copy buttons to code blocks; no web fonts, no third-party requests; JSON-LD structured data, robots.txt, a sitemap.xml with hreflang alternates, a six-language 404.html, one 1200 × 630 Open Graph card per page and language in og/, made by scripts/og-cards.sh, and the reference docs under site/docs/ with their Brazilian Portuguese translation under site/pt/docs/, rendered from docs/**/*.md by scripts/build_docs.py and committed), docs/brand as brand/ and docs/briefings as briefings/ to GitHub Pages. After a deploy it notifies the IndexNow engines (Bing, Yandex, Seznam, Naver...) of the changed pages: scripts/indexnow.py maps the push's changed site/**/index.html to URLs, or takes every sitemap.xml URL when a shared file (stylesheet, script, image, sitemap) changed or on a manual run, and the job sends them to api.indexnow.org once the key file is live. The key is the INDEXNOW_KEY repository variable, public by design (served at /<key>.txt, written into the artifact, never committed); without it the ping is skipped. Briefing-only deploys and deploys that change no page send nothing, and a failed ping only logs a warning.

1.11 Deliver and record

  • Each enabled notifier receives the rendered briefing per language; a notifier failure is logged and reported, not fatal.
  • Published stories go to the history store (powers repeat suppression, "previous coverage" and MCP history search).
  • A failed run sends a short operator alert (error, report path, secrets redacted) to the enabled chat and push notifiers (telegram, slack, discord, matrix, ntfy, pushover, teams, google_chat; push at alert_priority) and a run.failed event to each webhook whose events include it. Email and WhatsApp only with "alerts": true. A WhatsApp alert is a text message (delivered only inside the 24-hour window) unless alert_template names an approved template whose two body variables are the date and the alert text.
  • WhatsApp (notify/whatsapp.py) uses only the official Cloud API (POST graph.facebook.com/<api_version>/<phone_number_id>/messages, Bearer token, redirects not followed). mode: template (default) sends an approved template with five body parameters (date, story count, top 3 headlines by score; whitespace collapsed, 180 chars max each) plus, with url_button: true and site.base_url, a URL button suffix <date>.<lang>.html. mode: text sends the full briefing in WhatsApp formatting, chunked under 4096 chars, and works only inside the recipient's 24-hour window. Recipients must be E.164. 429, 5xx, connect errors and Meta's transient codes (2, 4, 80007, 130429, 131000, 131016, 131056, 133004, even as HTTP 400) get up to 3 attempts (Retry-After capped at 30 s); timeouts after sending are not retried. Other errors map Meta codes to a readable detail with masked numbers.
  • Matrix (notify/matrix.py) uses the client-server API: PUT <homeserver>/_matrix/client/v3/rooms/{roomId}/send/m.room.message/{txnId}, Bearer token (https only, except plain http to localhost/private hosts: http.safe_for_token), redirects not followed. Each part is an m.text event with to_plain_text as body and to_html_fragment as formatted_body (org.matrix.custom.html); parts are chunked at story boundaries (12,000 chars, halved until the UTF-8 content is at most 32 KiB, half the 64 KiB event limit). The txnId is herald.<day>.<lang>.<part>.<sha256(text)[:16]>, so retries and same-text reruns are deduplicated by the homeserver; because of that, timeouts after sending are retried too. 429 (Retry-After, else retry_after_ms, capped at 30 s), 5xx and transport errors get up to 3 attempts; other errors map errcode to a readable detail.
  • Push (notify/push.py): ntfy and Pushover share one summary (localized title with the long date, story count, top 3 headlines by score, <site.base_url>/<date>.<lang>.html when set) and one POST helper (redirects not followed; connect errors and each channel's retryable statuses get up to 3 attempts; timeouts after sending are not retried; tokens, keys and the ntfy topic masked). ntfy posts JSON to the server root (default https://ntfy.sh, plain http only to localhost/private hosts via http.safe_for_token, optional Bearer token), message cut at 4096 bytes, priority 1-5; only 429 and 503 are retried (Retry-After honored), since after another 5xx the push may already be out. Pushover posts a form to api.pushover.net/1/messages.json (message 1024 / title 250 / url 512 / url_title 100 chars, priority capped at 1, 5xx retried at least 5 s apart, 429 = monthly quota, not retried).
  • Teams (notify/teams.py) posts {"type": "message", "attachments": [Adaptive Card 1.4]} to a Workflows webhook ("Post to a channel when a webhook request is received"); retired Office 365 connector hosts are refused. The Markdown becomes TextBlocks (headings styled with size/weight, since Teams renders no Markdown headings; links only http(s); {{ broken so it is not read as a card function). Whole sections are packed per card under 24 KB (Teams' limit is 28 KB) and cards are sent interval_s apart so parallel flow runs keep the order. Only connect errors and 429 are retried; 5xx and timeouts are not (no idempotency key).
  • Google Chat (notify/google_chat.py) posts cardsV2 to a space's incoming webhook: one card per #/## section (header = section name, one textParagraph per paragraph in Chat's HTML subset, only http(s) links), split past 100 widgets, packed up to 10 cards per message under 30,000 bytes (Chat's limit is 32,000). thread.threadKey = herald-<date> plus messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD keeps a day in one thread; messages are interval_s (1.1 s) apart for the 1 request/second/space quota. Only connect errors and 429 are retried (3 attempts, Retry-After); 5xx and timeouts are not, since webhooks are not documented to honor the requestId (derived from run, day, language and part) that is still sent. Query parameters are appended to the configured URL, never rebuilt, so key/token redaction keeps matching.
  • The webhook (notify/webhook.py) speaks a versioned contract, herald.event/v1 (docs/schemas/herald-event-v1.json): {spec, id, type, created_at, data} with a stable id per (day or run, type, language) for receiver-side dedupe. Auth is per target (HMAC signature, Standard Webhooks signature with the event id as webhook-id, bearer token, static headers; an unresolved ${VAR} blocks the send). Payloads can be reshaped with format or a template (only the fixed $name variables are replaced, JSON-escaped; the output must parse as JSON). max_body_bytes caps the body: over it, the briefing goes as markdown cut at a ## section boundary with a link to the full page, or is not sent. Redirects are never followed. Delivery retries 5xx/429/network errors 3 times with exponential backoff or Retry-After, never other 4xx. herald dev sink is a stdlib receiver that verifies and validates events for local end-to-end tests.
  • Chat bots (bot/): bot/commands.py is a platform-neutral core (command text in, Markdown reply out: /start double opt-in through a 24-hour pending record, /stop, /categories, /follow, /unfollow, /today, /lang, /help, /privacy, /export, /delete), so another chat channel only needs an adapter. bot/telegram.py (herald bot telegram) long-polls getUpdates with the offset persisted in the state table, passes on only bot commands from private chats, and stops on SIGINT/SIGTERM. Bad responses and a locked store (both SQLite files use WAL and a busy timeout, shared with the daily run) are logged and retried with backoff. Subscribers live in chat_subscribers (subscribers.db), keyed by (channel, chat_id), with language, followed categories and consent timestamps. The telegram notifier with "subscribers": true sends each active subscriber the briefing in their language with the sections of unfollowed categories dropped; alerts go to chat_id only. Sends are paced (20/s overall, 1/s per chat) and retry only 429 (retry_after) and connection failures, never a 5xx or read timeout that may already have delivered the message; a 403 (bot blocked) unsubscribes that chat. A failing chat_id does not stop the subscriber deliveries.
  • Preview (preview.py, herald notify preview): runs the selected notifiers unchanged on a stored briefing (data/briefings/<date>.<lang>.md plus the briefs stage of that day's latest run) or the bundled preview_sample.json. Their HTTP goes to a recording httpx.MockTransport that answers each vendor with a plausible success, and a notifier with a connect seam (email) gets a recording SMTP connection. While it runs, socket.connect, create_connection and getaddrinfo raise, so a notifier that builds its own client fails closed and is reported as failed. Subscribers come from an in-memory sqlite3 backup of the real files opened read-only (sample subscribers with --sample). The printed requests have credentials redacted (secret config values, /bot<token>/, Authorization, signature and token headers and query parameters) and phone numbers, chat ids and email addresses masked. A new notifier works without changes as long as it uses ctx.fetcher.client. herald notify send is the same function with live=True: a real client and SMTP connection, the network open, and only the outcome of each delivery printed (exit 1 when one fails). --sample then swaps only the briefing; subscribers always come from the read-only copy of the store, so a live send never mails a made-up address. It backs the local end-to-end harness (scripts/e2e-local.sh with docker-compose.e2e.yml: Mailpit, Conduit, ntfy and herald dev sink, one channel per config) and docs/release-checklist.md. The offline preview backs the contract sweep (tests/test_connector_contracts.py): every vendor channel previews a long six-language briefing and each recorded request is checked against the vendor contract in tests/contracts/.
  • Source health (health.py, herald sources health) reads per-source outcomes from the stored runs: dead = an error in each of the last 5 runs, flaky = some errors, silent = never any items. The run report adds a health line naming dead sources; --apply marks them dead in the catalog (pinned entries kept).
  • --dry-run: runs fetch → render, writes files, no delivery and no history write. Combined with scoring.provider = "none" it skips all LLM calls (pre-filter relevance becomes the score) for zero-cost smoke tests.

2. Module layout

herald/
├── pyproject.toml                 # uv, Python ≥ 3.12, entry points: herald, herald-mcp
├── config.example.json, .env.example
├── Dockerfile, compose.yaml, .github/workflows/{ci,daily}.yml
├── .gitleaks.toml, .pre-commit-config.yaml   # secret scanning: CI job, local hooks, test gate
├── profiles/
│   ├── _schema.json               # default enrichment output schema
│   └── <id>.md                    # front matter (rules) + prompt body; optional <id>.schema.json
├── sources/                       # catalog: one YAML file per group
│   ├── br-markets.yaml  br-fintech.yaml  br-tech.yaml  br-politics.yaml  br-official.yaml
│   ├── br-news.yaml     br-regional.yaml   # regional papers + state governments, TJs, TCEs
│   ├── latam.yaml                 # AR, MX, CL, CO, PE, UY papers, central banks, regional press
│   ├── latam-central.yaml         # more Mexico, Central America and the Caribbean
│   ├── europe-fr-it.yaml          # FR, BE, LU, CH, MC, IT, MT, SM, VA: local-language press + official
│   ├── latam-south.yaml           # rest of South America: VE, EC, BO, PY, GY, SR + more AR/CL/CO/PE/UY
│   ├── us-markets.yaml  us-fintech.yaml  us-policy.yaml  us-politics.yaml
│   ├── tech-ai.yaml     global.yaml      communities.yaml
│   ├── tech-regional.yaml         # Europe, LatAm, Canada, AU/NZ tech and startup press
│   ├── apac.yaml                  # Asia-Pacific: English-language editions + central banks
│   ├── oceania.yaml               # AU, NZ and Pacific islands: press, RBA, government releases
│   ├── mea.yaml                   # Middle East and Africa: news, energy, fintech + central banks
│   ├── europe-southeast.yaml      # Western Balkans, Greece, Cyprus: press + official feeds
│   ├── europe-iberia-uk.yaml      # ES, PT, AD, IE, GB national + regional press, official sources
│   ├── europe-central-east.yaml   # PL, CZ, SK, HU, RO, BG, SI, HR, UA, MD, BY (exile) press + central banks
│   ├── europe-nordic-baltic.yaml  # DK, SE, NO, FI, IS, EE, LV, LT: local + English press, official
│   ├── canada.yaml                # Canada: English and French news, Bank of Canada, StatCan, governments
│   └── topics.yaml                # science, health, climate/energy, culture, startups/VC
├── src/herald/
│   ├── cli.py                     # argparse: run, history, runs, sources, subscribers, bot, notify preview|send, dev sink
│   ├── config.py                  # pydantic models, ${VAR}, .env
│   ├── models.py                  # Item, Story, Brief, CalendarEvent, RunStats
│   ├── http.py                    # Fetcher: UA, robots, rate limit, retry
│   ├── extract.py                 # trafilatura full text (non-paywalled only)
│   ├── catalog.py                 # load + select sources/*.yaml
│   ├── validate.py                # feed discovery, freshness check, sources report
│   ├── profiles.py                # load profiles/*.md (+ schema)
│   ├── store.py                   # SQLite: runs, stages, history (FTS5), score cache, state, subscribers
│   ├── site.py                    # static site output
│   ├── mcp_server.py
│   ├── devsink.py                 # `herald dev sink`: local webhook receiver
│   ├── preview.py                 # `herald notify preview` (offline) and `send` (live): notifiers + preview_sample.json
│   ├── pipeline/
│   │   ├── run.py context.py      # RunContext + stage functions + run()
│   │   ├── fetch.py normalize.py prefilter.py cluster.py score.py select.py
│   │   └── enrich.py render.py report.py prompts.py
│   ├── text/                      # urls.py wire.py embed.py match.py
│   ├── ai/                        # base.py (LLM protocol, Meter) openai_compat.py anthropic.py gemini.py agent_cli.py
│   ├── sources/
│   │   ├── base.py                # Source base class + registry
│   │   ├── rss.py hackernews.py google_news.py community.py html_list.py
│   │   └── official/              # bcb.py (Focus, SGS, Copom, normativos)
│   │                              # brazil.py (IBGE, Câmara, Senado, CVM) us.py (SEC, FRED, FedReg, Congress)
│   ├── calendar/                  # business days + providers.py (Copom, Focus, IBGE, FOMC, BLS, BEA, central banks, ONS, StatCan, INE Spain, CZSO, INE Portugal, earnings)
│   ├── bot/                       # commands.py (platform-neutral core) telegram.py (long polling)
│   └── notify/                    # registry + telegram.py email.py (SMTP, Resend) email_html.py chat.py (Slack, Discord) teams.py google_chat.py webhook.py whatsapp.py matrix.py push.py markup.py
└── tests/                         # fixtures/<group>/... recorded or documented-format responses

Dependencies (each justified):

Package Why
httpx async HTTP with HTTP/2, timeouts
feedparser RSS/Atom parsing; handles broken feeds
trafilatura full-text extraction
selectolax (lexbor) fast CSS selectors for the HTML list scraper, GitHub Trending, FOMC calendar and feed autodiscovery
pydantic config + model validation
pyyaml sources/*.yaml, profile front matter
python-dotenv .env loading
openai, anthropic, google-genai provider SDKs (OpenAI SDK also covers Ollama/compatible)
fastembed (extra embed, default in Docker) local multilingual embeddings, ONNX, no torch
mcp MCP server
holidays BR/B3 and US business-day calendars
markdown (Step 6) HTML email body (email_html.py: branded table layout, inline styles, dark mode)
jsonschema herald dev sink validates webhook envelopes; already installed through mcp

Dev: pytest, pytest-asyncio, ruff. HTTP is faked with httpx.MockTransport replaying fixtures.


3. Interfaces

3.1 Source plugin

class Source(Protocol):
    type: ClassVar[str]                       # "rss", "hackernews", ...

    def __init__(self, spec: SourceSpec, fetcher: Fetcher, watchlists: Watchlists) -> None: ...
    async def fetch(self, since: datetime) -> list[Item]: ...

SOURCES: dict[str, type[Source]] = {}
def register(cls): SOURCES[cls.type] = cls; return cls
  • SourceSpec is one entry from sources/*.yaml (validated by pydantic); type-specific options live in spec.options and are validated by the plugin with its own small pydantic model.
  • Plugins raise on failure; the runner wraps each call, records ok | empty | error(msg) and latency per source in the fetch report.
  • Plugins return items with at least: title, url, published_at, lede (may be empty), author, and meta (engagement, comments count, etc.).

3.2 Routing

Per source, route is one of:

Value Meaning
"br-markets" fixed profile
["br-markets", "br-economy"] candidates: best by pre-filter relevance
"auto" candidates: all profiles

Resolution is cheap and deterministic: compute r for each candidate (§1.5) and keep the best; if the runner-up is within routing.ambiguity_margin (default 0.05) keep both and let the LLM score decide (§1.7). No separate classification call.

Categories. A category is a profile; its front matter category: holds the region (brazil, latam, us, europe, apac, oceania, mea, canada, global) or topics for subjects followed across regions (science, health, climate-energy, culture, startups-vc), whose sources mix Brazilian and global outlets. The categories a deployment follows are profiles.enabled in config.json, written by herald init and herald categories (onboarding.py, which edits the raw JSON so ${VAR} placeholders survive). Only enabled profiles are candidates. A source whose route names no enabled profile is not fetched; auto sources always are.

3.3 AI provider

@dataclass
class Usage:
    input_tokens: int; output_tokens: int; cached_input_tokens: int = 0

@dataclass
class Completion:
    text: str; usage: Usage; model: str

class LLM(Protocol):
    async def complete(self, system: str, user: str, *,
                       json_schema: dict | None = None,
                       max_tokens: int = 2048,
                       temperature: float = 0.2) -> Completion: ...
  • make_llm(ModelSettings) -> LLM picks the implementation by provider: openai (any base_url); openrouter, opencode and ollama (OpenAI-compatible with preset base URLs); anthropic; gemini; claude-code and codex (ai/agent_cli.py: the operator's signed-in CLI run as a subprocess, with tools disabled, in an empty temp dir, reporting zero marginal cost); none (stub for dry runs). A block without api_key reads the provider's environment variable; a block without model gets the provider default where one exists.
  • Two independent settings: ai.scoring (cheap) and ai.enrichment (strong). They may use different providers.
  • Every call reports Usage to ctx.stats.ai[stage]; cost = tokens × ai.pricing[model] (USD per 1M tokens, user-maintained table in config; unknown model → cost reported as null, tokens still reported).

3.4 Embedder

class Embedder(Protocol):
    def embed(self, texts: list[str]) -> np.ndarray: ...   # L2-normalized

Implementations: fastembed, openai (compatible /embeddings), none.

3.5 Notifier

class Notifier(Protocol):
    type: ClassVar[str]
    async def send(self, briefing: Briefing) -> DeliveryResult: ...

Briefing holds date, language, Markdown, and the structured stories (so a notifier can build native formatting, e.g. Telegram HTML chunks ≤ 4096 chars, Slack blocks). Each notifier entry in config has languages to pick which language(s) it receives.

3.6 Calendar provider

class CalendarProvider(Protocol):
    async def upcoming(self, start: date, days: int) -> list[CalendarEvent]: ...

CalendarEvent(date, time | None, tz, country, kind, title, source_url). Kinds: copom, fomc, rate_decision, ipca, ibge, focus, cpi, jobs, gdp, pce, retail, earnings. Rendered as the "Agenda / Upcoming" section, never scored.


4. Config

4.1 Files and precedence

  1. .env (loaded from CWD or --config dir; never committed).
  2. config.json (--config, default ./config.json); every string leaf supports ${VAR} and ${VAR:-default} interpolation; unresolved ${VAR} without default is a validation error only if the containing block is enabled.
  3. CLI flags override config: --hours, --data-dir, --log-level, --profile (repeatable; restrict the run to these profiles), --dry-run.

Secrets are only referenced, never stored in config.json.

4.2 Schema (abridged; full example in config.example.json)

{
  "timezone": "America/Sao_Paulo",
  "window_hours": 24,
  "schedule": { "skip_non_business_days": false, "market_calendar": "B3" },

  "sources": {
    "catalog": ["sources/*.yaml"],
    "max_tier": 2,
    "enable": [], "disable": [],
    "states": [],                # Brazilian UFs to follow; empty = every state
    "tier_caps": { "1": 30, "2": 10, "3": 5 },
    "rate_limit": { "per_host_interval_s": 1.0, "per_host_concurrency": 2, "max_concurrency": 64 },
    "user_agent": "Herald/0.1 (+https://github.com/felipebossolani/herald)"
  },

  "profiles": {
    "dir": "profiles",
    "enabled": ["br-markets", "br-economy", "global-tech-ai"],
    "overrides": { "br-markets": { "threshold": 6.5, "max_items": 6 } }
  },

  "watchlists": {
    "b3": ["ITUB4", "PETR4", "NU"],
    "us": ["NVDA", "MSFT"],
    "companies": ["Itaú Unibanco", "Nubank", "Stripe"],
    "people": ["Gabriel Galípolo", "Jerome Powell"],
    "keywords": ["Drex", "open finance", "stablecoin"],
    "filings": { "cvm": true, "sec_8k": true }
  },

  "prefilter": {
    "max_candidates": 400,
    "weights": { "embedding": 0.6, "keywords": 0.3, "tier": 0.1 }
  },
  "embeddings": { "provider": "fastembed", "model": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" },
  "cluster": { "threshold": 0.86, "lexical_threshold": 0.6, "max_gap_hours": 36 },
  "routing": { "ambiguity_margin": 0.05 },

  "ai": {
    "scoring":    { "provider": "openai", "model": "${HERALD_SCORING_MODEL}", "base_url": null, "api_key": "${OPENAI_API_KEY}", "batch_size": 25 },
    "enrichment": { "provider": "anthropic", "model": "${HERALD_ENRICH_MODEL}", "api_key": "${ANTHROPIC_API_KEY}", "concurrency": 4, "max_chars": 6000 },
    "pricing": { "<model-id>": { "input": 0.0, "output": 0.0, "cached_input": 0.0 } }
  },

  "digest": {
    "max_items": "auto",
    "min_per_category": 1,
    "section_order": ["br-markets", "br-economy", "br-politics"],
    "groups": { "brazil": { "profiles": ["br-markets", "br-economy"] } }
  },

  "output": { "languages": ["pt-BR", "en"], "primary": "pt-BR" },
  "history": { "repeat_window_days": 3, "retention_days": 365 },
  "calendars": { "enabled": ["copom", "focus", "ibge", "fomc", "bls", "bea", "earnings"], "days_ahead": 7 },

  "site": { "enabled": false, "dir": "docs/briefings", "base_url": null, "feed_days": 30 },
  "notifiers": [
    { "type": "telegram", "enabled": false, "languages": ["pt-BR"], "bot_token": "${TELEGRAM_BOT_TOKEN}", "chat_id": "${TELEGRAM_CHAT_ID}" },
    { "type": "email", "enabled": false, "languages": ["pt-BR"], "smtp_host": "${SMTP_HOST}", "smtp_port": 587, "username": "${SMTP_USER:-}", "password": "${SMTP_PASSWORD:-}", "from": "${SMTP_FROM}" }
  ]
}

4.3 Source catalog entry (sources/*.yaml)

- id: infomoney
  name: InfoMoney
  site: https://www.infomoney.com.br
  type: rss                      # plugin type
  feed_url: https://www.infomoney.com.br/feed/
  status: ok                     # ok | no_feed | dead | scrape_needed | blocked | unchecked
  tier: 1
  paywall: false
  lang: pt-BR
  country: BR
  state: null                    # Brazilian UF (e.g. RS) for regional and state-level sources
  route: [br-markets, br-economy]
  spectrum: null                 # politics only: left | center-left | center | center-right | right
  max_items: null                # overrides tier cap
  full_text: true                # ignored when paywall: true
  options: {}                    # plugin-specific (selectors, query, locale, ...)
  checked_at: 2026-11-29         # written by validate_sources

Selection: entry enabled iff status ∈ {ok, unchecked} and tier ≤ sources.max_tier (tier 3 off by default) and not in disable, or explicitly in enable. When sources.states is set, entries with a state outside it are skipped and entries with a followed state are selected whatever their tier; entries without state are unaffected.

4.4 Profile file (profiles/<id>.md)

---
id: br-markets
names: { pt-BR: "Mercados Brasil", en: "Brazil Markets" }
description: >            # embedded for pre-filter similarity and routing
  Brazilian equities, rates, FX, credit, IPOs, M&A, earnings of B3-listed ...
keywords: [Ibovespa, B3, DI futuro, Selic, debênture, IPO, follow-on]
exclude: [horóscopo, "BBB2\\d", futebol]
require_any: []
threshold: 6.0
max_items: 6
category: brazil
schema: _schema.json
---
# Relevant
...
# Ignore
...
# Scoring rubric (0–10)
...
# Output
...

Front matter drives the pre-filter and selection; the Markdown body is the prompt for both scoring (relevant / ignore / rubric sections) and enrichment (output section). The JSON schema constrains the enrichment response.


5. Brazil and US specifics

5.1 Politics balance

Politics sources carry a spectrum tag (an editorial label maintained in the catalog and documented in docs/sources-report.md). Clusters keep the spectrum of each member; enrichment receives the member list and is instructed to report only facts common to the coverage and to attribute contested claims. The run report shows the spectrum distribution of fetched and selected politics items so imbalance is visible.

5.2 Syndication

text/wire.py tags an item with wire ∈ {agencia-brasil, estadao-conteudo, folhapress, reuters, ap, bloomberg, afp, efe} using: author/byline field, credit lines in lede/text ("Com informações da Reuters", "(Estadão Conteúdo)", "Folhapress", "— Agência Brasil"), and rel=canonical pointing to a wire domain. Wire items with matching titles collapse into one cluster; the wire's own item is the representative when fetched, otherwise the earliest copy, and the brief credits the wire.

5.3 Official sources and calendars

  • Official data via APIs where available: BCB Olinda (Focus), BCB SGS, Copom statements and minutes, BCB normativos, IBGE releases, CVM dados abertos (fatos relevantes for watchlist companies), Câmara/Senado plenary votes, SEC EDGAR (8-K for watchlist tickers), FRED, Federal Register, Congress.gov. DOU is recorded as blocked (in.gov.br refuses automated clients; INLABS requires login).
  • Calendars: Copom meeting dates (configured; BCB has no public calendar API), FOMC dates (parsed from the Fed calendar page), IBGE release calendar API (IPCA, PIB, PNAD), Focus every Monday (computed, shifted on B3 holidays), BLS (CPI, payrolls, PPI, JOLTS) and BEA (GDP, PCE) via FRED release dates (bls.gov blocks automated clients), other central banks' rate decisions (configured per bank and linked to its official calendar page; none publishes a machine-readable schedule), UK CPI, GDP, labour market and retail sales from the ONS release calendar API, the same headline releases from Statistics Canada (key-indicators JSON), INE Spain, the CZSO and INE Portugal (official iCalendar feeds, read by a small built-in parser), earnings from configured manual entries (no free reliable API). Missing data is omitted, never guessed.

6. Data model

class Item(BaseModel):
    id: str                    # sha1(canonical_url)
    source_id: str
    source_type: str
    title: str
    url: str
    canonical_url: str
    published_at: datetime     # UTC
    author: str | None
    lede: str = ""             # feed summary, HTML stripped, ≤ 1000 chars
    text: str | None = None    # full text, non-paywalled only, lazy
    lang: str
    tier: int
    paywall: bool
    wire: str | None = None
    spectrum: str | None = None
    meta: dict[str, Any] = {}  # engagement, comments, tickers ...
    # filled by stages
    profiles: list[str] = []   # candidate profiles after routing
    relevance: dict[str, float] = {}
    must_keep: bool = False

class Story(BaseModel):        # a cluster
    id: str                    # id of representative
    primary: Item
    members: list[Item]        # includes primary
    profile: str | None
    score: float | None
    reason: str | None

class Brief(BaseModel):
    story_id: str
    profile: str
    text: dict[str, BriefText]          # lang -> headline/summary/why_it_matters
    sources: list[SourceRef]            # best first, then also covered by

class RunStats(BaseModel):
    run_id: str; started_at: datetime; window_hours: int
    funnel: dict[str, int]              # fetched, normalized, unseen, prefiltered, clusters, scored, selected, enriched
    sources: list[SourceOutcome]        # per source: status, items, latency, error
    ai: dict[str, StageUsage]           # scoring / enrichment / cluster_confirm
    cost_usd: float | None

6.1 SQLite schema (<data-dir>/herald.db)

runs(id TEXT PK, started_at, finished_at, status, window_hours, stats_json)
run_stages(run_id, stage, payload_json, PRIMARY KEY(run_id, stage))  -- MCP replay
published(story_id TEXT, run_id, date, profile, url, canonical_url,
          sources_json, score, embedding BLOB, published_at,
          texts_json,                       -- {lang: {headline, summary}}, every output language
          PRIMARY KEY(story_id, date))
published_fts USING fts5(headlines, summaries)  -- all languages of a row, same rowid
score_cache(item_id, profile, prompt_hash, score, reason, created_at,
            PRIMARY KEY(item_id, profile, prompt_hash))
subscribers(email PK, status, language, created_at, consent_at, consent_source, token,
            unsubscribed_at, bounced_at)   -- status: pending | active | unsubscribed | bounced

A database written before per-language history (four columns headline_pt, headline_en, summary_pt, summary_en) is migrated in place the first time it is opened, in one transaction: the text moves into texts_json under pt-BR and en, and the index is rebuilt, so old stories stay searchable.

Retention: published kept history.retention_days; run_stages kept 7 days; score_cache 3 days; pending subscribers 7 days, unsubscribed and bounced records 30 days (docs/privacy.md). Pruned at the end of each run.


7. MCP server

herald-mcp (official mcp SDK) serves stdio by default, or streamable HTTP with --http (/mcp, bound to 127.0.0.1:8765 by default). HTTP refuses to start without HERALD_MCP_TOKEN and checks Authorization: Bearer on every request in a small ASGI guard (constant-time compare).

Bot tools read the rendered files and the config; they never run the pipeline:

Tool Purpose
herald_briefing(date?, language, category?) latest (or dated) data/briefings/<date>.<lang>.md, whole or one ## section
herald_categories(language) every profile, region, followed flag
herald_follow(categories) / herald_unfollow(categories) edit profiles.enabled (same code as herald categories)

Each stage tool takes a run_id, reads the previous stage from run_stages, writes its own, so an agent can re-run a single stage with different parameters.

Tool Purpose
herald_fetch(hours, sources?, profiles?) new run, returns run_id + fetch report
herald_prefilter(run_id, max_candidates?) funnel counts + sample
herald_cluster(run_id) clusters with members
herald_score(run_id, profiles?) score distribution
herald_select(run_id, max_items?, thresholds?) selected stories
herald_enrich(run_id) briefs
herald_render(run_id, language) Markdown
herald_run(hours, dry_run) full pipeline
herald_get_run(run_id, stage?) inspect stored stage / stats
herald_history_search(query, days=30, profile?) FTS5 over published stories

8. Cost model

Variables per run: N raw items, C candidates after pre-filter, K clusters, B scoring batch size, S selected stories, P profile prompt tokens, L languages.

Stage Calls Input tokens Output tokens
Pre-filter / cluster 0 LLM – –
Scoring ⌈K/B⌉ (+ per-profile split) K·t_row + ⌈K/B⌉·P K·t_score
Enrichment S S·(P + t_ctx) S·L·t_brief

Typical daily run at full catalog (~300 sources):

Value
N raw items 3,000–5,000
C after pre-filter ≤ 400
K clusters ~250–300
Scoring ~12–15 calls, ~70k in / ~12k out
S enriched 30
Enrichment 30 calls, ~120k in / ~25k out (pt-BR + en)

The scoring stage therefore costs about the same as enriching a handful of stories, and the total is dominated by the strong model on ~30 stories. The run report prints, per stage: calls, input/cached/output tokens, and estimated USD from ai.pricing. Exact prices are not hard-coded; the user keeps the pricing table current.

Levers if cost needs to drop: lower prefilter.max_candidates, raise scoring.batch_size, lower digest.max_items, use a single output language, or route enrichment to a local Ollama model.

Run report example

Herald run 2026-11-30T09:00-03:00  window=24h  status=ok
funnel  fetched 4,112 → unseen 3,870 → prefiltered 392 → clusters 268 → scored 268 → selected 30 → enriched 30
sources 287 ok · 6 empty · 4 error (see report)
ai      scoring    gpt-x-mini   12 calls  71,204 in (48,000 cached) / 11,890 out  $0.02
        enrichment claude-x     30 calls 118,330 in / 24,770 out                   $0.73
total   $0.75

9. Testing

  • Every plugin has fixtures under tests/fixtures/<group>/ replayed through httpx.MockTransport; CI never touches the network. Fixtures are recorded from live endpoints where access allows, otherwise hand-built from the documented response format (noted in each test module).
  • LLM stages tested with a FakeLLM that returns canned JSON keyed by prompt content; pipeline integration test runs fetch → render on fixtures.
  • Pure functions (canonical URL, wire detection, clustering, caps, rendering) have unit tests named as specifications.

10. Out of scope for v1

Unofficial WhatsApp clients (only the official Cloud API is supported), X/Twitter, paid data APIs, web UI, multi-tenant subscriptions beyond the opt-in email list.