Skip to content

Signals and Signal Sources

Signals turn external events into auditable Brezel records. A signal source polls a channel through a driver, a small AI agent filters the resulting signals, and a large AI agent groups accepted signals into cases and work items. Cases and work items remain withheld until a human reviews them.

Signal source --poll every 5 min--> Signal --small model--> accepted --large model every 15 min--> Case
|
+--> rejected (retained for audit)
Case --> Work Item (withheld) --> Human Review --> approved + released --> optional agent execution
  • SignalSources: a module capability for driver selection, configuration, cursor state, and polling health.
  • Signals: a module capability for normalized payloads, classifications, audit state, and case references.
  • Cases: a capability for generated decisions or cases.
  • CaseWorkItems: a capability for reviewable, releasable work derived from a case.
  • SignalDriver: the PHP contract used to add channels other than IMAP.
  • imap: the built-in driver, implemented with directorytree/imapengine.
  • webhook: the built-in push driver for external applications. It provisions a token-authenticated source URL and sends received payloads through the same signal classification pipeline as polled sources.
  • signal-filter: an automatically provisioned small-model agent.
  • signal-case-builder: an automatically provisioned large-model agent.

Capabilities generate their canonical fields during Bakery planning. A new module can therefore use "fields": []. Explicit fields are only needed for presentation data, driver-specific configuration, or an existing schema that should be mapped to a capability.

Before enabling a source, make sure that:

  1. The API version containing the signal jobs and capability classes is deployed.
  2. Tenant migrations have been applied with php bakery migrate --force.
  3. The target system has a global client.
  4. AI provider credentials and the small and large default models are configured.
  5. The system scheduler runs every minute.
  6. A queue worker processes the system’s workflow queue.
  7. The four capability-backed modules described below have been applied.

For local queue processing:

Terminal window
php bakery work example

For a typical server, invoke Laravel’s scheduler every minute. The exact PHP path depends on the deployment:

* * * * * cd /path/to/brezel-api && php artisan schedule:run >/dev/null 2>&1

Set both defaults in the API environment:

OPENAI_API_KEY=sk-...
AI_DEFAULT_SMALL_MODEL=gpt-5.4-mini
AI_DEFAULT_LARGE_MODEL=gpt-5.4

AI_DEFAULT_MODEL remains the legacy fallback for the large tier. Model resolution follows this order:

  1. Explicit model on the agent.
  2. Provider-specific tier configuration, when present.
  3. AI_DEFAULT_SMALL_MODEL or AI_DEFAULT_LARGE_MODEL.
  4. Legacy AI_DEFAULT_MODEL fallback.

The signal filter uses small; the case builder uses large. If an agent with the reserved identifier already exists, Brezel uses that agent unchanged. This makes it possible to customize the provider, model, and instructions before the first signal arrives:

Terminal window
php bakery agent create example signal-filter \
--name="Signal Filter" \
--provider=openai \
--model-tier=small \
--background
php bakery agent create example signal-case-builder \
--name="Signal Case Builder" \
--provider=openai \
--model-tier=large \
--background

An explicit --model overrides --model-tier. Provider credentials and budgets are configured by the operator of the instance.

The generic SignalSources capability generates these fields:

FieldPurpose
source_identifierStable source identity used in deduplication keys.
driverRegistered driver identifier. Defaults to imap.
enabledWhether the scheduler should poll the source.
configurationDriver configuration not represented by dedicated fields.
cursorDriver-owned incremental polling state.
webhook_urlRead-only URL generated for a source using the webhook driver.
webhook_tokenRead-only secret token storage. The token is hashed; use the generated URL as the integration credential.
statusidle, active, or error.
last_polled_atTime of the last successful poll.
last_errorLast polling error, capped at 2,000 characters.

For an IMAP source, add editable IMAP fields and map them into the driver’s configuration:

[
{
"resource_module": "signal_sources",
"resource": {
"identifier": "signal_sources",
"title": "title",
"icon": "mdi:access-point",
"options": {
"capabilities": [
{
"identifier": "SignalSources",
"options": {
"driver_configuration": {
"host": "host",
"port": "port",
"username": "username",
"password": "password",
"encryption": "encryption",
"validate_cert": "validate_cert",
"folders": "folders",
"bootstrap_days": "bootstrap_days",
"max_messages_per_poll": "max_messages_per_poll"
}
}
}
]
},
"fields": [
{"identifier": "title", "type": "text", "options": {"rules": "required"}},
{"identifier": "host", "type": "text"},
{"identifier": "port", "type": "number", "options": {"default": 993}},
{"identifier": "username", "type": "text"},
{"identifier": "password", "type": "password", "options": {"hide_value": true}},
{"identifier": "encryption", "type": "choice", "options": {"default": "ssl", "values": ["ssl", "tls", "none"]}},
{"identifier": "validate_cert", "type": "checkbox", "options": {"default": true}},
{"identifier": "folders", "type": "list", "options": {"default": ["INBOX"], "fields": [{"identifier": "value", "type": "text"}]}},
{"identifier": "bootstrap_days", "type": "number", "options": {"default": 7}},
{"identifier": "max_messages_per_poll", "type": "number", "options": {"default": 25}}
]
}
}
]

driver_configuration maps configuration keys to entity fields. Values from dedicated fields override values with the same key in the generic configuration JSON field.

The capability also accepts:

OptionDefaultPurpose
drivers["imap", "module", "webhook"]Choice values offered by the generated driver field. Add custom driver identifiers here.
field_mappingcanonical namesMaps capability roles to fields in an existing module.
driver_configuration{}Maps driver configuration keys to editable module fields.

Select webhook as the source driver and create the source through the normal resource API or SPA. After creation, Brezel generates a unique webhook_url. Enable the source before sending data. Send JSON or form data to that URL with POST:

Terminal window
curl -X POST 'https://example.test/system/public/signal/orders/GENERATED_TOKEN' \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: order-event-42' \
-d '{"order":{"id":42},"status":"created"}'

The endpoint returns 202 Accepted and queues classification. Reusing the same Idempotency-Key for the same source returns 200 with status: duplicate; without an event identity, every request is treated as a new signal. The signal type defaults to webhook.received and can be overridden with X-Brezel-Signal-Type or X-Event-Type. To derive the identity from a JSON field instead, set event_id_field in the source’s generic configuration field.

The token is never stored in clear text. Treat the generated URL like a credential and restrict access to the signal source module accordingly.

Keep credentials in the system environment and reference them from a detached Bakery entity. Cursor and health fields are runtime state. A synchronized source can reapply capability defaults such as cursor = {} and status = idle, resetting the polling position even when those fields are omitted from the seed.

Use detach so the source becomes runtime-owned after it is created:

[
{
"resource_entity": "signal_source_inbox",
"depends_on": "resource_module.signal_sources",
"policy": "detach",
"resource": {
"module": "signal_sources",
"client": "${resource_client.global_client}",
"fields": {
"source_identifier": "main-inbox",
"title": "Main Inbox",
"driver": "imap",
"enabled": "${env('SIGNAL_IMAP_ENABLED', false)}",
"host": "${env('SIGNAL_IMAP_HOST', '')}",
"port": "${env('SIGNAL_IMAP_PORT', 993)}",
"username": "${env('SIGNAL_IMAP_USERNAME', '')}",
"password": "${env('SIGNAL_IMAP_PASSWORD', '')}",
"encryption": "${env('SIGNAL_IMAP_ENCRYPTION', 'ssl')}",
"validate_cert": "${env('SIGNAL_IMAP_VALIDATE_CERT', true)}",
"folders": [{"value": "INBOX"}],
"bootstrap_days": 7,
"max_messages_per_poll": 25,
"configuration": {}
}
}
}
]

Do not switch a live source to policy: sync. To change its connection settings later, edit the source in Brezel or recreate it deliberately after preserving or resetting its cursor. Keep cursor, status, last_polled_at, and last_error out of the seed as an additional safeguard and to make their runtime ownership explicit.

In systems/example/.env:

SIGNAL_IMAP_ENABLED=false
SIGNAL_IMAP_HOST=imap.example.com
SIGNAL_IMAP_PORT=993
SIGNAL_IMAP_USERNAME=inbox@example.com
SIGNAL_IMAP_PASSWORD=change-me
SIGNAL_IMAP_ENCRYPTION=ssl
SIGNAL_IMAP_VALIDATE_CERT=true

Apply the module while the source is disabled. Enable it only after the connection values, queue, and scheduler have been verified.

KeyDefaultNotes
hostnoneRequired by the IMAP server.
port993Cast to an integer.
usernamenoneIMAP login.
passwordnoneIMAP password or application password.
encryptionsslssl, tls, or none. none is converted to no encryption.
validate_certtrueKeep enabled outside controlled local development.
timeout30Connection timeout in seconds; normally supplied through configuration.
folders["INBOX"]List values or a comma-separated string. List records may use {"value":"INBOX"}.
bootstrap_days7Lookback used when no valid UID cursor exists. 0 starts at the current UTC day.
max_messages_per_poll25Per-folder limit, clamped to 1..100.

The driver:

  • uses directorytree/imapengine;
  • fetches messages in ascending UID order;
  • leaves messages unread;
  • stores a cursor per folder with UID, UIDVALIDITY, and message time;
  • resets to the configured lookback when UIDVALIDITY changes;
  • uses Message-ID, or folder and UID as fallback, for stable transport keys;
  • stores the original text or HTML body, capped at 50,000 characters, together with body_format;
  • disconnects the mailbox even when polling fails.

The normalized mail.received payload contains message_id, uid, folder, from, from_name, to, cc, subject, body, body_format, and sent_at.

The persisted payload remains the audit source and is never mutated for AI use. Immediately before classification, Brezel creates a model-only copy: HTML structure, styles, scripts, hidden content, CSS fragments, tracking whitespace, and excessive blank lines are removed from body. The 50,000-character model limit is applied after this cleanup. Keeping the raw payload allows later retries to benefit from improved preprocessing without fetching the mail again.

The Signals capability supplies the complete audit schema, so the module itself needs no fields:

[
{
"resource_module": "signals",
"depends_on": "resource_module.signal_sources",
"resource": {
"identifier": "signals",
"title": "signal_identifier",
"icon": "mdi:radar",
"options": {"capabilities": ["Signals"]},
"fields": []
}
}
]

Generated fields include the source relation and source key, normalized type and payload, occurrence time, classification result, safety, relevance, reason, classifier run, processing batch, case keys, and error text.

Signal states are:

StateMeaning
pending_classificationPersisted and queued for the filter agent.
acceptedBoth safe and relevant are true.
rejectedUnsafe or not relevant. The record remains available for audit.
classification_failedThe agent run or structured JSON parsing failed.
processingReserved by the current case-building batch.
processedBatch processing finished; case_keys records generated cases.

Every persisted source key is prefixed with source_identifier. Duplicate keys are ignored, which makes repeated polls safe. The source cursor is stored after a successful poll. If ingestion is retried before the cursor is updated, the same deduplication key prevents duplicate signal records.

The batch processor only runs when Brezel finds modules with Cases and CaseWorkItems. They can use any identifiers; the capabilities are what connect them to the signal runtime.

Example using decisions:

[
{
"resource_module": "decisions",
"resource": {
"identifier": "decisions",
"title": "title",
"options": {
"capabilities": [
{
"identifier": "Cases",
"options": {
"include_optional_fields": true,
"field_mapping": {
"identifier_field": "decision_identifier"
}
}
}
]
},
"fields": []
}
},
{
"resource_module": "decision_work_items",
"depends_on": "resource_module.decisions",
"resource": {
"identifier": "decision_work_items",
"title": "description",
"options": {
"capabilities": [
{
"identifier": "CaseWorkItems",
"options": {
"include_optional_fields": true,
"case_module": "decisions",
"field_mapping": {
"case_relation_field": "decision"
}
}
}
]
},
"fields": []
}
}
]

When no field_mapping is present, optional fields are included automatically. When at least one field is mapped, include_optional_fields defaults to false; set it to true when the capability should still generate all review, target, provenance, and agent-brief fields.

case_module tells CaseWorkItems which module the generated case relation references. It defaults to cases.

Mappings are intended for existing schemas. A mapped field keeps its existing type and required rules. If the mapped field does not yet exist, Bakery creates it using the capability’s standard definition.

The scheduler dispatches source polling every minute and case batching every fifteen minutes for every configured system. Both jobs use the system workflow queue, onOneServer, and overlap protection. Poll jobs are additionally unique per system while queued or running. Ingestion also locks each source and merges IMAP folder cursors monotonically: within the same UIDVALIDITY, an older concurrent result cannot lower the stored UID. A changed UIDVALIDITY is treated as a legitimate mailbox reset.

For every new signal, classification is queued immediately. The signal-filter agent must return a JSON object with:

{
"safe": true,
"relevant": true,
"reason": "Existing customer asks for a contract change.",
"category": "customer_request",
"confidence": 0.94,
"security_flags": []
}

Safety and relevance are independent. Prompt injection, instruction manipulation, phishing, impersonation, and other security warnings must produce safe = false, even when the underlying business subject is important and therefore relevant = true. Only safe and relevant signals enter case batching. Existing systems can retain a historical physical field such as serious by mapping safe_field to it; the field then carries safety semantics.

A batch takes at most 50 accepted signals in occurrence order. The signal-case-builder returns cases, each with identifier, title, summary, priority, signal_keys, and work_items. Supported work item kinds are analysis, reply, implementation, review, and follow_up. Invalid kinds fall back to follow_up; invalid priorities fall back to medium.

Generated cases start with:

status = generated
review_state = review_pending

Generated work items start with:

status = generated
review_state = review_pending
agent_release_state = withheld
execution_state = not_started

No signal-generated work item is automatically released to an execution agent.

Add layouts, permissions, and review actions

Section titled “Add layouts, permissions, and review actions”

Capabilities create storage fields, not an instance-specific user experience. Add normal index and detail layouts that reference the generated field identifiers, then add the modules to a menu and grant roles access.

For signal triage, useful index tabs are:

  • Classification errors.
  • Pending classification.
  • Relevant (safe = true, relevant = true).
  • Safe but not relevant.
  • Unsafe.
  • All signals.

Keep these filters mutually exclusive by also filtering classified tabs by accepted or rejected. Otherwise the default false values of unclassified checkbox fields can make pending signals appear as unsafe.

For failed classifications, expose a detail-layout button only when status == 'classification_failed'. Its webhook workflow can call action/retrySignalClassification, followed by action/refresh. The action clears the previous classification and error fields, sets pending_classification, and queues one deduplicated ClassifySignal job.

Human-review buttons should invoke workflows instead of making review_state and agent_release_state freely editable. A typical setup provides:

  • Approve and reject actions for cases.
  • Approve and reject actions for work items.
  • A separate release action that checks review_state == 'approved' before setting agent_release_state = 'released'.
  • A withhold action that returns the release state to withheld.
  • reviewed_by or approved_by set to user() in the workflow.

See Workflow-backed Buttons for the declarative UI and workflow pattern.

Polling signal drivers are pull-based. Implement SignalDriver for a channel that can be polled, such as a webhook staging table, message queue adapter, support API, filesystem inbox, or CRM event feed.

<?php
namespace App\Signals\Drivers;
use App\Signals\Contracts\SignalDriver;
use App\Signals\SignalEnvelope;
use App\Signals\SignalPollResult;
use Carbon\CarbonImmutable;
final class SupportApiSignalDriver implements SignalDriver
{
public function poll(array $configuration, array $cursor): SignalPollResult
{
$after = $cursor['last_id'] ?? null;
$records = $this->loadRecords($configuration, $after);
$signals = array_map(
fn(array $record) => new SignalEnvelope(
sourceKey: 'ticket:' . $record['id'],
type: 'support.ticket.received',
occurredAt: CarbonImmutable::parse($record['created_at'])->utc(),
payload: $record,
),
$records,
);
return new SignalPollResult(
signals: $signals,
cursor: ['last_id' => $records === [] ? $after : end($records)['id']],
);
}
private function loadRecords(array $configuration, mixed $after): array
{
// Fetch records from the external channel.
return [];
}
}

Register it during application boot:

use App\Signals\Drivers\SupportApiSignalDriver;
use App\Signals\SignalDriverManager;
public function boot(SignalDriverManager $signals): void
{
$signals->extend('support_api', SupportApiSignalDriver::class);
}

Add support_api to the drivers option of SignalSources, expose any driver-specific fields, and map them through driver_configuration. A driver must:

  1. Return stable sourceKey values within one source.
  2. Return UTC occurrence times.
  3. Keep payloads JSON-serializable and bounded.
  4. Treat the incoming cursor as opaque driver state.
  5. Return the next cursor only after it has successfully collected the corresponding envelopes.
  6. Avoid irreversible changes to the external channel during polling.

Use a targeted plan before changing a live system:

Terminal window
php bakery plan example
php bakery apply example

Review the complete plan. apply recalculates the plan and may include unrelated changes in a dirty system definition.

Recommended rollout order:

  1. Apply migrations and the four modules while all sources are disabled.
  2. Start or verify the queue worker and scheduler.
  3. Verify provider credentials and both model tiers with CLI agent runs.
  4. Enable one source with a small bootstrap window.
  5. Confirm last_polled_at, source status, and newly created signal records.
  6. Confirm rejected signals remain visible and accepted signals reach processed.
  7. Review generated cases and work items before releasing anything to agents.
SymptomCheck
Source stays idleIs enabled true, and does the server invoke schedule:run every minute?
Source becomes errorInspect last_error, IMAP connectivity, credentials, encryption, folder names, and certificate validation.
Signals stay pending_classificationIs the system queue worker running, and can the small model be resolved?
Signals become classification_failedInspect error and the associated agent run. Fix the cause, then use the retry-classification button. The agent must return valid structured JSON.
Accepted signals never become casesEnsure the Cases and CaseWorkItems capabilities are applied and the large model is available.
The same messages are fetched againCheck the source cursor and UIDVALIDITY. Duplicate signal records should still be prevented by source_key.
Cursor returns to {} or the source becomes idle after php bakery applyRemove the runtime fields from the seed and use policy: detach for the source entity.
Poll succeeds but creates no signals while newer mail existsCompare the cursor UID with the highest persisted signal UID and IMAP UIDNEXT. A cursor behind already persisted messages advances in max_messages_per_poll batches without creating duplicates.
Old mail is not importedIncrease bootstrap_days, clear the source cursor intentionally, and poll again. Expect deduplication to skip known messages.
Too many messages are processedLower max_messages_per_poll; the driver enforces a maximum of 100 per folder and poll.