Skip to content

Adding a Signal Source

Claude edited this page Nov 12, 2026 · 4 revisions

Checked against v0.7.6 on November 13, 2026.

Adding a signal source

A signal source feeds the consulting track. Where a job board adapter returns postings, a signal source returns public facts about organizations (a filing, a news item, a portfolio listing) or ready-made consulting postings such as a government RFP. This page explains the contract, what the runner does with the output, and the files you touch to add a new one. For employment sources, see Adding a job board adapter.

Four signal sources ship: sec_edgar, sam_gov, rss and pe_portfolio. All four live in kestrel/ingest/signal_sources/. The Sources page and the Help page list them from the live registry (kestrel/ingest/catalog.py), and docs/SOURCES.md has the user-facing table.

Two hard rules from CLAUDE.md apply directly.

  • Public data only, politely. Public filings and public pages, a descriptive User-Agent, a rate limit per host, robots.txt checked before any web page is read, nothing behind a login.
  • Kestrel never acts for you. A signal source reads. A trigger opportunity is created with url=None because there is nothing to apply to, and nothing in this path sends a message or contacts anyone. Any address a person types into the source's config (an RSS feed, a firm's portfolio page) is fetched with public_only=True, which refuses a link that points at this computer or a private network.

The contract

The protocol is in kestrel/ingest/signal_base.py:

@runtime_checkable
class SignalSource(Protocol):
    kind: str
    def validate_config(self, config: dict) -> None: ...
    async def fetch(self, config: dict, client: Any) -> list[RawSignal]: ...

validate_config is pure and structural. It raises SourceConfigError and never touches the network. fetch does the I/O through the shared HttpClient (kestrel/ingest/http.py) and returns RawSignal objects. Like a job board adapter, a signal source never reads or writes the database.

RawSignal has one field that decides everything else, signal_kind:

signal_kind Meaning What the runner does
"trigger" (default) A public fact worth classifying Runs the P10 trigger_classify prompt, records the result on the organization, and promotes it to an opportunity under the rules below
"posting" A ready consulting opportunity Builds a RawPosting and calls normalize_and_store, the same path job board adapters use. No model is involved

The fields you will use most:

Field Notes
org_name May be None. P10 extracts the organization from the text, which the RSS source relies on
source_url The public page or filing
external_id Makes re-observation idempotent. Use something stable, such as an EDGAR accession:filename or firm:company
text For triggers, the excerpt P10 classifies. For postings, the description
published_date ISO string
title, form, item Display and metadata. form and item are EDGAR-style (8-K, 5.02)
location_raw, comp_*, naics Posting-only extras
raw Original payload. A PE portfolio source sets raw={"firm": ...}, and the classifier carries that onto the organization's signal record

Fill what the payload provides and leave the rest None. Never guess a date or a company name.

What the runner does

run_signal_source() in kestrel/ingest/signal_runner.py handles one source per call.

  1. It creates a scrape_run, looks up the source with get_signal_source(kind), calls validate_config, then fetch.
  2. SourceConfigError disables the source (enabled = False), adds a source_disabled notification and ends the run partial. This is the path a missing SAM.gov key takes.
  3. AdapterError or any other exception adds one to consecutive_failures. Three in a row disable the source with a notification.
  4. Each signal is processed and committed on its own. One bad signal rolls back and increments an error count, not the whole run. A posting signal goes straight to normalize_and_store. The area and title drop that run_source applies to job board postings before storage (see Filter rules) does not run here, so a consulting posting is judged only by Tier 0.
  5. If fetch returns a list with a fetch_errors attribute, the runner records those and marks the run partial. SignalBatch in kestrel/ingest/signal_sources/sam_gov.py is a list subclass that carries it. Use it when some of your queries can fail while others succeed.
  6. A run that processed nothing but hit errors or quarantines counts as a failure, so a prompt that quarantines everything trips the auto-disable instead of looking healthy. An empty success resets the counter.

How triggers become opportunities

classify_and_store() in kestrel/ingest/triggers.py is the part that makes this track different. For each trigger signal:

  1. The text goes through P10 (kestrel/llm/prompts/trigger_classify.v1.md) under the usual structured-output rules: schema-validated, one repair attempt, then quarantine with the raw response kept. The result is a P10Trigger with is_relevant, an event_type from a fixed list (such as cio_departure, acquisition, pe_investment, security_incident), evidence_quote, confidence, implied_need and urgency_window_days.
  2. The organization is resolved by name (kestrel/ingest/orgs.py), and a record is appended to org.signals exactly once. A stable key (external_id, else source_url, else a hash of organization, event type and evidence) keeps a re-observed item from counting twice.
  3. A signal that is relevant and at or above consulting.min_trigger_confidence (default 0.5) creates a trigger_event opportunity on its own.
  4. Weaker signals accumulate. When an organization reaches three signals within 90 days, it is promoted once, with a "Multiple signals" opportunity, unless it already has a live trigger opportunity. This is the three-weak-signals rule.

A model failure is reported as quarantined or error, never as a rejection. Tier 0 then scores the resulting opportunity with the consulting rules in Filter rules, including org_signal_count, which reads the records you just wrote.

Files to touch

  1. kestrel/ingest/signal_sources/<kind>.py: the class.
  2. kestrel/ingest/signal_sources/__init__.py: add the kind to the SIGNAL_SOURCE_KINDS frozenset, and add a (module, class) pair to the tuple inside _register_all(). Both are required. The runner routes on the frozenset, so a kind missing from it is sent down the job posting path and fails.
  3. kestrel/db/enums.py: add the kind to SOURCE_KINDS. The Sources page refuses a kind that is not in it, both when a source is created (POST /sources) and when its Settings (JSON) editor, under Show details in the source's drawer, is saved.
  4. kestrel/ingest/catalog.py: add a description to _DESCRIPTIONS. tests/test_about_sources.py::test_every_listed_kind_is_documented fails until you do.
  5. kestrel/ingest/dedup.py: add a precedence to _PRIORITY if the source emits postings. Unmapped kinds rank 9, the least canonical. Triggers do not go through job posting dedup.
  6. tests/test_<kind>.py: parsing and validate_config tests.
  7. docs/SOURCES.md and SPEC.md, if the payload shape is worth recording.
  8. docs/OUTBOUND-CALLS.md: add any new host to the host index with its kind, and describe the call in the tables above it. tests/test_outbound_inventory.py fails until you do, and a call that skips Kestrel's User-Agent or robots.txt handling needs a plain sentence there. See Security and privacy model.

You do not need to touch the scheduler, the worker, the CLI or the Sources page validation. All of them route on SIGNAL_SOURCE_KINDS and call get_signal_source(kind).validate_config for you.

What the registry does not give you is a way for a person to add the source without writing JSON. The Add a source sheet (kestrel/web/pages/sources_ui.py) has one tile per type: for the consulting track, Job board search, Public bids (gov, which builds a sam_gov source), Watch a company (sig, which builds a sec_edgar source from a company name) and Company news (feeds, which builds an rss source from a feed link). The tile list is TYPES, and _build_source() turns a tile's form into a source. pe_portfolio has a route (POST /sources/pe-portfolio) but no tile on the sheet today. A new signal kind needs a tile and a branch there so that the app, and not only a JSON editor, can add it. Add a test beside the existing sheet tests, and check docs/SOURCES.md for how the kind is described to people. The how_to_add text that kestrel/ingest/catalog.py generates for the About page still points at a generic form under Advanced, which the sheet has replaced, so do not copy it into new documentation.

A minimal source

This example reads a made-up JSON newsroom API. The URL and fields are invented. Take real ones from a real response.

"""Acme newsroom signal source: one trigger per press release."""

from __future__ import annotations

from typing import Any

from kestrel.ingest.signal_base import AdapterError, RawSignal, SourceConfigError

_DEFAULT_RATE = 1.0


class AcmeNewsSignalSource:
    kind = "acme_news"

    def validate_config(self, config: dict) -> None:
        url = config.get("url")
        if not isinstance(url, str) or not url.startswith("https://"):
            raise SourceConfigError("acme_news requires an https 'url'")

    async def fetch(self, config: dict, client: Any) -> list[RawSignal]:
        self.validate_config(config)
        rate = float(config.get("rate_per_sec", _DEFAULT_RATE))
        try:
            data = await client.get_json(config["url"], rate_per_sec=rate, public_only=True)
        except Exception as exc:
            raise AdapterError(f"acme_news fetch failed: {exc}") from exc
        items = data.get("items") if isinstance(data, dict) else None
        if not isinstance(items, list):
            raise AdapterError("acme_news: unexpected response shape")
        signals: list[RawSignal] = []
        for item in items:
            if not isinstance(item, dict) or not item.get("id"):
                continue
            signals.append(
                RawSignal(
                    signal_kind="trigger",
                    org_name=item.get("company"),
                    source_url=item.get("link"),
                    external_id=str(item["id"]),
                    title=item.get("headline"),
                    text=f"{item.get('headline', '')}\n\n{item.get('summary', '')}".strip(),
                    published_date=item.get("published"),
                    raw={"feed": config["url"]},
                )
            )
        return signals

Registration in __init__.py:

SIGNAL_SOURCE_KINDS = frozenset({"sec_edgar", "sam_gov", "pe_portfolio", "rss", "acme_news"})

# inside _register_all(), in the tuple of (module, class) pairs:
("acme_news", "AcmeNewsSignalSource"),

Pass check_robots=True to client.get_text or client.get_json when you read ordinary web pages, as pe_portfolio.py does. A disallow raises PermissionError; treat that as "skip this page", never as a reason to ignore robots.txt. The JSON endpoints that SEC EDGAR and SAM.gov document do not set it, and neither does the RSS source's read of a feed the person adds.

Lessons from the shipped sources

  • SEC EDGAR (sec_edgar.py). The User-Agent must carry a real contact address. edgar_user_agent() raises SourceConfigError when it does not, using has_contact_address(), which rejects any value without @ or containing example.com. That disables the source before the first request instead of sending a made-up contact. The searches hit efts.sec.gov and the documents hit www.sec.gov, which the limiter buckets separately, so the default is 5 requests per second per host to stay under the 10 per second SEC ceiling. robots.txt is not checked for EDGAR, whose fair-access rules apply instead. If every query fails the source raises AdapterError. If only some fail, it returns what it collected with fetch_errors set.
  • SAM.gov (sam_gov.py). Emits posting signals. The key comes from config.api_key or the environment variable named by api_key_env (default SAM_GOV_API_KEY), is sent in an X-Api-Key header and never goes in a URL, because error text is stored in scrape_run.error. The call is keyed and does not check robots.txt. The description field is sometimes a link to another document. The source does not fetch it and falls back to the title. The module docstring says this source was coded against the documentation and not verified against the live API.
  • RSS (rss.py). Fetched with public_only=True because the feed address is the person's, and not checked against robots.txt. Parsed with the standard library ElementTree, which has no protection against entity expansion, so any feed declaring a DOCTYPE or ENTITY in its first 4 KB is refused. A broken feed is logged and skipped. org_name is left None for P10 to extract.
  • PE portfolio (pe_portfolio.py). Reads one configured page per firm, uses check_robots=True and public_only=True, and by default keeps only linked entries that are not navigation or social links. An optional css_selector in the config overrides that heuristic. external_id is firm:company, so a company already seen is re-observed, not promoted again.

Testing

Tests never call a live endpoint (CLAUDE.md). The signal source tests build their sample payloads inline in the test file with a fake client; see tests/test_sec_edgar.py and tests/test_rss.py. tests/test_signal_runner.py covers the runner behavior above, and tests/test_triggers.py with tests/trigger_fakes.py covers classification and promotion without a model.

Assert the field mapping for your payload, that validate_config refuses each missing key, that a duplicate external_id is collapsed, and that a failed request becomes AdapterError or fetch_errors and not an unhandled exception. Then run uv run --extra dev python scripts/check.py before pushing, as described in Contributing.

Related

Clone this wiki locally