You are in AUTONOMOUS MODE. Do NOT ask questions. Do NOT pause for confirmation.
Execute every phase below in sequence, making decisions based on what you find.
============================================================
PHASE 0 — INPUT
$ARGUMENTS may contain:
- A monitoring stack:
prometheus, datadog, cloudwatch, newrelic, grafana
--instrument — add application-level metrics instrumentation to source code
--alerts-only — generate alerting rules without full dashboard setup
--slo — define and configure SLO/SLI targets with burn-rate alerts
- A specific focus:
latency, errors, traffic, saturation
- If no arguments, auto-detect existing monitoring and extend it, or default to Prometheus + Grafana
============================================================
PHASE 1 — INFRASTRUCTURE DETECTION
Scan for existing monitoring setup:
Prometheus ecosystem:
prometheus.yml, prometheus/ directory
alertmanager.yml, alertmanager/ directory
- Grafana dashboards:
grafana/, dashboards/, *.json with "panels" key
- Docker compose services named
prometheus, grafana, alertmanager
Cloud-native:
- AWS: CloudWatch references in Terraform,
aws_cloudwatch_* resources
- GCP: Cloud Monitoring,
google_monitoring_* resources
- Azure: Application Insights,
azurerm_monitor_* resources
Third-party:
- Datadog:
datadog.yaml, DD_* environment variables, datadog-agent in compose
- New Relic:
.newrelic.yml, NEW_RELIC_* env vars, newrelic in dependencies
- Sentry:
sentry.properties, SENTRY_DSN in env, @sentry/* in deps
Application stack:
- Node.js: check for
prom-client, express-prometheus-middleware, @opentelemetry/*
- Python: check for
prometheus_client, django-prometheus, opentelemetry-*
- Go: check for
prometheus/client_golang, go.opentelemetry.io
- Java: check for Micrometer, Spring Actuator
Infrastructure:
- Kubernetes: check for ServiceMonitor CRDs, Prometheus Operator
- Docker: check compose services for metrics endpoints
- Serverless: check for X-Ray, CloudWatch Logs
============================================================
PHASE 2 — METRICS DESIGN (Golden Signals)
Design metrics based on the Four Golden Signals:
1. Latency — time to service a request
http_request_duration_seconds (histogram)
- Buckets: 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10
- Track by: method, route, status_code
- Report P50, P90, P95, P99 percentiles
2. Traffic — demand on the system
http_requests_total (counter)
- Track by: method, route, status_code
- Report requests per second
3. Errors — rate of failed requests
http_errors_total (counter) — 5xx responses
http_client_errors_total (counter) — 4xx responses
- Error rate = errors / total requests
4. Saturation — how full the service is
- CPU utilization, memory usage
- Connection pool usage (database, Redis)
- Queue depth (if applicable)
- Event loop lag (Node.js)
- GC pause time (Java, Go)
============================================================
PHASE 3 — APPLICATION INSTRUMENTATION (if --instrument)
Add metrics middleware to the application:
Node.js (Express/Fastify):
- Install
prom-client dependency
- Create metrics middleware tracking
http_request_duration_seconds and http_requests_total
- Add
/metrics endpoint exposing Prometheus format
- Add default Node.js process metrics (memory, CPU, event loop)
Python (FastAPI/Django):
- Install
prometheus_client or prometheus-fastapi-instrumentator
- Expose
/metrics endpoint
- Add middleware for request duration tracking
Go:
- Add
promhttp.Handler() on /metrics
- Use
promauto for auto-registering metrics
- Add middleware using
promhttp.InstrumentHandlerDuration
Also add to the application:
- Health endpoints:
/health (liveness), /ready (readiness)
- Version endpoint:
/version returning app version and build info
- Structured logging: ensure logs are JSON-formatted with correlation IDs
============================================================
PHASE 4 — PROMETHEUS + GRAFANA SETUP
If using Prometheus stack, generate:
monitoring/prometheus/prometheus.yml:
- Global scrape interval: 15s, evaluation interval: 15s
- Rule files referencing
alerts/*.yml
- Scrape config targeting
app:{port} on /metrics with 10s interval
monitoring/prometheus/alerts/app.yml:
Alert rules (all with for duration to prevent flapping):
HighErrorRate: rate(http_errors_total[5m]) / rate(http_requests_total[5m]) > 0.01 for 5m (critical)
HighLatency: P99 > 2s for 5m (warning)
HighMemoryUsage: > 512MB for 10m (warning)
HighCPU: > 80% for 10m (warning)
DiskUsageHigh: > 80% for 5m (warning)
ServiceDown: up == 0 for 1m (critical)
monitoring/grafana/dashboards/app.json:
Grafana dashboard JSON with panels:
- Request Rate (by status code)
- Error Rate (percentage over time)
- Latency Distribution (heatmap)
- P50/P90/P99 Latency (time series)
- Active Connections (gauge)
- Memory Usage (time series)
- CPU Usage (time series)
- Saturation (connection pool, queue depth)
monitoring/grafana/provisioning/dashboards.yml: File-based dashboard provisioning.
Docker Compose (monitoring/docker-compose.monitoring.yml):
- Prometheus v2.51+ with 30d retention
- Grafana 10.4+ with provisioned dashboards and datasources
- Alertmanager v0.27+ for notification routing
- All with proper volume mounts and health checks
============================================================
PHASE 5 — CLOUD MONITORING (if Datadog/CloudWatch/New Relic)
Datadog:
- Generate
datadog.yaml agent config
- Add
dd-trace to application dependencies
- Configure APM, log collection, custom metrics
- Generate monitor definitions in JSON
CloudWatch:
- Generate Terraform for CloudWatch alarms, dashboards, log groups
- Configure metric filters on log groups
- Set up SNS topics for alarm notifications
New Relic:
- Generate
newrelic.yml configuration
- Add agent to application dependencies
- Configure custom dashboards via NR API (NRQL queries)
============================================================
PHASE 6 — SLO CONFIGURATION (if --slo)
Define SLOs based on service type:
- Availability SLO: 99.9% uptime (43.8 min/month error budget)
- Latency SLO: 95% of requests < 200ms, 99% < 1s
- Error SLO: < 0.1% error rate
Generate burn rate alerts:
- Fast burn (2%/hour): page immediately — requires human attention within minutes
- Slow burn (5%/day): ticket within 1 hour — investigate during business hours
============================================================
SELF-HEALING VALIDATION (max 2 iterations)
After completing deployment/infrastructure changes, validate:
- Verify all generated files are syntactically valid (YAML, JSON, HCL, Dockerfile).
- Run validation commands if available (terraform validate, docker build --check, kubectl dry-run).
- Verify no secrets, credentials, or sensitive values are hardcoded.
- If validation fails, diagnose and fix the specific syntax or config error.
- Repeat up to 2 iterations.
IF STILL FAILING after 2 iterations:
- Document what failed and the exact error
- Include partial output if available
============================================================
OUTPUT
## Monitoring Setup Complete
### Stack: {Prometheus + Grafana / Datadog / CloudWatch / New Relic}
### Files Created
{list of all generated files with one-line descriptions}
### Metrics Endpoints
- Application: http://localhost:{port}/metrics
- Prometheus: http://localhost:9090
- Grafana: http://localhost:3001 (admin/admin)
- Alertmanager: http://localhost:9093
### Alert Rules
| Alert | Condition | Severity |
|-------|-----------|----------|
| HighErrorRate | >1% for 5m | critical |
| HighLatency | P99 >2s for 5m | warning |
| HighMemory | >512MB for 10m | warning |
| DiskUsageHigh | >80% for 5m | warning |
| ServiceDown | down for 1m | critical |
### Dashboard Panels
{list of dashboard panels with their metric queries}
============================================================
NEXT STEPS
- Start monitoring stack:
docker compose -f monitoring/docker-compose.monitoring.yml up -d
- Verify metrics are being scraped: check Prometheus targets page at :9090/targets
- Configure alerting notification channels (Slack, PagerDuty, email) in Alertmanager
- Add application-specific custom metrics for business KPIs
- Set up log aggregation if not already configured (Loki, ELK)
- Review alert thresholds after 1 week of baseline data
============================================================
SELF-EVOLUTION TELEMETRY
After producing output, record execution metadata for the /evolve pipeline.
Check if a project memory directory exists:
- Look for the project path in
~/.claude/projects/
- If found, append to
skill-telemetry.md in that memory directory
Entry format:
### /monitoring — {{YYYY-MM-DD}}
- Outcome: {{SUCCESS | PARTIAL | FAILED}}
- Self-healed: {{yes — what was healed | no}}
- Iterations used: {{N}} / {{N max}}
- Bottleneck: {{phase that struggled or "none"}}
- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
Only log if the memory directory exists. Skip silently if not found.
Keep entries concise — /evolve will parse these for skill improvement signals.
============================================================
DO NOT
- Do NOT set alert thresholds too aggressively — avoid alert fatigue
- Do NOT expose Prometheus/Grafana ports publicly without authentication
- Do NOT store Grafana admin passwords in plain text in committed files
- Do NOT use
rate() on gauges — use rate() only on counters and histograms
- Do NOT create alerts without
for duration — always require sustained condition
- Do NOT use high-cardinality labels (user IDs, request IDs) in Prometheus metrics
- Do NOT scrape more frequently than every 10s without good reason
- Do NOT overwrite existing monitoring configs — extend them
- Do NOT add instrumentation that significantly impacts application performance
1---2name: monitoring3description: Set up application observability with Prometheus, Grafana, Datadog, or CloudWatch — instrument metrics endpoints, configure Golden Signal dashboards, define alert rules with burn-rate SLOs, and add structured logging4---56You are in AUTONOMOUS MODE. Do NOT ask questions. Do NOT pause for confirmation.7Execute every phase below in sequence, making decisions based on what you find.89============================================================10PHASE 0 — INPUT11============================================================1213$ARGUMENTS may contain:14- A monitoring stack: `prometheus`, `datadog`, `cloudwatch`, `newrelic`, `grafana`15- `--instrument` — add application-level metrics instrumentation to source code16- `--alerts-only` — generate alerting rules without full dashboard setup17- `--slo` — define and configure SLO/SLI targets with burn-rate alerts18- A specific focus: `latency`, `errors`, `traffic`, `saturation`19- If no arguments, auto-detect existing monitoring and extend it, or default to Prometheus + Grafana2021============================================================22PHASE 1 — INFRASTRUCTURE DETECTION23============================================================2425Scan for existing monitoring setup:2627**Prometheus ecosystem**:28- `prometheus.yml`, `prometheus/` directory29- `alertmanager.yml`, `alertmanager/` directory30- Grafana dashboards: `grafana/`, `dashboards/`, `*.json` with `"panels"` key31- Docker compose services named `prometheus`, `grafana`, `alertmanager`3233**Cloud-native**:34- AWS: CloudWatch references in Terraform, `aws_cloudwatch_*` resources35- GCP: Cloud Monitoring, `google_monitoring_*` resources36- Azure: Application Insights, `azurerm_monitor_*` resources3738**Third-party**:39- Datadog: `datadog.yaml`, `DD_*` environment variables, `datadog-agent` in compose40- New Relic: `.newrelic.yml`, `NEW_RELIC_*` env vars, `newrelic` in dependencies41- Sentry: `sentry.properties`, `SENTRY_DSN` in env, `@sentry/*` in deps4243**Application stack**:44- Node.js: check for `prom-client`, `express-prometheus-middleware`, `@opentelemetry/*`45- Python: check for `prometheus_client`, `django-prometheus`, `opentelemetry-*`46- Go: check for `prometheus/client_golang`, `go.opentelemetry.io`47- Java: check for Micrometer, Spring Actuator4849**Infrastructure**:50- Kubernetes: check for ServiceMonitor CRDs, Prometheus Operator51- Docker: check compose services for metrics endpoints52- Serverless: check for X-Ray, CloudWatch Logs5354============================================================55PHASE 2 — METRICS DESIGN (Golden Signals)56============================================================5758Design metrics based on the Four Golden Signals:5960**1. Latency** — time to service a request61- `http_request_duration_seconds` (histogram)62- Buckets: 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 1063- Track by: method, route, status_code64- Report P50, P90, P95, P99 percentiles6566**2. Traffic** — demand on the system67- `http_requests_total` (counter)68- Track by: method, route, status_code69- Report requests per second7071**3. Errors** — rate of failed requests72- `http_errors_total` (counter) — 5xx responses73- `http_client_errors_total` (counter) — 4xx responses74- Error rate = errors / total requests7576**4. Saturation** — how full the service is77- CPU utilization, memory usage78- Connection pool usage (database, Redis)79- Queue depth (if applicable)80- Event loop lag (Node.js)81- GC pause time (Java, Go)8283============================================================84PHASE 3 — APPLICATION INSTRUMENTATION (if --instrument)85============================================================8687Add metrics middleware to the application:8889**Node.js (Express/Fastify)**:90- Install `prom-client` dependency91- Create metrics middleware tracking `http_request_duration_seconds` and `http_requests_total`92- Add `/metrics` endpoint exposing Prometheus format93- Add default Node.js process metrics (memory, CPU, event loop)9495**Python (FastAPI/Django)**:96- Install `prometheus_client` or `prometheus-fastapi-instrumentator`97- Expose `/metrics` endpoint98- Add middleware for request duration tracking99100**Go**:101- Add `promhttp.Handler()` on `/metrics`102- Use `promauto` for auto-registering metrics103- Add middleware using `promhttp.InstrumentHandlerDuration`104105Also add to the application:106- **Health endpoints**: `/health` (liveness), `/ready` (readiness)107- **Version endpoint**: `/version` returning app version and build info108- **Structured logging**: ensure logs are JSON-formatted with correlation IDs109110============================================================111PHASE 4 — PROMETHEUS + GRAFANA SETUP112============================================================113114If using Prometheus stack, generate:115116**`monitoring/prometheus/prometheus.yml`**:117- Global scrape interval: 15s, evaluation interval: 15s118- Rule files referencing `alerts/*.yml`119- Scrape config targeting `app:{port}` on `/metrics` with 10s interval120121**`monitoring/prometheus/alerts/app.yml`**:122Alert rules (all with `for` duration to prevent flapping):123- `HighErrorRate`: `rate(http_errors_total[5m]) / rate(http_requests_total[5m]) > 0.01` for 5m (critical)124- `HighLatency`: P99 > 2s for 5m (warning)125- `HighMemoryUsage`: > 512MB for 10m (warning)126- `HighCPU`: > 80% for 10m (warning)127- `DiskUsageHigh`: > 80% for 5m (warning)128- `ServiceDown`: `up == 0` for 1m (critical)129130**`monitoring/grafana/dashboards/app.json`**:131Grafana dashboard JSON with panels:1321. Request Rate (by status code)1332. Error Rate (percentage over time)1343. Latency Distribution (heatmap)1354. P50/P90/P99 Latency (time series)1365. Active Connections (gauge)1376. Memory Usage (time series)1387. CPU Usage (time series)1398. Saturation (connection pool, queue depth)140141**`monitoring/grafana/provisioning/dashboards.yml`**: File-based dashboard provisioning.142143**Docker Compose** (`monitoring/docker-compose.monitoring.yml`):144- Prometheus v2.51+ with 30d retention145- Grafana 10.4+ with provisioned dashboards and datasources146- Alertmanager v0.27+ for notification routing147- All with proper volume mounts and health checks148149============================================================150PHASE 5 — CLOUD MONITORING (if Datadog/CloudWatch/New Relic)151============================================================152153**Datadog**:154- Generate `datadog.yaml` agent config155- Add `dd-trace` to application dependencies156- Configure APM, log collection, custom metrics157- Generate monitor definitions in JSON158159**CloudWatch**:160- Generate Terraform for CloudWatch alarms, dashboards, log groups161- Configure metric filters on log groups162- Set up SNS topics for alarm notifications163164**New Relic**:165- Generate `newrelic.yml` configuration166- Add agent to application dependencies167- Configure custom dashboards via NR API (NRQL queries)168169============================================================170PHASE 6 — SLO CONFIGURATION (if --slo)171============================================================172173Define SLOs based on service type:174175- **Availability SLO**: 99.9% uptime (43.8 min/month error budget)176- **Latency SLO**: 95% of requests < 200ms, 99% < 1s177- **Error SLO**: < 0.1% error rate178179Generate burn rate alerts:180- Fast burn (2%/hour): page immediately — requires human attention within minutes181- Slow burn (5%/day): ticket within 1 hour — investigate during business hours182183184============================================================185SELF-HEALING VALIDATION (max 2 iterations)186============================================================187188After completing deployment/infrastructure changes, validate:1891901. Verify all generated files are syntactically valid (YAML, JSON, HCL, Dockerfile).1912. Run validation commands if available (terraform validate, docker build --check, kubectl dry-run).1923. Verify no secrets, credentials, or sensitive values are hardcoded.1934. If validation fails, diagnose and fix the specific syntax or config error.1945. Repeat up to 2 iterations.195196IF STILL FAILING after 2 iterations:197- Document what failed and the exact error198- Include partial output if available199200============================================================201OUTPUT202============================================================203204```205## Monitoring Setup Complete206207### Stack: {Prometheus + Grafana / Datadog / CloudWatch / New Relic}208209### Files Created210{list of all generated files with one-line descriptions}211212### Metrics Endpoints213- Application: http://localhost:{port}/metrics214- Prometheus: http://localhost:9090215- Grafana: http://localhost:3001 (admin/admin)216- Alertmanager: http://localhost:9093217218### Alert Rules219| Alert | Condition | Severity |220|-------|-----------|----------|221| HighErrorRate | >1% for 5m | critical |222| HighLatency | P99 >2s for 5m | warning |223| HighMemory | >512MB for 10m | warning |224| DiskUsageHigh | >80% for 5m | warning |225| ServiceDown | down for 1m | critical |226227### Dashboard Panels228{list of dashboard panels with their metric queries}229```230231============================================================232NEXT STEPS233============================================================2342351. Start monitoring stack: `docker compose -f monitoring/docker-compose.monitoring.yml up -d`2362. Verify metrics are being scraped: check Prometheus targets page at :9090/targets2373. Configure alerting notification channels (Slack, PagerDuty, email) in Alertmanager2384. Add application-specific custom metrics for business KPIs2395. Set up log aggregation if not already configured (Loki, ELK)2406. Review alert thresholds after 1 week of baseline data241242243============================================================244SELF-EVOLUTION TELEMETRY245============================================================246247After producing output, record execution metadata for the /evolve pipeline.248249Check if a project memory directory exists:250- Look for the project path in `~/.claude/projects/`251- If found, append to `skill-telemetry.md` in that memory directory252253Entry format:254```255### /monitoring — {{YYYY-MM-DD}}256- Outcome: {{SUCCESS | PARTIAL | FAILED}}257- Self-healed: {{yes — what was healed | no}}258- Iterations used: {{N}} / {{N max}}259- Bottleneck: {{phase that struggled or "none"}}260- Suggestion: {{one-line improvement idea for /evolve, or "none"}}261```262263Only log if the memory directory exists. Skip silently if not found.264Keep entries concise — /evolve will parse these for skill improvement signals.265266============================================================267DO NOT268============================================================269270- Do NOT set alert thresholds too aggressively — avoid alert fatigue271- Do NOT expose Prometheus/Grafana ports publicly without authentication272- Do NOT store Grafana admin passwords in plain text in committed files273- Do NOT use `rate()` on gauges — use `rate()` only on counters and histograms274- Do NOT create alerts without `for` duration — always require sustained condition275- Do NOT use high-cardinality labels (user IDs, request IDs) in Prometheus metrics276- Do NOT scrape more frequently than every 10s without good reason277- Do NOT overwrite existing monitoring configs — extend them278- Do NOT add instrumentation that significantly impacts application performance