diff --git a/promptbook/prompts.json b/promptbook/prompts.json index e450afc..b1f54f5 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -614,6 +614,27 @@ ], "formatNotes": "All three. Point the tool at the Jenkinsfile, any shared-library `vars/*.groovy` it loads, and the scripts its `sh` steps call; list credential IDs only, never secret values. Copilot: jenkins-pipeline path instructions plus those files in agent mode. Claude Code: the jenkins-declarative-pipeline-guardrails skill plus the Jenkinsfile. Codex: AGENTS.md Jenkins section, then the diff.", "body": "Task: Review and harden the Jenkins pipeline I specify. Keep it Declarative, move heavy logic out of Groovy, make every run bounded and reproducible, and make sure no credential can leak — then give me a minimal diff I can open as a PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Pipeline file: {{JENKINSFILE_PATH}} (usually `Jenkinsfile`)\n- Job type: {{JOB_TYPE}} (multibranch | pipeline | organization-folder)\n- Build stack: {{BUILD_STACK}} (maven | gradle | docker | python | other)\n- Agents available: {{AGENTS}} (labels, Kubernetes pod templates, or \"unknown\")\n- Shared libraries: {{LIBRARIES}} (names and versions, or \"none\")\n- Credential IDs in use: {{CREDENTIAL_IDS}} (IDs only — never paste secret values)\n- Deploy targets: {{DEPLOY_TARGETS}} (e.g. aks-dev, aks-prod, artifact-repo, none)\n- Pain points: {{PAIN}} (hangs | slow | flaky | controller-load | secret-exposure | none)\n\nRequirements:\n\n1. Inventory\n - Read {{JENKINSFILE_PATH}} end to end: agent declarations, `options`, `environment`, every stage, `when` conditions, `script {}` blocks, `input` steps, `parallel`/`matrix`, `post`\n - List each credential binding, how the secret is referenced, and which stages can see it\n - List shared libraries and the version each is loaded at, plus any `Jenkins.instance` or other internal API use\n - Note how fork PRs are treated if {{JOB_TYPE}} is multibranch\n\n2. Findings (rank by risk: secret exposure > untrusted code with credentials > controller load > unbounded runs > reproducibility > hygiene)\n - Groovy-interpolated secrets (`\"${TOKEN}\"` inside `sh`), echoed secrets, `set -x` around secrets, secrets written to the workspace\n - Builds that can run on the controller, `agent any` without labels, unpinned images or tools\n - Large `script {}` blocks, Groovy JSON/XML parsing, loops of tiny `sh` calls\n - Missing `timeout`, `buildDiscarder`, `timestamps`, or concurrency policy\n - `input` holding an agent; deploys without `lock`/`milestone`; `if` logic that should be `when { ... beforeAgent true }`\n - Unpinned `@Library` refs, overridden built-in steps, sandbox bypasses\n - Missing `post` publishing (tests, artifacts with fingerprints) and workspace cleanup\n\n3. Fix\n - Declarative structure with `agent none` at the top only if every stage declares its own agent; otherwise one labelled agent or pod template\n - Move heavy logic into scripts (`scripts/ci/*.sh`) or build-tool goals ({{BUILD_STACK}}: e.g. `./mvnw -B -ntp verify`)\n - Top-level `options { timeout(...); buildDiscarder(logRotator(...)); timestamps(); disableConcurrentBuilds(abortPrevious: true) }` — adjust stage timeouts knowing they include agent provisioning when the agent is stage-level\n - Bind credentials per stage with `withCredentials` or `credentials()`; reference them only inside single-quoted `sh` strings\n - Approval stages: `agent none`, `input` with `timeout`, and `lock`/`milestone` on deploys to {{DEPLOY_TARGETS}}\n - Pin `@Library` to a tag or commit; replace `Jenkins.instance` use with a supported step or flag it for a plugin\n - `post { always { junit ...; archiveArtifacts ... fingerprint: true } cleanup { cleanWs() } }`\n - Keep deploy credentials out of PR and fork builds\n\n4. Verification\n - Run the Declarative linter (`jenkins-cli declarative-linter` or the validate endpoint) and include its output\n - Run on a branch build and, for multibranch, a PR build; compare duration and queue time with recent builds\n - Confirm in the console log that secrets show as masked and are never printed by a step\n - List anything that needs a Jenkins admin (plugins, credential scope, fork trust settings, agent templates)\n\nConstraints:\n- Minimal diff; keep stage names and artifacts unless a rename is needed for clarity.\n- Do not invent credential IDs, agent labels, image names, or URLs — use placeholders if unknown.\n- Never print or request secret values; refer to credentials by ID only.\n- Do not change what gets built or deployed; behaviour stays the same except for the safety fixes.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete Jenkinsfile diff and a checklist.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (Jenkinsfile diff plus any new scripts)\n3. Before/after: run duration, queue time, controller-side `script` lines, credentials scope per stage\n4. Admin follow-ups and residual risks\n\nStart from {{JENKINSFILE_PATH}}. Fix secret handling before anything else." + }, + { + "id": "wire-spring-micrometer-prometheus", + "title": "Wire Spring Boot Micrometer Prometheus Metrics", + "whenToUse": "Add or harden Micrometer Prometheus metrics on a Spring Boot service (RED/SLI histograms, cardinality-safe tags, management-port scrape) and produce a minimal config/code/manifest diff with a verification checklist.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "micrometer", + "prometheus", + "observability", + "metrics", + "aks", + "java" + ], + "formatNotes": "All three. Point the tool at `application.yml`/`application.properties`, Meter/Metrics config, the build file, and any ServiceMonitor/PodMonitor or Prometheus annotation manifests; keep Actuator security changes aligned with spring-boot-actuator-hardening. Copilot: spring-micrometer-prometheus path instructions plus those files in agent mode. Claude Code: the spring-boot-micrometer-prometheus-guardrails skill plus the config and scrape manifests. Codex: AGENTS.md Micrometer section, then the diff.", + "body": "Task: Wire or harden Micrometer + Prometheus metrics for the Spring Boot service I specify. Deliver RED-ready histograms, cardinality-safe tags, and a private management-port scrape path — then give me a minimal diff I can open as a PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- App module / root: {{APP_PATH}}\n- Spring Boot version: {{BOOT_VERSION}} (2.x | 3.x | unknown)\n- Build tool: {{BUILD_TOOL}} (maven | gradle)\n- Current Actuator exposure: {{ACTUATOR_EXPOSURE}} (e.g. health,info | include=* | unknown)\n- Management port today: {{MANAGEMENT_PORT}} (number | same-as-server | unknown)\n- Scrape style: {{SCRAPE_STYLE}} (servicemonitor | podmonitor | pod-annotations | none | unknown)\n- Cluster / env: {{ENVIRONMENT}} (e.g. aks-dev, aks-prod)\n- Service name for tags: {{SERVICE_NAME}}\n- Latency SLO targets (optional): {{SLO_BUCKETS_MS}} (e.g. 100,250,500,1000,2500,5000)\n- Pain points: {{PAIN}} (no-percentiles | cardinality | scrape-404 | public-actuator | missing-red | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file and `application*.yml|properties` for Actuator, Micrometer, and management server settings\n - List existing meters (`MeterRegistry` beans, `@Timed`, Observations) and any custom tags\n - Locate scrape manifests or annotations under deploy/Helm paths; note whether scrape hits the public or management port\n - Note overlap with Actuator security config (do not weaken lockdown)\n\n2. Findings (rank by risk: public sensitive Actuator > unbounded cardinality > scrape on public Ingress > missing histograms > hygiene)\n - `include=*` or sensitive endpoints exposed alongside prometheus\n - Raw URI / user id / exception message labels\n - Summaries without histogram buckets where p95/p99 or SLO burn is required\n - Scrape targeting the public Service/Ingress\n - Missing common tags (`application`, `environment`)\n - Custom meters with unbounded label values\n\n3. Fix\n - Dependencies: ensure `spring-boot-starter-actuator` and `micrometer-registry-prometheus` for {{BUILD_TOOL}}\n - Config: separate `management.server.port` when the app has a public HTTP surface; `management.endpoints.web.exposure.include=health,prometheus` (add `info` only if safe); set `management.metrics.tags.application={{SERVICE_NAME}}` and `management.metrics.tags.environment={{ENVIRONMENT}}`\n - HTTP server metrics: enable percentile-histogram (or distribution SLO deadlines / buckets from {{SLO_BUCKETS_MS}}) for `http.server.requests` so Prometheus can compute percentiles\n - Cardinality: ensure URI tags use route templates; strip or deny tags that carry ids or free text; rewrite custom meters to bounded enums\n - Scrape: for {{SCRAPE_STYLE}}, point path at `/actuator/prometheus` (honor any `management.endpoints.web.base-path`) on the **management** port; Prefer ServiceMonitor/PodMonitor selectors over scraping Ingress. Keep changes surgical — no full Helm rewrite unless required\n - Security: keep Actuator lockdown consistent with spring-boot-actuator-hardening; if scrape needs auth, document the platform mechanism without inventing secrets in Git\n - Do not invent OTel collectors or logging pipelines here — link to otel-aks-observability / structured-logging if gaps exist\n\n4. Verification\n - Show sample lines from `/actuator/prometheus` for `http_server_requests_*` including bucket series and common tags\n - Provide PromQL sketches: request rate, 5xx error ratio, `histogram_quantile(0.95, ...)` (and 0.99 if useful)\n - Confirm scrape config targets management port; note NetworkPolicy / private Service expectations for {{ENVIRONMENT}}\n - List residual risks (auth on management, bucket fit to SLO, remaining high-cardinality candidates)\n\nConstraints:\n- Minimal diff; do not refactor unrelated config or open extra Actuator endpoints.\n- Do not invent cluster URLs, credential values, or Helm chart names — use placeholders if unknown.\n- Do not put PII or secrets into metric tags or `info`.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete diffs and a checklist.\n- Metrics lane only; defer traces and log shipping to their skills.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (build + application config + meter/tag fixes + scrape manifest/annotations)\n3. Verification: sample prometheus text, PromQL, scrape target summary\n4. Residual risks and follow-ups (Actuator auth, OTel, logging)\n\nStart from {{APP_PATH}}. Fix public Actuator exposure and unbounded labels before polishing dashboards.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index 26e72c1..db4e3d9 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -612,6 +612,27 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/jenkins-pipeline.instructions.md` with applyTo for pipeline code (`**/Jenkinsfile`, `**/*.jenkinsfile`, `**/vars/*.groovy`, `**/src/**/*.groovy`, `**/jenkins/**/*.yaml`) (optional `.github/skills/jenkins-declarative-pipeline-guardrails/SKILL.md`). Claude Code: `.claude/skills/jenkins-declarative-pipeline-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that pipeline Groovy runs on the controller, so script blocks stay tiny and credentials are never Groovy-interpolated. Codex: a Jenkins section in root `AGENTS.md` or a nested `AGENTS.md` beside the shared library. Pair with bash-script-hardening-guardrails for the scripts the pipeline calls and gha-devsecops-pipeline if the repo also runs GitHub Actions.", "body": "# Skill: Jenkins Declarative Pipeline Guardrails\n\n## Goal\nKeep Jenkinsfiles short, predictable, and safe: Declarative syntax as thin glue, real build logic in scripts and build tools, ephemeral agents, bounded runs, secrets that never leak into logs or Groovy strings, and pinned shared libraries — so the controller stays healthy and every build can be reproduced.\n\n## When to apply\n- Writing a new `Jenkinsfile` or converting a freestyle / Scripted job to Declarative\n- Reviews that add stages, `script {}` blocks, credentials, `input` gates, `parallel`/`matrix`, or a new `@Library`\n- Builds that hang, queue forever, fill the controller disk, or slow the whole Jenkins instance\n- Moving builds from static VMs to Kubernetes pod agents (for example on AKS)\n- Someone asks for a script approval or wants to call `Jenkins.instance` from a pipeline\n\n## Baseline rules\n1. **Pipeline as code, Declarative first.** The `Jenkinsfile` lives in the repo next to the code and is reviewed like code. Use Declarative `pipeline {}`; keep `script {}` blocks to a few lines and move anything bigger into a versioned shared library or a shell script.\n2. **Groovy is glue, not the build.** Pipeline Groovy runs on the controller. Put compilation, tests, packaging, and parsing in `sh` steps that call scripts or build tools (`./mvnw -B -ntp verify`, `make`, `./scripts/deploy.sh`). Combine many tiny `sh` calls into one script; avoid `JsonSlurper`/`XmlSlurper`, big loops, and file processing in Groovy — use `readJSON`/`readYaml` (Pipeline Utility Steps) or do it in the script.\n3. **Never build on the controller.** The built-in node has zero executors. Select agents by explicit `label`, or define a pod template / container image per stage. Prefer ephemeral agents (Kubernetes or cloud agents) so every build starts clean and nothing persists between jobs.\n4. **Pin the toolchain.** Use container images pinned by tag or digest, or `tools { jdk 'jdk-21'; maven 'maven-3.9' }` with names that map to fixed versions. Commit the Maven/Gradle wrapper. No \"latest\" images and no reliance on whatever happens to be installed on an agent.\n5. **Bound every run.** Top-level `options {}` sets `timeout(...)`, `buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))`, `timestamps()`, and `disableConcurrentBuilds(abortPrevious: true)` for branch/PR jobs. Remember a stage-level timeout with a stage-level agent includes agent provisioning time — size it accordingly.\n6. **Secrets through bindings only.** Use `withCredentials([...])` or `environment { X = credentials('id') }`, scoped to the narrowest stage. Reference secrets inside single-quoted shell strings (`sh 'curl -u \"$USER:$PASS\" ...'`) so the shell expands them, never Groovy string interpolation (`\"${PASS}\"`). No `echo` of secrets, no `set -x` around them, no writing them into the workspace or artifacts. Store credentials at folder scope, not global.\n7. **Don't punch holes in the sandbox.** No `Jenkins.instance` / internal Jenkins APIs in Jenkinsfiles or libraries, no script approvals that bypass the Groovy sandbox, and no shared-library code that overrides built-in steps like `sh` or `timeout`. If a Jenkins API is truly needed, it belongs in a small reviewed plugin.\n8. **Pin shared libraries.** Load with `@Library('team-lib@v2.3.1') _` (a tag or commit), not a moving branch. Libraries are small, tested (for example with JenkinsPipelineUnit), and versioned like any other dependency.\n9. **Gates don't hold executors.** `input` (approvals) runs with `agent none` on that stage plus its own `timeout`, so nobody's approval holds a build agent. Use `when { branch 'main' }`, `when { changeRequest() }`, or `when { tag ... }` with `beforeAgent true` instead of `if` logic inside steps. Guard deploys with `lock` and `milestone` so older builds cannot overtake newer ones.\n10. **Parallelism with intent.** Use `parallel` or `matrix` for independent work, `failFast true` when one failure makes the rest pointless, and `stash`/`unstash` only for small artifacts — publish big ones to an artifact repository.\n11. **Always report and clean up.** `post { always { junit ...; archiveArtifacts artifacts: '...', fingerprint: true, allowEmptyArchive: true } cleanup { cleanWs() } }`. Test results are published even when the build fails; failure notifications go to the owning team, not everyone.\n12. **Untrusted changes get untrusted treatment.** Multibranch / PR jobs from forks must not run a modified `Jenkinsfile` with access to deploy credentials; use the trust settings so fork PRs use the target branch's Jenkinsfile, and keep deploy credentials off PR builds entirely.\n13. **Lint before merge.** Validate the Jenkinsfile with the Declarative linter (`jenkins-cli declarative-linter` or the pipeline-model-converter validate endpoint) or a Jenkinsfile Runner check in CI. Pipeline fixes go through a PR, not ad-hoc Replay edits that never reach the repo.\n\n## Workflow\n1. Inventory: current `Jenkinsfile`, shared libraries and versions, agent labels or pod templates, credentials IDs used, plugins relied on, and the slowest/most flaky stages from recent builds.\n2. Map stages to responsibilities (checkout, build, test, scan, package, publish, deploy) and move heavy logic into scripts or build-tool goals.\n3. Apply the rules above in order: agents and toolchain → options/bounds → credentials → `when`/gates → parallelism → post/cleanup → library pinning.\n4. Lint the result, run it on a branch (and on a PR from a branch, if multibranch), and compare duration and queue time to previous builds.\n5. PR notes: stage diagram, credentials touched (by ID only), agent/image changes, timeouts chosen, and anything that still needs a Jenkins admin (plugins, credential scope, trust settings).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/jenkins-pipeline.instructions.md` with `applyTo` for pipeline code (for example `**/Jenkinsfile`, `**/*.jenkinsfile`, `**/vars/*.groovy`, `**/src/**/*.groovy`, `**/jenkins/**/*.yaml`).\n- Always-on line in `.github/copilot-instructions.md`: \"Jenkinsfiles are Declarative glue: logic in scripts, agents by label or pod template, timeouts on every run, secrets via withCredentials in single-quoted sh only.\"\n- Optional `.github/skills/jenkins-declarative-pipeline-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/jenkins-declarative-pipeline-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Pipeline Groovy runs on the controller: keep `script {}` tiny, never interpolate credentials in Groovy strings, pin `@Library` versions.\"\n- Before claiming done, show the linter result and the final `options`, `agent`, and credential-binding blocks.\n\n### Codex\n- A Jenkins section in root `AGENTS.md`, or a nested `AGENTS.md` beside the shared library (or linked `docs/agents/jenkins-pipeline.md`).\n- State: how to lint the Jenkinsfile, which agent labels / pod templates exist, the approved credential IDs, banned patterns (Groovy-interpolated secrets, `Jenkins.instance`, unpinned libraries, builds on the controller), and the required `post` block.\n\n## Anti-patterns\n- `agent any` on a controller that still has executors\n- 300-line `script {}` blocks doing JSON parsing and loops on the controller\n- `sh \"curl -H 'Authorization: Bearer ${TOKEN}' ...\"` (Groovy interpolation of a secret)\n- `input` inside a stage that holds an agent for days\n- No `timeout`, no `buildDiscarder`, and a controller disk full of old artifacts\n- `@Library('team-lib@main')` or implicit-load libraries nobody reviews\n- Script approvals granted to make `Jenkins.instance` work\n- Fork PRs running a modified Jenkinsfile with production credentials in scope\n- Fixing pipelines with Replay and never committing the change\n\n## Verification checklist\n- [ ] Declarative syntax; `script {}` blocks small and justified\n- [ ] Heavy logic lives in scripts or build-tool goals\n- [ ] No builds on the controller; agents by label or pinned pod template/image\n- [ ] `timeout`, `buildDiscarder`, `timestamps`, and concurrency policy set\n- [ ] Credentials bound per stage; no Groovy-interpolated secrets; nothing echoed\n- [ ] Shared libraries pinned to a tag or commit; no sandbox bypasses\n- [ ] Approval gates use `agent none` + timeout; deploys guarded by `lock`/`milestone`\n- [ ] `post` publishes tests/artifacts and runs `cleanWs()`\n- [ ] Fork PRs cannot reach deploy credentials\n- [ ] Jenkinsfile passes the Declarative linter\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: jenkins-declarative-pipeline-guardrails\ndescription: Use when writing or reviewing a Jenkinsfile or Jenkins shared library — new stages, credentials, approvals, agents, or slow/hanging builds. Keep Declarative pipelines as thin glue with bounded runs, safe credential bindings, and pinned libraries.\n---\n\nFollow Jenkins Declarative Pipeline Guardrails: Declarative first with tiny script blocks, build logic in scripts and build tools, no builds on the controller, pinned agents and toolchains, timeout and buildDiscarder on every run, credentials via withCredentials in single-quoted sh, no sandbox bypasses, pinned @Library versions, approvals that don't hold agents, post blocks that publish results and clean the workspace, and a lint check before merge.\n```" + }, + { + "id": "spring-boot-micrometer-prometheus-guardrails", + "title": "Spring Boot Micrometer Prometheus Guardrails", + "whenToUse": "Wiring or reviewing Micrometer metrics and a Prometheus scrape for a Spring Boot service — actuator prometheus registry, RED/SLI histograms, cardinality control, common tags, and AKS scrape hygiene (often paired with Actuator lockdown).", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "micrometer", + "prometheus", + "observability", + "metrics", + "aks", + "java" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-micrometer-prometheus.instructions.md` with applyTo for `**/application*.{yml,yaml,properties}`, `**/*Meter*Config*.java`, `**/*Metrics*.java`, `**/pom.xml`/`**/build.gradle*`, and scrape manifests (`**/servicemonitor*.yaml`, `**/podmonitor*.yaml`, `**/values*.yaml`). Optional `.github/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md`. Claude Code: `.claude/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md` plus a CLAUDE.md fact that URI templates (not raw paths) and bounded labels keep Prometheus cardinality safe. Codex: a Micrometer/Prometheus section in root `AGENTS.md` or nested `src/main/AGENTS.md`. Pair with spring-boot-actuator-hardening for endpoint lockdown; otel-aks-observability and spring-boot-structured-logging-guardrails for traces/logs — this skill owns metrics design and scrape hygiene only.", + "body": "# Skill: Spring Boot Micrometer Prometheus Guardrails\n\n## Goal\nShip durable RED/SLI metrics from Spring Boot via Micrometer's Prometheus registry: histograms that support p95/p99 and SLO burn alerts, low and stable cardinality, clear common tags, and a scrape path that works on AKS — without turning `/actuator` into a public dump of secrets or exploding Prometheus series count.\n\n## When to apply\n- New Spring Boot 2.x/3.x services adding `micrometer-registry-prometheus` (or reviewing an existing scrape)\n- Reviews of `management.metrics.*`, `management.endpoints.web.exposure`, or HTTP server timer buckets\n- AKS / Kubernetes workloads that need ServiceMonitor, PodMonitor, or annotation-based Prometheus scrape\n- Dashboards or alerts that cannot compute latency percentiles, or Prometheus cardinality alerts firing\n- Custom business meters about to take unbounded label values (user id, order id, exception message, raw URI)\n\n## Baseline rules\n1. **Prometheus registry on Actuator, not on the public API surface by accident.** Add `spring-boot-starter-actuator` and `micrometer-registry-prometheus`. Expose `prometheus` (and usually `health`) on the management endpoints. Prefer a separate `management.server.port` so scrapes and probes never share the user-facing listener. Security lockdown of Actuator belongs in **spring-boot-actuator-hardening** — reference it; do not re-open `env` / `heapdump` / `include=*`.\n2. **Expose only what the scraper needs.** Typical production include set: `health,prometheus` (add `info` only if it carries no secrets). Keep `metrics` JSON endpoint off public/management exposure unless authenticated ops tooling needs it. Never ship `include=*`.\n3. **Common tags on every series.** Set `management.metrics.tags.application` (service name) and `management.metrics.tags.environment` (or equivalent) so PromQL can filter by service and env without relying on scrape job labels alone. Keep the tag set small and stable across the fleet.\n4. **Cardinality is a product decision.** Use route / URI **templates** (`/api/orders/{id}`), never raw path params, query strings, user ids, session ids, or free-text exception messages as label values. Prefer Spring MVC / WebFlux's built-in `http.server.requests` tagging (method, uri template, status, outcome, exception class name only when bounded). Cap or deny custom tags that can grow without bound.\n5. **RED first: Rate, Errors, Duration.** Drive dashboards and alerts from `http.server.requests`: request rate, 5xx (and optionally 4xx where product-defined) error ratio, and latency percentiles from **histograms** — not from sparse summary snapshots alone. Enable percentile-histogram (or explicit SLO buckets) for `http.server.requests` so Prometheus can compute `histogram_quantile` for p95/p99 and multi-window burn rates.\n6. **Choose histogram buckets for your SLOs.** Default Micrometer/Prometheus buckets are a starting point; override with service-appropriate SLO boundaries (for example 50ms / 100ms / 250ms / 500ms / 1s / 2.5s / 5s / 10s for an HTTP API). Document the SLO the buckets support. Avoid enabling every timer as a full histogram — prefer HTTP server and a few critical outbound/client timers.\n7. **Custom business meters stay bounded.** Counters and timers for domain events use a fixed vocabulary of labels (status enum, payment method enum, region code). Never put customer id, email, free-text reason, or stack-trace snippets on labels. Prefer exemplars / traces for per-request drill-down (see **otel-aks-observability**).\n8. **Client and dependency timers, carefully.** Instrument outbound HTTP, JDBC, messaging with Micrometer Observation or existing binders, but apply the same URI-template and bounded-tag rules. Prefer one meter name per dependency with a `client`/`peer` tag rather than a new meter name per endpoint.\n9. **AKS scrape hygiene (light touch).** Prefer scraping the **management port** only: NetworkPolicy / Service that exposes management to the Prometheus namespace (or private scrape network), not to the Ingress. Use Prometheus Operator `ServiceMonitor` / `PodMonitor` with `path: /actuator/prometheus` (or your management base-path), the management port name, and sensible scrape / timeout intervals. Pod annotations (`prometheus.io/scrape`, `prometheus.io/port`, `prometheus.io/path`) are fine for simpler clusters — keep them pointed at management, not the public container port. Do not require a full Helm rewrite for a metrics PR.\n10. **Auth and network for scrape.** If the management port is reachable beyond the scrape mesh, require auth or mTLS consistent with platform standards; otherwise keep it ClusterIP-private and NetworkPolicy-restricted. Do not put bearer tokens in Git — use platform secrets / workload identity patterns already approved for the cluster.\n11. **Naming and units.** Stick to Micrometer naming (dot-separated names become Prometheus `snake_case` with `_total` / `_seconds` / `_bucket` suffixes). Prefer base units (seconds, bytes). Do not invent parallel metric names for the same signal.\n12. **Pair the three pillars, don't duplicate them.** Metrics = this skill. Traces / sampling / W3C context = **otel-aks-observability**. Request logs with `trace_id` and no PII = **spring-boot-structured-logging-guardrails**. Correlate via exemplars or shared trace ids; do not try to encode full request payloads into metric labels.\n13. **Verify with scrape + PromQL, not only `/actuator/metrics`.** Hit `/actuator/prometheus` (management port), confirm `http_server_requests_*` histogram buckets and common tags, run a sample `histogram_quantile` and error-rate query, and check Prometheus TSDB / cardinality for unexpected series growth after traffic.\n\n## Workflow\n1. Inventory: current Actuator exposure, management port, existing Micrometer registries, scrape config (ServiceMonitor / annotations), and any cardinality or missing-percentile complaints.\n2. Dependencies and config: ensure prometheus registry, expose `health`+`prometheus` only, set common tags, enable HTTP server histogram/SLO buckets.\n3. Audit meters: list custom `MeterRegistry` / `@Timed` / Observation usage; remove or rewrite unbounded labels; convert raw-URI tags to templates.\n4. Scrape path: point Prometheus at the management port/path; confirm NetworkPolicy / private Service; leave public Ingress alone.\n5. Cross-check Actuator lockdown with **spring-boot-actuator-hardening**; leave traces/logs to their skills.\n6. PR notes: meter inventory, cardinality before/after, PromQL examples for RED, scrape manifest diff, residual risks (auth on management, bucket choices).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-micrometer-prometheus.instructions.md` with `applyTo` covering application config, Meter/Metrics config classes, build files, and scrape manifests.\n- Always-on line in `.github/copilot-instructions.md`: \"Micrometer metrics use URI templates and bounded labels; Prometheus scrapes management-port `/actuator/prometheus` with histograms for http.server.requests.\"\n- Optional `.github/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Never put user ids or raw request paths on Micrometer tags; scrape only the management prometheus endpoint.\"\n- Before claiming done, show `/actuator/prometheus` sample lines for `http_server_requests` and the ServiceMonitor (or annotation) diff.\n\n### Codex\n- Micrometer / Prometheus section in root `AGENTS.md` or nested `src/main/AGENTS.md` (or linked `docs/agents/spring-micrometer-prometheus.md`).\n- State: required dependencies, allowed exposed endpoints, banned label patterns, histogram/SLO bucket policy, management-port scrape convention, and which sibling skills cover Actuator security vs OTel vs logging.\n\n## Anti-patterns\n- `management.endpoints.web.exposure.include=*` so prometheus works \"for now\"\n- Scraping the public app port / Ingress for `/actuator/prometheus`\n- Labeling timers with `uri=/orders/12345` or `userId=...`\n- Using exception **messages** (or stack traces) as tag values instead of bounded exception class names\n- Summaries only, then wondering why Grafana cannot show stable p99 or SLO burn\n- A new custom counter per customer, tenant-without-bound, or free-text \"reason\"\n- Duplicating the same RED signal under three meter names\n- Putting secrets or connection strings into `info` or metric tags\n- Ignoring Actuator hardening while opening prometheus (or the reverse: locking Actuator so hard scrapes break with no scrape auth plan)\n\n## Verification checklist\n- [ ] `micrometer-registry-prometheus` on the classpath; Prometheus scrape returns data\n- [ ] Management port (preferred) exposes `health` + `prometheus` only; no `include=*`\n- [ ] Common tags include application and environment (or platform equivalent)\n- [ ] `http.server.requests` uses URI templates; no raw ids in uri/path labels\n- [ ] Percentile histogram or explicit SLO buckets enabled for HTTP server (and critical clients)\n- [ ] Custom meters use bounded enums/codes only — no user/order ids or free text\n- [ ] AKS scrape targets management port via ServiceMonitor/PodMonitor or equivalent annotations\n- [ ] Network path for scrape is private; Actuator lockdown still matches **spring-boot-actuator-hardening**\n- [ ] Sample PromQL for rate, 5xx ratio, and `histogram_quantile` documented in the PR\n- [ ] Traces/logs left to OTel / structured-logging skills — not stuffed into labels\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-micrometer-prometheus-guardrails\ndescription: Use when wiring or reviewing Micrometer + Prometheus for a Spring Boot service — actuator prometheus registry, RED/SLI histograms, cardinality control, common tags, and AKS scrape hygiene.\n---\n\nFollow Spring Boot Micrometer Prometheus Guardrails: prometheus registry on a separate management port exposing health+prometheus only, common application/environment tags, URI templates not raw paths or user ids, histograms/SLO buckets for http.server.requests, bounded labels on custom meters, private AKS scrape (ServiceMonitor or annotations on the management port), and pair with spring-boot-actuator-hardening for lockdown plus otel-aks-observability / structured-logging for traces and logs.\n```\n" } ] }