⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat: provision Sentry alert rules from sentry/alerts.json
justineb00753888d5
diff --git a/.env.sample b/.env.sampleindex bc4afb315..33224e726 100644--- a/.env.sample+++ b/.env.sample@@ -82,6 +82,7 @@ SMTP_REQUIRE_TLS=# SENTRY_TRACES_SAMPLE_RATE=0.1 # 0.0 disables; default 0 (opt-in)# SENTRY_PROFILES_SAMPLE_RATE=0.1 # 0.0 disables; default 0 (opt-in)# SENTRY_RELEASE= # git SHA; ties events to source maps. Falls back to package.json version.+# SENTRY_API_TOKEN= # Used by scripts/provision-sentry-alerts.sh. Scope: org:write. https://sentry.io/settings/account/api/auth-tokens/# Kaneo Cloud billing via Creem (Optional): only active when KANEO_CLOUD=true# and both keys are set. Self-hosted installs leave these empty; billing stays off.diff --git a/scripts/provision-sentry-alerts.sh b/scripts/provision-sentry-alerts.shnew file mode 100755index 000000000..115177cee--- /dev/null+++ b/scripts/provision-sentry-alerts.sh@@ -0,0 +1,241 @@+#!/usr/bin/env bash+# Provisions Sentry alert rules from sentry/alerts.json via the Sentry REST API.+# Idempotent: existing alerts with the same name are skipped.+#+# Usage:+# SENTRY_API_TOKEN=sntrys_... ./scripts/provision-sentry-alerts.sh+# SENTRY_API_TOKEN=... ./scripts/provision-sentry-alerts.sh --dry-run+#+# The token needs one of: alerts:write, org:admin, org:write, or org:manager scopes.+# Generate at: https://sentry.io/settings/account/api/auth-tokens/+set -euo pipefail++ORG="kaneo"+REGION="de"+API_BASE="https://${REGION}.sentry.io/api/0"++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+CONFIG_DIR="$(dirname "$SCRIPT_DIR")"+ALERTS_FILE="${SENTRY_ALERTS_FILE:-${CONFIG_DIR}/sentry/alerts.json}"++DRY_RUN=0+if [ "${1:-}" = "--dry-run" ] || [ "${SENTRY_DRY_RUN:-0}" = "1" ]; then+ DRY_RUN=1+fi++info() { printf '\033[1;34m[info]\033[0m %s\n' "$*"; }+warn() { printf '\033[1;33m[warn]\033[0m %s\n' "$*" >&2; }+error() { printf '\033[1;31m[err]\033[0m %s\n' "$*" >&2; }+ok() { printf '\033[1;32m[ok]\033[0m %s\n' "$*"; }++if [ -z "${SENTRY_API_TOKEN:-}" ]; then+ error "SENTRY_API_TOKEN is not set. Generate one at https://sentry.io/settings/account/api/auth-tokens/ with alerts:write scope."+ exit 1+fi++if [ ! -f "$ALERTS_FILE" ]; then+ error "Alerts config not found at $ALERTS_FILE"+ exit 1+fi++command -v jq >/dev/null || { error "jq is required"; exit 1; }++# Resolve monitor slug -> numeric ID via Sentry API.+# Returns 1 if not found.+resolve_monitor_id() {+ local slug="$1"+ local response+ response=$(curl -fsSL \+ -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \+ "${API_BASE}/organizations/${ORG}/monitors/?query=${slug}" 2>/dev/null) || return 1+ echo "$response" | jq -r --arg slug "$slug" \+ '.[] | select(.slug == $slug) | .id' | head -n1+}++# Check whether an alert with this name already exists.+# Returns the ID if found, empty string otherwise.+find_existing_alert() {+ local name="$1"+ local response+ response=$(curl -fsSL \+ -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \+ "${API_BASE}/organizations/${ORG}/workflows/?query=${name}" 2>/dev/null) || return 1+ echo "$response" | jq -r --arg name "$name" \+ '.[] | select(.name == $name) | .id' | head -n1+}++# Create a metric detector (used by metric alerts). Returns the new ID.+# Args: detector JSON (without organizationId / projectId).+create_detector() {+ local project="$1"+ local body="$2"+ local response+ response=$(curl -fsSL \+ -X POST \+ -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \+ -H "Content-Type: application/json" \+ -d "$body" \+ "${API_BASE}/organizations/${ORG}/projects/${project}/detectors/")+ echo "$response" | jq -r '.id'+}++# Create a workflow (alert rule). Returns the new ID.+create_workflow() {+ local body="$1"+ local response+ response=$(curl -fsSL \+ -X POST \+ -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \+ -H "Content-Type: application/json" \+ -d "$body" \+ "${API_BASE}/organizations/${ORG}/workflows/")+ echo "$response" | jq -r '.id'+}++# Wire a detector into a workflow (POST detector_ids to the workflow).+attach_detector_to_workflow() {+ local workflow_id="$1"+ local detector_id="$2"+ curl -fsSL \+ -X PUT \+ -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \+ -H "Content-Type: application/json" \+ -d "{\"detectorIds\": [\"${detector_id}\"]}" \+ "${API_BASE}/workflows/${workflow_id}/detector/${detector_id}" >/dev/null+}++# Apply a single alert entry from the JSON config.+apply_alert() {+ local alert_json="$1"+ local name type projects workflow_json++ name=$(echo "$alert_json" | jq -r '.name')+ type=$(echo "$alert_json" | jq -r '.kind')++ if [ -z "$name" ] || [ "$name" = "null" ]; then+ error "Alert entry missing name; skipping"+ return 0+ fi++ local existing+ existing=$(find_existing_alert "$name" || true)+ if [ -n "$existing" ]; then+ ok "Alert '$name' already exists (id $existing); skipping"+ return 0+ fi++ info "Creating alert: $name ($type)"++ case "$type" in+ issue)+ projects=$(echo "$alert_json" | jq -r '.projects | join(",")')+ workflow_json=$(echo "$alert_json" | jq --arg org "$ORG" --arg projects "$projects" '+ .workflow + {+ organizationId: $org,+ triggers: {+ logicType: .workflow.triggers.logicType,+ conditions: .workflow.triggers.conditions,+ actions: []+ }+ }+ ')+ if [ "$DRY_RUN" = "1" ]; then+ echo "$workflow_json" | jq .+ else+ local new_id+ new_id=$(create_workflow "$workflow_json")+ ok "Created workflow $new_id"+ fi+ ;;++ metric)+ local detector_id+ detector_id=$(echo "$alert_json" | jq -r '.detector.id // ""')++ if [ -z "$detector_id" ] || [ "$detector_id" = "null" ]; then+ # Try resolving from detector_slugs (cron check-in monitors).+ local slugs+ slugs=$(echo "$alert_json" | jq -r '.detector_slugs | join(" ")')+ local resolved_ids=()++ for slug in $slugs; do+ local id+ id=$(resolve_monitor_id "$slug" || true)+ if [ -z "$id" ]; then+ warn " cron monitor '$slug' not found in Sentry yet. Have the cron jobs run at least once?"+ continue+ fi+ resolved_ids+=("$id")+ info " resolved monitor '$slug' -> id $id"+ done+ detector_id=$(echo "${resolved_ids[@]:-}" | tr ' ' '\n' | head -n1)+ fi++ # Create the detector (if we have a body for it).+ local detector_body+ detector_body=$(echo "$alert_json" | jq -r '.detector // empty')+ if [ -n "$detector_body" ]; then+ local project+ project=$(echo "$alert_json" | jq -r '.project')+ detector_body=$(echo "$detector_body" | jq --arg org "$ORG" --arg project "$project" '+ . + {organizationId: $org, projectId: $project}+ ')+ if [ "$DRY_RUN" = "1" ]; then+ echo "$detector_body" | jq .+ else+ local new_detector_id+ new_detector_id=$(create_detector "$project" "$detector_body")+ ok "Created detector $new_detector_id"+ detector_id="$new_detector_id"+ fi+ fi++ # Create the workflow.+ local workflow_body+ workflow_body=$(echo "$alert_json" | jq --arg org "$ORG" --arg det "$detector_id" '+ .workflow + {+ organizationId: $org,+ detectorIds: (if $det != "" then [$det] else [] end)+ }+ ')+ if [ "$DRY_RUN" = "1" ]; then+ echo "$workflow_body" | jq .+ else+ local new_workflow_id+ new_workflow_id=$(create_workflow "$workflow_body")+ ok "Created workflow $new_workflow_id"+ fi+ ;;++ *)+ error "Unknown alert kind '$type' for '$name'; skipping"+ return 0+ ;;+ esac+}++# ---- main ----+info "Reading alerts from $ALERTS_FILE"+[ "$DRY_RUN" = "1" ] && info "DRY RUN: no changes will be made"+info "Organization: $ORG, Region: $REGION"++count=$(jq '.alerts | length' "$ALERTS_FILE")+info "Found $count alert(s) to process"++OK=0+SKIPPED=0+ERRORED=0++for i in $(seq 0 $((count - 1))); do+ ALERT=$(jq -c ".alerts[$i]" "$ALERTS_FILE")+ if apply_alert "$ALERT"; then+ OK=$((OK + 1))+ else+ ERRORED=$((ERRORED + 1))+ fi+done++echo ""+info "Done: $OK created/skipped, $ERRORED errors"+[ "$DRY_RUN" = "1" ] && info "Re-run without --dry-run to apply"+info "Configure per-alert notifications in Sentry: Settings > Alerts > [alert name] > Actions"diff --git a/sentry/README.md b/sentry/README.mdnew file mode 100644index 000000000..8a0f0485f--- /dev/null+++ b/sentry/README.md@@ -0,0 +1,61 @@+# Sentry++This directory holds Sentry configuration as code, so the alert rules and dashboards that Kaneo depends on are version-controlled and reproducible.++## What lives here++- `alerts.json` — alert rules. Five rules cover first-seen issues, error spikes, missed cron check-ins, slow p95 latency, and MCP error rate. Both `kaneo-api` and `kaneo-web` are covered.++## What's NOT here yet++- Dashboards. The 10 prebuilt dashboards that Sentry ships are still empty (zero widgets each). Filling them in is the next monitoring item.+- Cron monitor creation. These are auto-created the first time each cron job runs (`Sentry.captureCheckIn` from `apps/api/src/scheduler/index.ts`).++## Applying the alerts++### Option A: provisioning script (recommended)++The script lives at `scripts/provision-sentry-alerts.sh`. It reads `sentry/alerts.json`, asks Sentry which rules already exist, and creates the missing ones. Idempotent — re-runs are safe.++```bash+# 1. Generate a Sentry auth token (admin scope)+# https://sentry.io/settings/account/api/auth-tokens/+# Scope: org:write (or alerts:write)++# 2. Apply+SENTRY_API_TOKEN=sntrys_... ./scripts/provision-sentry-alerts.sh++# Dry-run first to see what would be created+SENTRY_API_TOKEN=sntrys_... ./scripts/provision-sentry-alerts.sh --dry-run+```++The script targets the EU region (`https://de.sentry.io`). If Kaneo ever moves to the US region, change the `region` field in `alerts.json` (or override `SENTRY_API_BASE`).++### Option B: manual setup via the Sentry UI++For each rule in `alerts.json`, walk through Settings > Alerts > Create Alert. The JSON is human-readable enough to drop in to the Sentry UI form fields. Tables of the conditions are at the top of `alerts.json`; the `_comment_*` keys are stripped before applying.++## After applying++The script creates the rules but does NOT wire up notifications. Each rule lands in Sentry with an empty `actions` array so you can choose the right channel per rule. To finish setup:++1. Settings > Alerts > [rule name] > Actions+2. Pick a notification target. Recommended:+ - Slack `#engineering` for spike/latency/cron-missed+ - Email to on-call for new issues and MCP errors+3. Save.++Once notifications are wired, the rules start firing based on the events flowing through `Sentry.captureException` (anywhere in the codebase) and `Sentry.captureCheckIn` (the four cron jobs).++## Schema notes++Two rule families:++- **Issue rules** (`kind: "issue"`) — trigger on event condition types (first_seen_event, regression_event, etc.). One JSON entry per rule.+- **Metric rules** (`kind: "metric"`) — trigger on aggregate conditions (count, p95, failure_rate). Each entry creates a Detector (the metric source) and a Workflow (the alert) and links them via `detectorIds`.++The cron-missed-check-in rule is special: it doesn't create a Detector because the cron monitors already exist. The script resolves the slug strings in `detector_slugs` to numeric IDs via `GET /api/0/organizations/{org}/monitors/`. If the cron jobs haven't run yet, the monitors don't exist and the script will skip with a warning.++The Sentry API surface used is documented at:+- <https://docs.sentry.io/api/monitors/create-an-alert-for-an-organization/>+- <https://docs.sentry.io/api/monitors/create-a-monitor-for-a-project/>diff --git a/sentry/alerts.json b/sentry/alerts.jsonnew file mode 100644index 000000000..0a8b7e219--- /dev/null+++ b/sentry/alerts.json@@ -0,0 +1,173 @@+{+ "version": 1,+ "organization": "kaneo",+ "region": "de",+ "api_base": "https://de.sentry.io/api/0",+ "_comment_actions": "Actions are intentionally minimal. After the script applies this config, configure per-alert notifications in the Sentry UI (Settings > Alerts). Recommended: Slack #engineering or email on-call.",+ "alerts": [+ {+ "name": "Kaneo API: New issue",+ "description": "First time a new issue is seen in kaneo-api. Triages everything that isn't yet bucketed.",+ "kind": "issue",+ "projects": ["kaneo-api"],+ "workflow": {+ "name": "Kaneo API: New issue",+ "enabled": true,+ "triggers": {+ "logicType": "any-short",+ "conditions": [{ "type": "first_seen_event", "comparison": true }],+ "actions": []+ },+ "actionFilters": []+ }+ },+ {+ "name": "Kaneo API: New error spike",+ "description": "More than 50 error events in 5 minutes. Detector is created alongside this workflow.",+ "kind": "metric",+ "project": "kaneo-api",+ "detector": {+ "name": "Kaneo API: Error spike detector",+ "description": "count(error events) > 50 in a 5-minute window",+ "type": "metric_issue",+ "config": {+ "detectionType": "static"+ },+ "dataSources": [+ {+ "dataset": "events",+ "query": "event.type:error",+ "queryType": 1,+ "aggregate": "count()",+ "timeWindow": 300,+ "environment": "production"+ }+ ],+ "workflows": []+ },+ "workflow": {+ "name": "Kaneo API: New error spike",+ "enabled": true,+ "triggers": {+ "logicType": "any-short",+ "conditions": [{ "type": "gt", "comparison": 50 }],+ "actions": []+ },+ "actionFilters": []+ }+ },+ {+ "name": "Cron: missed check-in (any)",+ "description": "A monitored cron job missed its check-in (or reported an error). Covers all 4 crons created by Sentry.captureCheckIn in apps/api/src/scheduler/index.ts.",+ "kind": "metric",+ "detector_slugs": [+ "due-date-reminders",+ "project-webhook-reminders",+ "seat-reconciliation",+ "trial-reminders"+ ],+ "_comment_detector_slugs": "Slugs are the human-readable identifiers from the captureCheckIn calls. The provisioning script resolves these to numeric detector IDs via GET /api/0/organizations/{org}/monitors/.",+ "workflow": {+ "name": "Cron: missed check-in (any)",+ "enabled": true,+ "triggers": {+ "logicType": "any-short",+ "conditions": [+ {+ "type": "monitor_check_in_failure",+ "comparison": true+ }+ ],+ "actions": []+ },+ "actionFilters": []+ }+ },+ {+ "name": "Kaneo API: Slow p95 latency",+ "description": "p95 of transaction.duration > 1500ms in any 10-minute window on /api/* routes.",+ "kind": "metric",+ "project": "kaneo-api",+ "detector": {+ "name": "Kaneo API: Slow p95 latency detector",+ "description": "p95(transaction.duration) > 1500ms over 10 minutes",+ "type": "metric_issue",+ "config": {+ "detectionType": "static"+ },+ "dataSources": [+ {+ "dataset": "transactions",+ "query": "transaction.duration:>0 transaction:*/api/*",+ "queryType": 1,+ "aggregate": "p95(transaction.duration)",+ "timeWindow": 600,+ "environment": "production"+ }+ ],+ "workflows": []+ },+ "workflow": {+ "name": "Kaneo API: Slow p95 latency",+ "enabled": true,+ "triggers": {+ "logicType": "any-short",+ "conditions": [{ "type": "gt", "comparison": 1500 }],+ "actions": []+ },+ "actionFilters": []+ }+ },+ {+ "name": "Kaneo API: MCP error rate",+ "description": "MCP tool errors exceed 5% over a 1h window. Helps catch regressions before users do.",+ "kind": "metric",+ "project": "kaneo-api",+ "detector": {+ "name": "Kaneo API: MCP error rate detector",+ "description": "MCP error rate > 5% over 1 hour",+ "type": "metric_issue",+ "config": {+ "detectionType": "static"+ },+ "dataSources": [+ {+ "dataset": "transactions",+ "query": "transaction:*/api/mcp/* http.status_code:>=500",+ "queryType": 1,+ "aggregate": "failure_rate()",+ "timeWindow": 3600,+ "environment": "production"+ }+ ],+ "workflows": []+ },+ "workflow": {+ "name": "Kaneo API: MCP error rate",+ "enabled": true,+ "triggers": {+ "logicType": "any-short",+ "conditions": [{ "type": "gt", "comparison": 0.05 }],+ "actions": []+ },+ "actionFilters": []+ }+ },+ {+ "name": "Kaneo Web: New issue",+ "description": "New React ErrorBoundary or unhandled exception in kaneo-web.",+ "kind": "issue",+ "projects": ["kaneo-web"],+ "workflow": {+ "name": "Kaneo Web: New issue",+ "enabled": true,+ "triggers": {+ "logicType": "any-short",+ "conditions": [{ "type": "first_seen_event", "comparison": true }],+ "actions": []+ },+ "actionFilters": []+ }+ }+ ]+}