Skip to content

Triggers

scarecr0w12 edited this page Jun 19, 2026 · 2 revisions

Triggers

Event-driven automation system for CortexPrism, enabling automatic agent turns and system events in response to webhooks, filesystem changes, and git hooks.

Architecture

Five files in src/triggers/:

File Purpose
types.ts Core types: TriggerConfig, TriggerEvent, providers, rate limits
manager.ts Trigger registry, rate limiting, template rendering, signature verification
webhook.ts HTTP webhook handler for GitHub, GitLab, and Generic providers
watcher.ts Filesystem watcher via Deno.watchFs with debouncing
git-hooks.ts Git hook installation and uninstallation

Three Trigger Sources

1. Webhooks

HTTP endpoint at /api/webhooks/<triggerName>. Supports three providers:

Provider Event Header Signature Header Events
GitHub X-GitHub-Event X-Hub-Signature-256 (sha256=...) push, pull_request, issues, release, check_run
GitLab X-Gitlab-Event X-Gitlab-Token Push Hook, Merge Request Hook, Issue Hook
Generic X-Event-Type X-Signature * (all)

Signature Verification

HMAC-SHA256 verification using crypto.subtle.verify(). The secret is loaded from webhook.secret or resolved via webhook.secretEnv (environment variable). If no secret is configured, verification is skipped.

IP Allow-listing

Optional CIDR-based IP filtering via webhook.allowedIps. Supports both exact IP matching and CIDR notation (e.g., 192.168.1.0/24).

Request Flow

  1. Match URL path: /api/webhooks/<triggerName>
  2. Look up trigger by name
  3. Check IP allow-list
  4. Read body, extract signature header
  5. Verify HMAC signature
  6. Parse JSON payload
  7. Extract event type from provider-specific header
  8. Filter by configured events
  9. Create TriggerEvent and dispatch to handler

2. Filesystem Watcher

Uses Deno.watchFs() to monitor filesystem changes.

Option Description
paths Directories or files to watch
patterns Glob patterns to filter files (supports * and ? wildcards)
events Event kinds: create, modify, delete
debounceMs Debounce window before firing trigger
recursive Watch subdirectories

Debouncing: Multiple filesystem events within debounceMs are batched. A timer fires once to process all accumulated change paths as a single trigger event.

3. Git Hooks

Installs shell scripts into .git/hooks/ that POST webhook payloads to the local Cortex server.

The generated hook scripts send a JSON payload with:

  • event: hook name
  • repo: repository path
  • timestamp: generation timestamp
  • branch: current branch name
  • commit: HEAD commit SHA
  • message: last commit message

Installation: installGitHooks(repoPath) writes executable hook scripts. Uninstallation: uninstallGitHooks(repoPath) removes only Cortex-generated hooks (detected by marker comment).

Trigger Actions

Two action types:

Type Description
agent_turn Creates a new agent turn with the rendered prompt
system_event Fires a system-level event

Template System

Prompt templates use {{ variable.path | filter }} syntax:

Filter Description Example
(none) Stringify value {{ repo.name }}
length Array length {{ commits | length }}
join Array join with , {{ files | join }}

Variables use dot-notation to traverse the event data object. Undefined values render as empty strings.

Rate Limiting

Per-trigger rate limiting with count-based windows:

interface RateLimit {
  count: number;          // Max events per window
  perSeconds: number;     // Window duration in seconds
  cooldownSeconds: number; // Minimum interval between events
}

checkRateLimit() maintains per-trigger buckets with reset timestamps and cooldown enforcement.

Security

Feature Description
HMAC-SHA256 Signature verification for webhooks
IP allow-listing CIDR-based source filtering
Rate limiting Per-trigger event throttling
Secret management Secrets via environment variables or direct config

Configuration

{
  "name": "on-pr-merged",
  "enabled": true,
  "source": "webhook",
  "webhook": {
    "path": "/api/webhooks/on-pr-merged",
    "secretEnv": "WEBHOOK_SECRET",
    "providers": ["github"],
    "events": ["pull_request"]
  },
  "action": {
    "type": "agent_turn",
    "agent": "code-reviewer",
    "promptTemplate": "A PR was merged: {{ pull_request.title }} by {{ sender.login }}. Please review the changes.",
    "timeoutSeconds": 300
  },
  "rateLimit": {
    "count": 10,
    "perSeconds": 60,
    "cooldownSeconds": 5
  }
}

CLI

cortex trigger list                         # List all triggers
cortex trigger create <config.json>         # Create trigger from config file
cortex trigger delete <name>                # Delete trigger
cortex trigger test <name> [data.json]      # Test trigger with sample data
cortex trigger hooks install <repo-path>    # Install git hooks
cortex trigger hooks uninstall <repo-path>  # Uninstall git hooks

See Also

Clone this wiki locally