Files
kandev/apps/backend/internal/automation/trigger_registry.go
T
João Salavisa 37b56ba11c feat(automations): reliable cron scheduling and webhook-driven push/CI triggers (#1972)
* feat(automations): reliable cron scheduling and webhook-driven push/CI triggers

Automations were "wounded": cron schedules mishandled timezones and some
never fired, and the GitHub push/CI trigger types were coming-soon stubs.

Cron (fix):
- The scheduler reduced every cron expression to a fixed interval derived
  only from a */N step in the minute/hour field, so any pinned schedule
  (0 9 * * *, 30 14 * * *, weekday ranges, day-of-month) never fired, and
  the configured timezone was parsed but never used.
- Replace the interval approximation with robfig/cron/v3: shouldFire now
  computes the true next fire time in the configured timezone (DST-aware,
  defaulting to UTC for host-independence), anchored to last-evaluated or
  creation time. Dead interval-parsing helpers and shorthand constants
  removed.

GitHub push + CI triggers (feat):
- Implement push and CI-failure triggers end to end via the existing
  per-workspace GitHub App webhook plumbing (#1810): the HMAC-verified
  webhook service now parses push and completed check_run events, resolves
  the installation to its workspaces, and publishes normalized bus events.
- A new automation subscriber matches enabled github_push / github_ci
  triggers by workspace + repo + branch/conclusion/check-name filters and
  fires them (deduped by commit SHA / check-run id). The old poll-based
  stub evaluators are removed; the PR poll path is unchanged.
- Subscribe the App manifest to push/check_run and enable both trigger
  types in the registry (CI defaults to the failure conclusion).

Docs:
- Update docs/public/feature-status.md and automation-and-mcp.md so the
  cron and push/CI rows reflect shipped reality.

Tests: regression tests pin the previously-never-firing cron shapes,
timezone/DST behavior, and host-independence; backend tests cover the
webhook parse->publish and subscriber match/fire/dedup flows for both
push and CI-failure.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(automations): populate push.message and ci.url placeholders in fired trigger data

Address PR review blockers: the default push and CI automation prompts
reference {{push.message}} and {{ci.url}}, which the interpolator maps to
data["message"] / data["html_url"] — but the webhook subscriber never
populated those fields, so both always rendered empty.

- Parse head_commit.message (push) and check_run.html_url (CI) in the
  GitHub webhook service and carry them on the published bus payloads.
- Include "message" / "html_url" in the fired trigger data so the
  placeholders resolve; extend the webhook and subscriber tests to assert
  both flow through end to end.

Non-blocking review cleanups:
- Replace the misleading reuse of matchesAuthors for CI conclusions/check
  names with a clearly-named matchesFilterValue helper.
- Drop dead context.Background() line and its unused import from the cron
  regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(automations): scope webhook triggers to active installs and per-branch dedup

Address CodeRabbit review on the push/CI webhook triggers:

- Security: resolveWorkspaceIDs now only returns connections whose status is
  active, so a suspended or revoked GitHub App installation can no longer fire
  push/CI automations.
- Correctness: include the branch in the push dedup key
  (push:owner/name@branch@sha) so the same commit pushed to two matching
  branches fires once per branch instead of being suppressed.
- Correctness: add an optional head-branch filter to github_ci triggers and
  gate CI matching on it, matching the push trigger's branch-scoping.
- Stability: make the webhook subscriber's Start retryable — a subscription
  failure rolls back partial subscriptions and leaves the subscriber
  un-started so a later Start re-attempts, instead of permanently disabling
  push/CI processing.
- Tests: cover multi-connection workspace resolution (dedup + inactive
  filtering), per-branch push dedup, and CI branch filtering.
- Docs: note the CI branch filter and per-branch push dedup.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(automations): cover webhook subscriber Start retry-after-failure path

Add TestGitHubWebhookSubscriberStartRetryableAfterFailure with a minimal
flaky bus whose second Subscribe fails, pinning the retry contract: a
subscription failure rolls back the partial subscription and leaves the
subscriber un-started, and a later Start re-attempts and succeeds.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:24:57 +01:00

128 lines
5.9 KiB
Go

package automation
import "encoding/json"
// PlaceholderInfo describes a single {{key}} placeholder available for a trigger type.
type PlaceholderInfo struct {
Key string `json:"key"`
Description string `json:"description"`
Example string `json:"example"`
}
// TriggerTypeInfo describes a trigger type and its associated metadata.
// Served to clients so they can build UIs dynamically.
type TriggerTypeInfo struct {
Type TriggerType `json:"type"`
Label string `json:"label"`
Description string `json:"description"`
Category string `json:"category"` // "schedule", "github", "webhook"
Enabled bool `json:"enabled"`
Placeholders []PlaceholderInfo `json:"placeholders"`
DefaultPrompt string `json:"default_prompt"`
DefaultTaskTitle string `json:"default_task_title"`
DefaultConfig json.RawMessage `json:"default_config"`
}
// Common placeholders available for every trigger type.
var commonPlaceholders = []PlaceholderInfo{
{Key: "trigger.type", Description: "Trigger type (scheduled, github_pr, webhook, etc.)", Example: string(TriggerTypeScheduled)},
{Key: "trigger.timestamp", Description: "When the trigger fired", Example: "2026-03-08T12:00:00Z"},
{Key: "data.*", Description: "Access any field from trigger data", Example: "data.action"},
}
var triggerTypeRegistry = []TriggerTypeInfo{
{
Type: TriggerTypeScheduled,
Label: "Scheduled",
Description: "Runs on a cron schedule",
Category: "schedule",
Enabled: true,
Placeholders: commonPlaceholders,
DefaultPrompt: "Run scheduled automation.\n\nTrigger: {{trigger.type}}",
DefaultTaskTitle: "",
DefaultConfig: json.RawMessage(`{"cron_expression":"0 */6 * * *","timezone":"UTC"}`),
},
{
Type: TriggerTypeGitHubPR,
Label: "New pull requests",
Description: "Polls GitHub for PRs matching your filters (repo, branch, author, labels)",
Category: triggerCategoryGitHub,
Enabled: true,
Placeholders: append([]PlaceholderInfo{
{Key: "pr.number", Description: "Pull request number", Example: "42"},
{Key: "pr.title", Description: "Pull request title", Example: "Fix the bug"},
{Key: "pr.url", Description: "Pull request URL", Example: "https://github.com/org/repo/pull/42"},
{Key: "pr.author", Description: "PR author login", Example: "alice"},
{Key: "pr.repo", Description: placeholderRepositoryOwner, Example: exampleRepositoryOwner},
{Key: "pr.branch", Description: "Head branch name", Example: "fix-bug"},
{Key: "pr.base_branch", Description: "Base branch name", Example: defaultBranchMain},
{Key: "pr.body", Description: "Pull request body text", Example: "Fixes #123"},
}, commonPlaceholders...),
DefaultPrompt: "Review PR #{{pr.number}} in {{pr.repo}}: {{pr.title}}\n\n{{pr.body}}\n\nBranch: {{pr.branch}} → {{pr.base_branch}}",
DefaultTaskTitle: "[Auto] {{pr.repo}}#{{pr.number}} — {{pr.title}}",
DefaultConfig: json.RawMessage(`{"events":["opened"],"repos":[],"exclude_draft":false}`),
},
{
Type: TriggerTypeGitHubPush,
Label: "Push to branch",
Description: "Webhook-driven: triggers when commits are pushed to matching branches. Requires " +
"a workspace GitHub App connection subscribed to push events.",
Category: triggerCategoryGitHub,
Enabled: true,
Placeholders: append([]PlaceholderInfo{
{Key: "push.branch", Description: "Branch that was pushed to", Example: defaultBranchMain},
{Key: "push.repo", Description: placeholderRepositoryOwner, Example: exampleRepositoryOwner},
{Key: "push.sha", Description: "Commit SHA", Example: "abc1234"},
{Key: "push.message", Description: "Commit message", Example: "feat: add feature"},
}, commonPlaceholders...),
DefaultPrompt: "Review push to {{push.branch}} in {{push.repo}}\n\nCommit: {{push.sha}}\n{{push.message}}",
DefaultTaskTitle: "[Auto] Push to {{push.branch}} — {{push.repo}}",
DefaultConfig: json.RawMessage(`{"repos":[],"branches":["main"]}`),
},
{
Type: TriggerTypeGitHubCI,
Label: "CI check result",
Description: "Webhook-driven: triggers when a CI check completes with matching conclusion. Requires " +
"a workspace GitHub App connection subscribed to check_run events.",
Category: triggerCategoryGitHub,
Enabled: true,
Placeholders: append([]PlaceholderInfo{
{Key: "ci.check_name", Description: "CI check/workflow name", Example: "build"},
{Key: "ci.conclusion", Description: "CI conclusion", Example: "failure"},
{Key: "ci.repo", Description: placeholderRepositoryOwner, Example: exampleRepositoryOwner},
{Key: "ci.url", Description: "CI run URL", Example: "https://github.com/..."},
}, commonPlaceholders...),
DefaultPrompt: "CI check '{{ci.check_name}}' {{ci.conclusion}} in {{ci.repo}}\n\n{{ci.url}}",
DefaultTaskTitle: "[Auto] CI {{ci.conclusion}} — {{ci.check_name}}",
DefaultConfig: json.RawMessage(`{"repos":[],"conclusions":["failure"]}`),
},
{
Type: TriggerTypeWebhook,
Label: "Webhook",
Description: "Triggers when an HTTP POST is received at the automation's webhook URL",
Category: "webhook",
Enabled: true,
Placeholders: append([]PlaceholderInfo{
{Key: "webhook.body", Description: "Full webhook request body (JSON)", Example: `{"event":"deploy"}`},
}, commonPlaceholders...),
DefaultPrompt: "Process webhook event.\n\n{{webhook.body}}",
DefaultTaskTitle: "",
DefaultConfig: json.RawMessage(`{}`),
},
}
// GetTriggerTypes returns metadata for all known trigger types.
func GetTriggerTypes() []TriggerTypeInfo {
return triggerTypeRegistry
}
// GetTriggerTypeInfo returns metadata for a specific trigger type, or nil if not found.
func GetTriggerTypeInfo(t TriggerType) *TriggerTypeInfo {
for i := range triggerTypeRegistry {
if triggerTypeRegistry[i].Type == t {
return &triggerTypeRegistry[i]
}
}
return nil
}