Repository navigation
Adding a Signal Source
Checked against v0.6.1 (commit 3b06892) on October 19, 2026.
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 in v0.5.0: 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.txtrespected, nothing behind a login. - Kestrel never acts for you. A signal source reads. A trigger opportunity is created with
url=Nonebecause there is nothing to apply to, and nothing in this path sends a message or contacts anyone.
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.
run_signal_source() in kestrel/ingest/signal_runner.py handles one source per call.
- It creates a
scrape_run, looks up the source withget_signal_source(kind), callsvalidate_config, thenfetch. -
SourceConfigErrordisables the source (enabled = False), adds asource_disablednotification and ends the runpartial. This is the path a missing SAM.gov key takes. -
AdapterErroror any other exception adds one toconsecutive_failures. Three in a row disable the source with a notification. - Each signal is processed and committed on its own. One bad signal rolls back and increments an error count, not the whole run.
- If
fetchreturns a list with afetch_errorsattribute, the runner records those and marks the runpartial.SignalBatchinkestrel/ingest/signal_sources/sam_gov.pyis alistsubclass that carries it. Use it when some of your queries can fail while others succeed. - 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.
classify_and_store() in kestrel/ingest/triggers.py is the part that makes this track different. For each trigger signal:
- 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 aP10Triggerwithis_relevant, anevent_typefrom a fixed list (such ascio_departure,acquisition,pe_investment,security_incident),evidence_quote,confidence,implied_needandurgency_window_days. - The organization is resolved by name (
kestrel/ingest/orgs.py), and a record is appended toorg.signalsexactly once. A stable key (external_id, elsesource_url, else a hash of organization, event type and evidence) keeps a re-observed item from counting twice. - A signal that is relevant and at or above
consulting.min_trigger_confidence(default 0.5) creates atrigger_eventopportunity on its own. - 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.
-
kestrel/ingest/signal_sources/<kind>.py: the class. -
kestrel/ingest/signal_sources/__init__.py: add the kind to theSIGNAL_SOURCE_KINDSfrozenset, 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. -
kestrel/db/enums.py: add the kind toSOURCE_KINDS, or the Sources page cannot offer it. -
kestrel/ingest/catalog.py: add a description to_DESCRIPTIONS.tests/test_about_sources.py::test_every_listed_kind_is_documentedfails until you do. -
kestrel/ingest/dedup.py: add a precedence to_PRIORITYif the source emits postings. Unmapped kinds rank 9, the least canonical. Triggers do not go through job posting dedup. -
tests/test_<kind>.py: parsing andvalidate_configtests. -
docs/SOURCES.mdandSPEC.md, if the payload shape is worth recording.
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.
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)
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 signalsRegistration 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 EDGAR and SAM.gov document do not set it.
-
SEC EDGAR (
sec_edgar.py). The User-Agent must carry a real contact address.edgar_user_agent()raisesSourceConfigErrorwhen it does not, usinghas_contact_address(), which rejects any value without@or containingexample.com. That disables the source before the first request instead of sending a made-up contact. The searches hitefts.sec.govand the documents hitwww.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. If every query fails the source raisesAdapterError. If only some fail, it returns what it collected withfetch_errorsset. -
SAM.gov (
sam_gov.py). Emitspostingsignals. The key comes fromconfig.api_keyor the environment variable named byapi_key_env(defaultSAM_GOV_API_KEY), is sent in anX-Api-Keyheader and never goes in a URL, because error text is stored inscrape_run.error. Thedescriptionfield 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). Parsed with the standard libraryElementTree, which has no protection against entity expansion, so any feed declaring aDOCTYPEorENTITYin its first 4 KB is refused. A broken feed is logged and skipped.org_nameis leftNonefor P10 to extract. -
PE portfolio (
pe_portfolio.py). Reads one configured page per firm, usescheck_robots=True, and by default keeps only linked entries that are not navigation or social links. An optionalcss_selectorin the config overrides that heuristic.external_idisfirm:company, so a company already seen is re-observed, not promoted again.
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.
Start here
Interfaces
Extending Kestrel
How it works
- Prompts and context budgets
- Document engine
- Learning loop internals
- Analytics internals
- Task queue and concurrency
- Database schema
Shipping and safety
- Packaging and releases
- Preflight and diagnostics
- Security and privacy model
- Outbound calls
- Benchmarking
Workarounds and Troubleshooting