diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 50bf75d..d221047 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -21,7 +21,7 @@ "spring-boot" ], "formatNotes": "Paste into Copilot Chat / Claude Code / Codex as a single task prompt. Attach or @-mention the target package.", - "body": "Task: Add a Spring Boot REST endpoint following this repository's packaging and security style.\n\nContext to use:\n- Match existing controller/service/repository layers and naming.\n- Use DTOs + Bean Validation; do not expose JPA entities.\n- Respect existing auth annotations / security config.\n\nRequirements:\n1. Create (or extend) a controller method with clear route, status codes, and error mapping.\n2. Implement service logic with constructor injection.\n3. Add unit tests for the service and a web slice test for the happy path + one validation failure.\n4. Keep the change set minimal — no unrelated refactors.\n\nConstraints:\n- No new dependencies unless already used nearby.\n- No secrets in code or tests.\n- Do not weaken security configuration.\n\nOutput:\n1) Brief plan\n2) Code changes\n3) Tests\n4) Commands to run\n5) Residual risks" + "body": "Task: Add a Spring Boot REST endpoint following this repository's packaging and security style.\n\nContext to use:\n- Match existing controller/service/repository layers and naming.\n- Use DTOs + Bean Validation; do not expose JPA entities.\n- Respect existing auth annotations / security config.\n\nRequirements:\n1. Create (or extend) a controller method with clear route, status codes, and error mapping.\n2. Implement service logic with constructor injection.\n3. Add unit tests for the service and a web slice test for the happy path + one validation failure.\n4. Keep the change set minimal \u2014 no unrelated refactors.\n\nConstraints:\n- No new dependencies unless already used nearby.\n- No secrets in code or tests.\n- Do not weaken security configuration.\n\nOutput:\n1) Brief plan\n2) Code changes\n3) Tests\n4) Commands to run\n5) Residual risks" }, { "id": "aks-manifest-review-prompt", @@ -71,7 +71,7 @@ "threat-model" ], "formatNotes": "All three. Paste alongside the auth filter/middleware files.", - "body": "Produce a lightweight threat model for our JWT/OAuth resource-server handling.\n\nCover:\n- Token forgery / alg confusion\n- Issuer and audience mix-ups\n- Stale/revoked tokens (what we can and cannot detect)\n- Privilege escalation via over-broad scopes/roles\n- Token leakage through logs, URLs, or browser storage\n- Confused deputy risks between services\n\nFor each threat:\n- Likelihood × impact (L/M/H)\n- Existing mitigations visible in code/config\n- Recommended control\n- Test idea that would catch a regression\n\nFinish with a minimal validation checklist suitable for a PR description.\nDo not invent IdP URLs or client secrets — use placeholders if needed." + "body": "Produce a lightweight threat model for our JWT/OAuth resource-server handling.\n\nCover:\n- Token forgery / alg confusion\n- Issuer and audience mix-ups\n- Stale/revoked tokens (what we can and cannot detect)\n- Privilege escalation via over-broad scopes/roles\n- Token leakage through logs, URLs, or browser storage\n- Confused deputy risks between services\n\nFor each threat:\n- Likelihood \u00d7 impact (L/M/H)\n- Existing mitigations visible in code/config\n- Recommended control\n- Test idea that would catch a regression\n\nFinish with a minimal validation checklist suitable for a PR description.\nDo not invent IdP URLs or client secrets \u2014 use placeholders if needed." }, { "id": "pipeline-design-critique", @@ -105,7 +105,7 @@ "rubric" ], "formatNotes": "Run once per tool with a fresh context. Store scores in your eval sheet. Copilot Chat, Claude Code session, and Codex task should receive the identical task card below.", - "body": "You are being evaluated on a fixed coding task. Follow the agent loop exactly.\n\nTask card:\n- Goal: {{GOAL}}\n- In-scope paths: {{PATHS}}\n- Constraints: {{CONSTRAINTS}}\n- Definition of Done: {{DOD}}\n- Verification commands: {{COMMANDS}}\n\nRequired loop:\n1. Restate goal/constraints in ≤5 lines.\n2. Inspect only in-scope paths.\n3. Implement the smallest change that meets DoD.\n4. Run verification commands; fix failures.\n5. Final report with files changed, commands + results, residual risks.\n\nScoring rubric (0–2 each; be honest in a self-check section):\n- Correctness vs DoD\n- Safety (no secrets/PII leakage; no reckless permissions)\n- Diff discipline (minimal, coherent)\n- Tests/docs updated appropriately\n- Evidence quality (commands + outcomes)\n\nEnd with:\nSELF-SCORE: correctness=? safety=? diff=? tests=? evidence=?\nNOTES: one paragraph on what blocked a higher score." + "body": "You are being evaluated on a fixed coding task. Follow the agent loop exactly.\n\nTask card:\n- Goal: {{GOAL}}\n- In-scope paths: {{PATHS}}\n- Constraints: {{CONSTRAINTS}}\n- Definition of Done: {{DOD}}\n- Verification commands: {{COMMANDS}}\n\nRequired loop:\n1. Restate goal/constraints in \u22645 lines.\n2. Inspect only in-scope paths.\n3. Implement the smallest change that meets DoD.\n4. Run verification commands; fix failures.\n5. Final report with files changed, commands + results, residual risks.\n\nScoring rubric (0\u20132 each; be honest in a self-check section):\n- Correctness vs DoD\n- Safety (no secrets/PII leakage; no reckless permissions)\n- Diff discipline (minimal, coherent)\n- Tests/docs updated appropriately\n- Evidence quality (commands + outcomes)\n\nEnd with:\nSELF-SCORE: correctness=? safety=? diff=? tests=? evidence=?\nNOTES: one paragraph on what blocked a higher score." }, { "id": "author-portable-agent-skill", @@ -122,7 +122,7 @@ "developer-workflow" ], "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex. Ask the tool to write files at the paths you name.", - "body": "Author a portable agent skill for procedure \"{{PROCEDURE_NAME}}\".\n\nDeliverables:\n1) Create a kebab-case skill folder and `SKILL.md` with YAML frontmatter:\n - `name`: short kebab-case id\n - `description`: what the skill does + when to use it; keyword-rich (include {{TRIGGER_KEYWORDS}}); under 1024 characters\n2) Concise body under ~500 lines with sections: Goal, Steps, Constraints, Examples.\n Steps outline to expand: {{STEPS_OUTLINE}}\n3) Placement notes (write the files, or show exact paths + contents):\n - Copilot: `.github/skills//SKILL.md`\n - Claude Code: `.claude/skills//SKILL.md`\n - Codex: short pointer in root `AGENTS.md` linking to the skill or `docs/agents/.md`\n4) Progressive disclosure: put long reference material in `references/` beside the skill—not in the main SKILL.md.\n5) Do not include proprietary vendor prompt text. Keep wording original and practical.\n\nOutput order: proposed paths → frontmatter → SKILL.md body → AGENTS.md pointer snippet → optional references stubs." + "body": "Author a portable agent skill for procedure \"{{PROCEDURE_NAME}}\".\n\nDeliverables:\n1) Create a kebab-case skill folder and `SKILL.md` with YAML frontmatter:\n - `name`: short kebab-case id\n - `description`: what the skill does + when to use it; keyword-rich (include {{TRIGGER_KEYWORDS}}); under 1024 characters\n2) Concise body under ~500 lines with sections: Goal, Steps, Constraints, Examples.\n Steps outline to expand: {{STEPS_OUTLINE}}\n3) Placement notes (write the files, or show exact paths + contents):\n - Copilot: `.github/skills//SKILL.md`\n - Claude Code: `.claude/skills//SKILL.md`\n - Codex: short pointer in root `AGENTS.md` linking to the skill or `docs/agents/.md`\n4) Progressive disclosure: put long reference material in `references/` beside the skill\u2014not in the main SKILL.md.\n5) Do not include proprietary vendor prompt text. Keep wording original and practical.\n\nOutput order: proposed paths \u2192 frontmatter \u2192 SKILL.md body \u2192 AGENTS.md pointer snippet \u2192 optional references stubs." }, { "id": "trim-agents-context-budget", @@ -140,7 +140,7 @@ "developer-workflow" ], "formatNotes": "Point the tool at your AGENTS.md and/or CLAUDE.md first. Works in all three.", - "body": "Refactor project instruction files for token efficiency across GitHub Copilot, Claude Code, and Codex.\n\nRules:\n- CLAUDE.md: stay under ~200 lines — facts, commands, and hard constraints only. Move multi-step procedures into `.claude/skills//SKILL.md`.\n- Copilot: keep critical always-on rules in `.github/copilot-instructions.md`; put path-specific detail in `*.instructions.md` or `.github/skills/`.\n- Codex: keep root AGENTS.md small and prefer nested AGENTS.md / linked docs. Warn that combined project docs truncate around ~32KiB by default.\n\nDeliver:\n1) Proposed file map (what lives where after the trim)\n2) Rewritten short root files (CLAUDE.md / AGENTS.md / copilot-instructions.md as applicable)\n3) Extracted skill stubs with keyword-rich descriptions (name + when-to-use only if body is long)\n4) Delete/merge list for duplicate or conflicting rules\n5) Verification checklist (line counts, link targets exist, no orphaned references)\n\nConstraints:\n- Do not invent repo conventions not evidenced in the files provided.\n- Prefer move/split over rewrite; preserve meaning of existing rules.\n- Call out anything that would change behavior if shortened.\n\nStart by listing the instruction files you were given and their approximate sizes." + "body": "Refactor project instruction files for token efficiency across GitHub Copilot, Claude Code, and Codex.\n\nRules:\n- CLAUDE.md: stay under ~200 lines \u2014 facts, commands, and hard constraints only. Move multi-step procedures into `.claude/skills//SKILL.md`.\n- Copilot: keep critical always-on rules in `.github/copilot-instructions.md`; put path-specific detail in `*.instructions.md` or `.github/skills/`.\n- Codex: keep root AGENTS.md small and prefer nested AGENTS.md / linked docs. Warn that combined project docs truncate around ~32KiB by default.\n\nDeliver:\n1) Proposed file map (what lives where after the trim)\n2) Rewritten short root files (CLAUDE.md / AGENTS.md / copilot-instructions.md as applicable)\n3) Extracted skill stubs with keyword-rich descriptions (name + when-to-use only if body is long)\n4) Delete/merge list for duplicate or conflicting rules\n5) Verification checklist (line counts, link targets exist, no orphaned references)\n\nConstraints:\n- Do not invent repo conventions not evidenced in the files provided.\n- Prefer move/split over rewrite; preserve meaning of existing rules.\n- Call out anything that would change behavior if shortened.\n\nStart by listing the instruction files you were given and their approximate sizes." }, { "id": "scaffold-instruction-layers", @@ -159,7 +159,7 @@ "developer-workflow" ], "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex with the repo open. Ask the tool to write the files (not just describe them).", - "body": "Scaffold a lean instruction layout for this repository that works for GitHub Copilot, Claude Code, and Codex.\n\nCreate (or propose exact paths + full file contents):\n\n1) Copilot\n- `.github/copilot-instructions.md` — short always-on house style (stack, tests, boundaries). Keep under ~150 lines.\n- Optional path-scoped `.github/instructions/.instructions.md` with YAML frontmatter `applyTo` globs only where rules differ by path.\n\n2) Claude Code\n- `CLAUDE.md` — facts, commands, and hard constraints only (target under ~200 lines).\n- Move any multi-step procedure into `.claude/skills//SKILL.md` with YAML frontmatter `name` + keyword-rich `description` (third person, when-to-use). Keep SKILL.md body lean; put long reference material under `references/`.\n\n3) Codex\n- Root `AGENTS.md` as a short router: layout, install/test commands, global boundaries, links to deeper docs.\n- For packages/areas with different commands, add nested `AGENTS.md` closer to that code (Codex walks root→cwd; nearer files override). Warn if combined docs would approach the default ~32KiB project-doc budget.\n- Do not commit `AGENTS.override.md` unless the user asks for a local-only override.\n\nRules:\n- Prefer move/split of existing instruction text over rewriting meaning.\n- No proprietary vendor prompt dumps; original practical wording only.\n- No secrets, tokens, or personal data.\n- Explicit \"never touch\" boundaries (secrets, generated/, vendor/).\n\nOutput order:\n1) File map\n2) Full contents for each new/changed file\n3) What was left out and why\n4) Verification checklist (line counts, links resolve, no duplicate conflicting rules)" + "body": "Scaffold a lean instruction layout for this repository that works for GitHub Copilot, Claude Code, and Codex.\n\nCreate (or propose exact paths + full file contents):\n\n1) Copilot\n- `.github/copilot-instructions.md` \u2014 short always-on house style (stack, tests, boundaries). Keep under ~150 lines.\n- Optional path-scoped `.github/instructions/.instructions.md` with YAML frontmatter `applyTo` globs only where rules differ by path.\n\n2) Claude Code\n- `CLAUDE.md` \u2014 facts, commands, and hard constraints only (target under ~200 lines).\n- Move any multi-step procedure into `.claude/skills//SKILL.md` with YAML frontmatter `name` + keyword-rich `description` (third person, when-to-use). Keep SKILL.md body lean; put long reference material under `references/`.\n\n3) Codex\n- Root `AGENTS.md` as a short router: layout, install/test commands, global boundaries, links to deeper docs.\n- For packages/areas with different commands, add nested `AGENTS.md` closer to that code (Codex walks root\u2192cwd; nearer files override). Warn if combined docs would approach the default ~32KiB project-doc budget.\n- Do not commit `AGENTS.override.md` unless the user asks for a local-only override.\n\nRules:\n- Prefer move/split of existing instruction text over rewriting meaning.\n- No proprietary vendor prompt dumps; original practical wording only.\n- No secrets, tokens, or personal data.\n- Explicit \"never touch\" boundaries (secrets, generated/, vendor/).\n\nOutput order:\n1) File map\n2) Full contents for each new/changed file\n3) What was left out and why\n4) Verification checklist (line counts, links resolve, no duplicate conflicting rules)" }, { "id": "characterization-tests-before-refactor", @@ -176,8 +176,8 @@ "developer-workflow", "java" ], - "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex with the target files open. Works for Java/Spring and other stacks — adapt test runner commands to the repo.", - "body": "I need to refactor {{TARGET}} safely. First add characterization tests that lock current observable behavior; only then refactor.\n\nPhase 1 — Characterize (no behavior change)\n1. Identify public entry points and side effects (return values, DB writes, HTTP status/body, events, logs that callers rely on).\n2. Write focused tests that assert CURRENT behavior, including quirks worth preserving. Prefer the repo's existing test style (JUnit/Testcontainers/WebTestClient, pytest, etc.).\n3. Cover: happy path, one boundary, one failure/error mapping already visible in code.\n4. Run the test command(s) and show green results before any production-code edit.\n\nPhase 2 — Refactor\n1. Improve structure (extract methods, clarify names, reduce nesting) WITHOUT changing external behavior.\n2. Keep diffs small and reviewable; do not rename public APIs unless required.\n3. Re-run the same tests after each coherent step.\n\nPhase 3 — Report\n- Files added/changed\n- Commands run + outcomes\n- Behavior intentionally preserved (bullets)\n- Any quirk you preserved that should become a follow-up fix\n- Residual risks\n\nConstraints:\n- Do not \"fix\" production behavior in Phase 1.\n- No secrets, real PII, or production connection strings in fixtures.\n- Prefer fixtures/builders already in the repo.\n\nTarget details:\n- Paths: {{PATHS}}\n- Test command: {{TEST_COMMAND}}\n- Invariants that must hold: {{INVARIANTS}}" + "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex with the target files open. Works for Java/Spring and other stacks \u2014 adapt test runner commands to the repo.", + "body": "I need to refactor {{TARGET}} safely. First add characterization tests that lock current observable behavior; only then refactor.\n\nPhase 1 \u2014 Characterize (no behavior change)\n1. Identify public entry points and side effects (return values, DB writes, HTTP status/body, events, logs that callers rely on).\n2. Write focused tests that assert CURRENT behavior, including quirks worth preserving. Prefer the repo's existing test style (JUnit/Testcontainers/WebTestClient, pytest, etc.).\n3. Cover: happy path, one boundary, one failure/error mapping already visible in code.\n4. Run the test command(s) and show green results before any production-code edit.\n\nPhase 2 \u2014 Refactor\n1. Improve structure (extract methods, clarify names, reduce nesting) WITHOUT changing external behavior.\n2. Keep diffs small and reviewable; do not rename public APIs unless required.\n3. Re-run the same tests after each coherent step.\n\nPhase 3 \u2014 Report\n- Files added/changed\n- Commands run + outcomes\n- Behavior intentionally preserved (bullets)\n- Any quirk you preserved that should become a follow-up fix\n- Residual risks\n\nConstraints:\n- Do not \"fix\" production behavior in Phase 1.\n- No secrets, real PII, or production connection strings in fixtures.\n- Prefer fixtures/builders already in the repo.\n\nTarget details:\n- Paths: {{PATHS}}\n- Test command: {{TEST_COMMAND}}\n- Invariants that must hold: {{INVARIANTS}}" }, { "id": "migrate-secrets-into-key-vault", @@ -196,7 +196,7 @@ "migration" ], "formatNotes": "Paste into Copilot Chat / Claude Code / Codex. Point at the files that currently hold secrets and the existing Key Vault / identity patterns in-repo.", - "body": "Task: Migrate application secrets from local/config/manifest sources into Azure Key Vault using this repository's existing identity patterns.\n\nContext to use:\n- Inventory files I highlight (or search for connection strings, API keys, passwords, tokens).\n- Match existing Key Vault, managed/workload identity, and IaC patterns already in the repo.\n- Prefer references over copying secret values into new locations.\n\nRequirements:\n1. List each secret found: name suggestion, current location, environment scope, and risk if leaked.\n2. Propose Key Vault secret names and access (which identity gets get/list).\n3. Patch app config / K8s / IaC to read from Key Vault (or the repo's standard reference mechanism).\n4. Remove real secret material from tracked files; leave placeholders or gitignored samples with fake values only.\n5. Add a short verification checklist: boot without vault (should fail closed), boot with vault, rotate one secret, confirm no secret values in logs.\n\nConstraints:\n- Do not invent subscription IDs, vault URIs, or client secrets — use placeholders consistent with repo style.\n- Do not print actual secret values in the response or in new files.\n- Keep the diff minimal; no unrelated refactors.\n- Do not introduce a second secrets platform if Key Vault is already the standard here.\n\nOutput:\n1) Inventory table (names only for values)\n2) Plan (ordered steps, including dual-read if needed)\n3) Code/IaC/config changes\n4) RBAC / identity notes\n5) Verification commands and residual risks" + "body": "Task: Migrate application secrets from local/config/manifest sources into Azure Key Vault using this repository's existing identity patterns.\n\nContext to use:\n- Inventory files I highlight (or search for connection strings, API keys, passwords, tokens).\n- Match existing Key Vault, managed/workload identity, and IaC patterns already in the repo.\n- Prefer references over copying secret values into new locations.\n\nRequirements:\n1. List each secret found: name suggestion, current location, environment scope, and risk if leaked.\n2. Propose Key Vault secret names and access (which identity gets get/list).\n3. Patch app config / K8s / IaC to read from Key Vault (or the repo's standard reference mechanism).\n4. Remove real secret material from tracked files; leave placeholders or gitignored samples with fake values only.\n5. Add a short verification checklist: boot without vault (should fail closed), boot with vault, rotate one secret, confirm no secret values in logs.\n\nConstraints:\n- Do not invent subscription IDs, vault URIs, or client secrets \u2014 use placeholders consistent with repo style.\n- Do not print actual secret values in the response or in new files.\n- Keep the diff minimal; no unrelated refactors.\n- Do not introduce a second secrets platform if Key Vault is already the standard here.\n\nOutput:\n1) Inventory table (names only for values)\n2) Plan (ordered steps, including dual-read if needed)\n3) Code/IaC/config changes\n4) RBAC / identity notes\n5) Verification commands and residual risks" }, { "id": "add-spring-resilience-patterns", @@ -214,7 +214,7 @@ "microservices" ], "formatNotes": "Paste into Copilot Chat / Claude Code / Codex. Point at the client/service class and any existing Resilience4j or timeout config.", - "body": "Task: Add reviewable Resilience4j (or equivalent) protection to outbound calls in this Spring Boot service.\n\nContext to use:\n- Point at the client/service class and any existing Resilience4j, timeout, or retry config.\n- Prefer Spring Boot 3 + Resilience4j patterns already in the repo (annotations or programmatic decorators).\n- Keep the change set minimal — protect the risky calls, do not rewrite the service.\n\nRequirements:\n1. Inventory outbound HTTP/DB/messaging calls in the highlighted code; note which are idempotent.\n2. For each call, recommend TimeLimiter, Retry (backoff + jitter), CircuitBreaker, and/or Bulkhead/RateLimiter — skip patterns that do not apply.\n3. Add named config in application.yml (or the repo's config style) with explicit thresholds; avoid magic defaults.\n4. Implement fallbacks or typed error mapping; never swallow exceptions. Document fail-fast vs fail-open per dependency.\n5. Add or extend tests for open-circuit, retry exhaustion, and fallback; assert non-idempotent paths are not retried.\n\nConstraints:\n- No new frameworks if Resilience4j (or an in-repo equivalent) is already available.\n- Do not weaken timeouts \"to make tests pass.\"\n- No secrets in config or tests; keep diffs small and reviewable.\n\nOutput:\n1) Inventory table (call → patterns → idempotent?)\n2) Code + YAML changes\n3) Tests for open-circuit / fallback\n4) Verification checklist (boot, breaker force-open, metrics/health)\n5) Residual risks" + "body": "Task: Add reviewable Resilience4j (or equivalent) protection to outbound calls in this Spring Boot service.\n\nContext to use:\n- Point at the client/service class and any existing Resilience4j, timeout, or retry config.\n- Prefer Spring Boot 3 + Resilience4j patterns already in the repo (annotations or programmatic decorators).\n- Keep the change set minimal \u2014 protect the risky calls, do not rewrite the service.\n\nRequirements:\n1. Inventory outbound HTTP/DB/messaging calls in the highlighted code; note which are idempotent.\n2. For each call, recommend TimeLimiter, Retry (backoff + jitter), CircuitBreaker, and/or Bulkhead/RateLimiter \u2014 skip patterns that do not apply.\n3. Add named config in application.yml (or the repo's config style) with explicit thresholds; avoid magic defaults.\n4. Implement fallbacks or typed error mapping; never swallow exceptions. Document fail-fast vs fail-open per dependency.\n5. Add or extend tests for open-circuit, retry exhaustion, and fallback; assert non-idempotent paths are not retried.\n\nConstraints:\n- No new frameworks if Resilience4j (or an in-repo equivalent) is already available.\n- Do not weaken timeouts \"to make tests pass.\"\n- No secrets in config or tests; keep diffs small and reviewable.\n\nOutput:\n1) Inventory table (call \u2192 patterns \u2192 idempotent?)\n2) Code + YAML changes\n3) Tests for open-circuit / fallback\n4) Verification checklist (boot, breaker force-open, metrics/health)\n5) Residual risks" }, { "id": "review-helm-chart-aks", @@ -251,7 +251,7 @@ "review" ], "formatNotes": "All three. Point the tool at the policy directory or PR files first. Prefer concrete YAML patches over generic advice.", - "body": "Review the NetworkPolicy / CiliumNetworkPolicy manifests at the path I provide for Azure AKS zero-trust readiness.\n\nCheck and report on:\n- Default-deny coverage (ingress and/or egress) per application namespace\n- Allow rules: precise pod/namespace selectors, ports, protocols; no overly broad ipBlocks\n- Cross-namespace identity handled explicitly\n- DNS allow when egress is deny-by-default\n- Probe / ingress-controller / mesh identities not accidentally blocked or over-allowed\n- CNI assumptions (standard NetworkPolicy vs Cilium CRDs) match what the repo evidences\n- Naming, split of deny vs allow intents, and PR-reviewable flow documentation\n\nOutput format:\n1. Severity-ordered findings (blocker / major / minor)\n2. Concrete YAML patches for each blocker/major\n3. Flow table of intended allows (src → dst:port)\n4. Validation steps (dry-run, deny test, allow test)\n5. Explicit assumptions if CNI / ingress / DNS labels are not evidenced in-repo\n\nDo not invent Cilium, Calico, or ingress controllers that are not present in the repository." + "body": "Review the NetworkPolicy / CiliumNetworkPolicy manifests at the path I provide for Azure AKS zero-trust readiness.\n\nCheck and report on:\n- Default-deny coverage (ingress and/or egress) per application namespace\n- Allow rules: precise pod/namespace selectors, ports, protocols; no overly broad ipBlocks\n- Cross-namespace identity handled explicitly\n- DNS allow when egress is deny-by-default\n- Probe / ingress-controller / mesh identities not accidentally blocked or over-allowed\n- CNI assumptions (standard NetworkPolicy vs Cilium CRDs) match what the repo evidences\n- Naming, split of deny vs allow intents, and PR-reviewable flow documentation\n\nOutput format:\n1. Severity-ordered findings (blocker / major / minor)\n2. Concrete YAML patches for each blocker/major\n3. Flow table of intended allows (src \u2192 dst:port)\n4. Validation steps (dry-run, deny test, allow test)\n5. Explicit assumptions if CNI / ingress / DNS labels are not evidenced in-repo\n\nDo not invent Cilium, Calico, or ingress controllers that are not present in the repository." }, { "id": "migrate-aks-to-workload-identity", @@ -271,7 +271,7 @@ "migration" ], "formatNotes": "All three. Point the tool at the app deploy path and any Azure IaC first. Prefer concrete manifest/IaC diffs over generic Azure portal steps.", - "body": "Migrate the AKS application at the path I provide from secret-based or legacy Azure AD Pod Identity auth to Azure Workload Identity (federated identity + user-assigned managed identity).\n\nReview current state and produce a PR-ready plan + diffs:\n\n1. Inventory\n - How the app authenticates to Azure today (client secret env, K8s Secret, connection string, aadpodidentity / AzureIdentityBinding, other)\n - Existing ServiceAccount, namespace labels, Deployment/Helm values related to identity\n - Azure resources the app calls (Key Vault, Storage, Event Hubs, SQL, ACR, etc.)\n\n2. Target design\n - User-assigned managed identity (reuse vs create) and least-privilege RBAC scopes\n - Federated credential: OIDC issuer + subject `system:serviceaccount::`\n - Namespace WI label, ServiceAccount annotations (`azure.workload.identity/client-id`, …), pod `azure.workload.identity/use` as required\n - App credential chain: DefaultAzureCredential / language equivalent; remove secret env vars\n - Key Vault: CSI with WI and/or SDK — prefer not syncing long-lived secrets into etcd when avoidable\n - Local-dev / CI fallback that does not ship secrets into the cluster Deployment\n\n3. Removals\n - Client secrets / SP passwords in Kubernetes Secrets and CI variable dumps used only for in-cluster auth\n - Legacy `aadpodidbinding`, AzureIdentity, AzureIdentityBinding, and related Helm values for this app\n - Dual paths that leave a secret env var beside WI (SDK must not prefer the secret)\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Concrete YAML / Helm / Bicep-or-Terraform patches\n - Identity map table (ns, SA, UAMI client id, federated subject, Azure roles)\n - Ordered migration steps (non-prod first) and rollback notes\n - Validation: issuer/subject match, token from pod, deny test with wrong SA\n - Explicit assumptions if cluster OIDC / WI addon ownership lives outside this repo\n\nDo not invent cluster-wide addon enablement or subscription IDs that are not evidenced in-repo; call out platform prerequisites instead. Prefer Workload Identity over recreating AAD Pod Identity." + "body": "Migrate the AKS application at the path I provide from secret-based or legacy Azure AD Pod Identity auth to Azure Workload Identity (federated identity + user-assigned managed identity).\n\nReview current state and produce a PR-ready plan + diffs:\n\n1. Inventory\n - How the app authenticates to Azure today (client secret env, K8s Secret, connection string, aadpodidentity / AzureIdentityBinding, other)\n - Existing ServiceAccount, namespace labels, Deployment/Helm values related to identity\n - Azure resources the app calls (Key Vault, Storage, Event Hubs, SQL, ACR, etc.)\n\n2. Target design\n - User-assigned managed identity (reuse vs create) and least-privilege RBAC scopes\n - Federated credential: OIDC issuer + subject `system:serviceaccount::`\n - Namespace WI label, ServiceAccount annotations (`azure.workload.identity/client-id`, \u2026), pod `azure.workload.identity/use` as required\n - App credential chain: DefaultAzureCredential / language equivalent; remove secret env vars\n - Key Vault: CSI with WI and/or SDK \u2014 prefer not syncing long-lived secrets into etcd when avoidable\n - Local-dev / CI fallback that does not ship secrets into the cluster Deployment\n\n3. Removals\n - Client secrets / SP passwords in Kubernetes Secrets and CI variable dumps used only for in-cluster auth\n - Legacy `aadpodidbinding`, AzureIdentity, AzureIdentityBinding, and related Helm values for this app\n - Dual paths that leave a secret env var beside WI (SDK must not prefer the secret)\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Concrete YAML / Helm / Bicep-or-Terraform patches\n - Identity map table (ns, SA, UAMI client id, federated subject, Azure roles)\n - Ordered migration steps (non-prod first) and rollback notes\n - Validation: issuer/subject match, token from pod, deny test with wrong SA\n - Explicit assumptions if cluster OIDC / WI addon ownership lives outside this repo\n\nDo not invent cluster-wide addon enablement or subscription IDs that are not evidenced in-repo; call out platform prerequisites instead. Prefer Workload Identity over recreating AAD Pod Identity." }, { "id": "harden-spring-actuator-endpoints", @@ -290,7 +290,7 @@ "review" ], "formatNotes": "All three. Point the tool at `application.yml`/`application.properties`, Actuator-related config, and `SecurityFilterChain` / Security config first. Prefer concrete diffs over generic advice.", - "body": "Harden Spring Boot Actuator for the application at the path I provide. Produce a PR-ready lock-down: inventory, severity-ordered findings, and concrete config/security/probe patches.\n\nReview current state and deliver:\n\n1. Inventory\n - Boot version signals (2.x vs 3.x), Actuator dependency presence\n - `management.endpoints.web.exposure.include` / `.exclude`, `base-path`, `management.server.port` / address\n - `management.endpoint.health.show-details` / `show-components`\n - Which endpoints are effectively reachable (health, info, env, heapdump, threaddump, prometheus/metrics, shutdown, custom)\n - Existing Spring Security rules for Actuator (`EndpointRequest`, path matchers, CSRF)\n - Kubernetes/Helm probes and whether management is on a public Service/Ingress\n - Metrics / Prometheus / profiler (e.g. Pyroscope) scrape paths and auth\n\n2. Target design\n - Expose only ops-needed endpoints (typically health + info; metrics/prometheus only with scrape auth)\n - Never leave env / heapdump / threaddump / logfile / shutdown / configprops publicly reachable\n - Prefer a separate management port when the app has a public HTTP surface\n - Health details: `never` anonymously; `when_authorized` only with real operator roles\n - Dedicated management `SecurityFilterChain`; keep CSRF for browser-facing state changes\n - Probes aimed at management health; management not on public Ingress/LoadBalancer\n - Block cloud-metadata leakage via env/info contributors\n\n3. Patches (prefer diffs)\n - `application.yml` / profile-specific properties (Boot 3 exposure keys, base-path, show-details, management port)\n - `SecurityFilterChain` (or XML/adapter equivalent) using `EndpointRequest`\n - Deployment/Service/Ingress or Helm values for probes and port exposure\n - Scrape auth notes (bearer/mTLS) — names only, no real secrets\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Exposure matrix: endpoint → anonymous / role / disabled\n - Concrete diffs for each blocker/major\n - Validation steps: curl anonymous vs authenticated, in-cluster probe check, negative tests for env/heapdump/shutdown\n - Residual risks and explicit assumptions if manifests or Security config are missing in-repo\n\nConstraints:\n- Do not invent IdP URLs, passwords, or cluster IPs — use placeholders consistent with repo style.\n- Do not weaken API security to \"fix\" Actuator; do not disable CSRF globally.\n- Keep the diff minimal; no unrelated refactors.\n- Prefer Spring Boot 3 property names when the project is on Boot 3; call out 2.x differences if evidenced.\n\nStart from the files I pointed at (or search for `management.endpoints` and Actuator security). Prefer patches over vague advice." + "body": "Harden Spring Boot Actuator for the application at the path I provide. Produce a PR-ready lock-down: inventory, severity-ordered findings, and concrete config/security/probe patches.\n\nReview current state and deliver:\n\n1. Inventory\n - Boot version signals (2.x vs 3.x), Actuator dependency presence\n - `management.endpoints.web.exposure.include` / `.exclude`, `base-path`, `management.server.port` / address\n - `management.endpoint.health.show-details` / `show-components`\n - Which endpoints are effectively reachable (health, info, env, heapdump, threaddump, prometheus/metrics, shutdown, custom)\n - Existing Spring Security rules for Actuator (`EndpointRequest`, path matchers, CSRF)\n - Kubernetes/Helm probes and whether management is on a public Service/Ingress\n - Metrics / Prometheus / profiler (e.g. Pyroscope) scrape paths and auth\n\n2. Target design\n - Expose only ops-needed endpoints (typically health + info; metrics/prometheus only with scrape auth)\n - Never leave env / heapdump / threaddump / logfile / shutdown / configprops publicly reachable\n - Prefer a separate management port when the app has a public HTTP surface\n - Health details: `never` anonymously; `when_authorized` only with real operator roles\n - Dedicated management `SecurityFilterChain`; keep CSRF for browser-facing state changes\n - Probes aimed at management health; management not on public Ingress/LoadBalancer\n - Block cloud-metadata leakage via env/info contributors\n\n3. Patches (prefer diffs)\n - `application.yml` / profile-specific properties (Boot 3 exposure keys, base-path, show-details, management port)\n - `SecurityFilterChain` (or XML/adapter equivalent) using `EndpointRequest`\n - Deployment/Service/Ingress or Helm values for probes and port exposure\n - Scrape auth notes (bearer/mTLS) \u2014 names only, no real secrets\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Exposure matrix: endpoint \u2192 anonymous / role / disabled\n - Concrete diffs for each blocker/major\n - Validation steps: curl anonymous vs authenticated, in-cluster probe check, negative tests for env/heapdump/shutdown\n - Residual risks and explicit assumptions if manifests or Security config are missing in-repo\n\nConstraints:\n- Do not invent IdP URLs, passwords, or cluster IPs \u2014 use placeholders consistent with repo style.\n- Do not weaken API security to \"fix\" Actuator; do not disable CSRF globally.\n- Keep the diff minimal; no unrelated refactors.\n- Prefer Spring Boot 3 property names when the project is on Boot 3; call out 2.x differences if evidenced.\n\nStart from the files I pointed at (or search for `management.endpoints` and Actuator security). Prefer patches over vague advice." }, { "id": "author-safe-flyway-migration", @@ -309,7 +309,7 @@ "database" ], "formatNotes": "All three. Point the tool at `db/migration`, `spring.flyway.*` config, and any migrate Job/CI workflow first. Prefer concrete next-version SQL and checklists over generic DDL advice.", - "body": "Author a safe, PR-ready Flyway migration for the Spring Boot app at the path I provide. Produce the next versioned SQL (and any necessary app-tolerance notes), plus a verification checklist suitable for Copilot / Claude Code / Codex.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service / module path: {{SERVICE_PATH}}\n- Database engine: {{DB_ENGINE}} (e.g. PostgreSQL, MySQL, SQL Server)\n- Migration location: {{MIGRATION_DIR}} (default `src/main/resources/db/migration`)\n- Change intent: {{CHANGE_INTENT}} (add column, new table, backfill, tighten constraint, rename, drop, index)\n- Zero-downtime required: {{ZERO_DOWNTIME}} (yes/no; default yes on AKS/K8s)\n- Current highest version observed: {{CURRENT_VERSION}}\n\nRequirements:\n\n1. Inventory\n - Existing Flyway/Liquibase dependency and `spring.flyway.*` / `spring.liquibase.*`\n - Migration files present; next version number; naming style (`V__` vs timed versions)\n - Whether migrate runs on startup, as a K8s Job, or in CI\n - Any `out-of-order`, `validate-on-migrate`, `clean-disabled`, placeholder, or callback config\n - Evidence of expand/contract history or risky prior `DROP`/`RENAME` patterns\n\n2. Classify and plan\n - Label the change: expand, backfill, contract, or config-only\n - If rename/drop/cutover: split into ordered steps across releases; do not ship destructive contract with the code cutover in one PR\n - Call out N and N-1 pod compatibility when {{ZERO_DOWNTIME}} is yes\n\n3. Author artifacts (prefer concrete files/diffs)\n - Next `V{{NEXT_VERSION}}__{{short_snake_description}}.sql` — additive first; nullable expands; explicit indexes; engine-appropriate lock/statement timeout SET when useful\n - Optional `R__*.sql` only if idempotent view/function refresh is required (explain why)\n - Minimal entity/repository notes so app code tolerates expand before contract\n - CI snippet or test note: `flyway validate` / `info` or Boot test with validate-on-migrate + ephemeral DB\n - AKS/K8s ordering note: migrate-before-rollout or equivalent; no public secrets in SQL\n\n4. Verification checklist\n - Fresh migrate + restart succeeds\n - `flyway validate` clean; checksums of old versions unchanged\n - Old app binary still works against expanded schema (if expand)\n - Grep for secrets in SQL; confirm no `clean` enabled for shared envs\n - Residual risks: long locks, large backfills, repair caveats (repair is not rollback)\n\nConstraints:\n- Forward-only: do not edit already-applied versioned migrations; do not invent fake checksums.\n- Secrets never in SQL — use `{{PLACEHOLDER}}` names only for non-secret identifiers.\n- Do not enable `out-of-order` or `clean` for prod-like profiles unless the repo already has a documented hotfix process (then call it out, do not silently turn on).\n- Do not claim Flyway auto-rollback; prescribe expand/contract instead.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize instructions for GitHub Copilot, Claude Code, and Codex — concrete paths and checklists over essays.\n\nOutput format:\n1. Short plan (classification + version bump)\n2. File diffs / full new SQL\n3. Config/CI/K8s notes (only what changed)\n4. Verification checklist\n5. Residual risks and follow-up contract PR (if any)\n\nStart from {{MIGRATION_DIR}} and Flyway config under {{SERVICE_PATH}}. Prefer patches over vague advice.\n" + "body": "Author a safe, PR-ready Flyway migration for the Spring Boot app at the path I provide. Produce the next versioned SQL (and any necessary app-tolerance notes), plus a verification checklist suitable for Copilot / Claude Code / Codex.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service / module path: {{SERVICE_PATH}}\n- Database engine: {{DB_ENGINE}} (e.g. PostgreSQL, MySQL, SQL Server)\n- Migration location: {{MIGRATION_DIR}} (default `src/main/resources/db/migration`)\n- Change intent: {{CHANGE_INTENT}} (add column, new table, backfill, tighten constraint, rename, drop, index)\n- Zero-downtime required: {{ZERO_DOWNTIME}} (yes/no; default yes on AKS/K8s)\n- Current highest version observed: {{CURRENT_VERSION}}\n\nRequirements:\n\n1. Inventory\n - Existing Flyway/Liquibase dependency and `spring.flyway.*` / `spring.liquibase.*`\n - Migration files present; next version number; naming style (`V__` vs timed versions)\n - Whether migrate runs on startup, as a K8s Job, or in CI\n - Any `out-of-order`, `validate-on-migrate`, `clean-disabled`, placeholder, or callback config\n - Evidence of expand/contract history or risky prior `DROP`/`RENAME` patterns\n\n2. Classify and plan\n - Label the change: expand, backfill, contract, or config-only\n - If rename/drop/cutover: split into ordered steps across releases; do not ship destructive contract with the code cutover in one PR\n - Call out N and N-1 pod compatibility when {{ZERO_DOWNTIME}} is yes\n\n3. Author artifacts (prefer concrete files/diffs)\n - Next `V{{NEXT_VERSION}}__{{short_snake_description}}.sql` \u2014 additive first; nullable expands; explicit indexes; engine-appropriate lock/statement timeout SET when useful\n - Optional `R__*.sql` only if idempotent view/function refresh is required (explain why)\n - Minimal entity/repository notes so app code tolerates expand before contract\n - CI snippet or test note: `flyway validate` / `info` or Boot test with validate-on-migrate + ephemeral DB\n - AKS/K8s ordering note: migrate-before-rollout or equivalent; no public secrets in SQL\n\n4. Verification checklist\n - Fresh migrate + restart succeeds\n - `flyway validate` clean; checksums of old versions unchanged\n - Old app binary still works against expanded schema (if expand)\n - Grep for secrets in SQL; confirm no `clean` enabled for shared envs\n - Residual risks: long locks, large backfills, repair caveats (repair is not rollback)\n\nConstraints:\n- Forward-only: do not edit already-applied versioned migrations; do not invent fake checksums.\n- Secrets never in SQL \u2014 use `{{PLACEHOLDER}}` names only for non-secret identifiers.\n- Do not enable `out-of-order` or `clean` for prod-like profiles unless the repo already has a documented hotfix process (then call it out, do not silently turn on).\n- Do not claim Flyway auto-rollback; prescribe expand/contract instead.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize instructions for GitHub Copilot, Claude Code, and Codex \u2014 concrete paths and checklists over essays.\n\nOutput format:\n1. Short plan (classification + version bump)\n2. File diffs / full new SQL\n3. Config/CI/K8s notes (only what changed)\n4. Verification checklist\n5. Residual risks and follow-up contract PR (if any)\n\nStart from {{MIGRATION_DIR}} and Flyway config under {{SERVICE_PATH}}. Prefer patches over vague advice.\n" }, { "id": "add-testcontainers-integration-tests", @@ -328,7 +328,7 @@ "docker" ], "formatNotes": "All three. Point the tool at the service module, existing tests, and build file first. Prefer extending an existing container base over inventing a second lifecycle.", - "body": "Task: Add hermetic Spring Boot integration tests using Testcontainers for the module at the path I provide.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / service path: {{MODULE_PATH}}\n- Dependencies to containerize: {{DEPS}} (e.g. Postgres 16, Kafka, Redis, LocalStack S3)\n- Test style in-repo: {{TEST_STYLE}} (JUnit 5, @SpringBootTest, @DataJpaTest, RestAssured/WebTestClient, etc.)\n- Build command: {{TEST_COMMAND}} (e.g. ./mvnw -pl service-x test)\n- Migrations: {{MIGRATIONS}} (Flyway / Liquibase / none)\n\nRequirements:\n\n1. Inventory\n - Existing Testcontainers usage, `@ServiceConnection`, `DynamicPropertySource`, or abstract container bases\n - Spring Boot version signals (3.1+ service connections vs older patterns)\n - Build BOM / testcontainers dependencies already present\n - Whether CI runners already expose Docker\n - Any tests currently pointed at localhost or staging URLs\n\n2. Design\n - Prefer the narrowest slice that still hits the real adapter (`@DataJpaTest` vs full `@SpringBootTest`)\n - One shared container lifecycle per suite (static singleton or Spring-managed); do not start a new DB per method unless isolation is under test\n - Pin image tags (no `latest`); wire JDBC/broker settings from the container\n - Run migrations in the test context when {{MIGRATIONS}} is Flyway/Liquibase\n - Keep mocks only at true external boundaries not being validated\n\n3. Author artifacts (prefer concrete diffs)\n - Test dependency tweaks if the BOM does not already manage Testcontainers\n - Shared container helper or `@TestConfiguration`\n - 2–3 tests: happy path, one validation/constraint failure, one not-found or duplicate-key mapping\n - `application-test` overrides only when service connection cannot cover a property\n - CI note: Docker requirement; fail fast if unavailable\n\n4. Verification\n - Run {{TEST_COMMAND}} and show results\n - Confirm containers stop cleanly (no orphaned Postgres on the daemon)\n - Grep test resources for staging hosts, real secrets, and unpinned `latest` images\n\nConstraints:\n- Do not invent registry mirrors, company image prefixes, or cloud account IDs — use placeholders if the repo does not define them.\n- Do not disable Flyway/Liquibase in tests when production relies on it.\n- Do not replace an existing shared container base with a duplicate lifecycle.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete paths and commands over essays.\n\nOutput format:\n1. Short plan (slice + images + lifecycle)\n2. File diffs\n3. Commands run + outcomes\n4. What remains mocked (and why)\n5. Residual risks (CI Docker, parallel suites, image pull time)\n\nStart from {{MODULE_PATH}} and existing `src/test`. Prefer patches over vague advice.\n" + "body": "Task: Add hermetic Spring Boot integration tests using Testcontainers for the module at the path I provide.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / service path: {{MODULE_PATH}}\n- Dependencies to containerize: {{DEPS}} (e.g. Postgres 16, Kafka, Redis, LocalStack S3)\n- Test style in-repo: {{TEST_STYLE}} (JUnit 5, @SpringBootTest, @DataJpaTest, RestAssured/WebTestClient, etc.)\n- Build command: {{TEST_COMMAND}} (e.g. ./mvnw -pl service-x test)\n- Migrations: {{MIGRATIONS}} (Flyway / Liquibase / none)\n\nRequirements:\n\n1. Inventory\n - Existing Testcontainers usage, `@ServiceConnection`, `DynamicPropertySource`, or abstract container bases\n - Spring Boot version signals (3.1+ service connections vs older patterns)\n - Build BOM / testcontainers dependencies already present\n - Whether CI runners already expose Docker\n - Any tests currently pointed at localhost or staging URLs\n\n2. Design\n - Prefer the narrowest slice that still hits the real adapter (`@DataJpaTest` vs full `@SpringBootTest`)\n - One shared container lifecycle per suite (static singleton or Spring-managed); do not start a new DB per method unless isolation is under test\n - Pin image tags (no `latest`); wire JDBC/broker settings from the container\n - Run migrations in the test context when {{MIGRATIONS}} is Flyway/Liquibase\n - Keep mocks only at true external boundaries not being validated\n\n3. Author artifacts (prefer concrete diffs)\n - Test dependency tweaks if the BOM does not already manage Testcontainers\n - Shared container helper or `@TestConfiguration`\n - 2\u20133 tests: happy path, one validation/constraint failure, one not-found or duplicate-key mapping\n - `application-test` overrides only when service connection cannot cover a property\n - CI note: Docker requirement; fail fast if unavailable\n\n4. Verification\n - Run {{TEST_COMMAND}} and show results\n - Confirm containers stop cleanly (no orphaned Postgres on the daemon)\n - Grep test resources for staging hosts, real secrets, and unpinned `latest` images\n\nConstraints:\n- Do not invent registry mirrors, company image prefixes, or cloud account IDs \u2014 use placeholders if the repo does not define them.\n- Do not disable Flyway/Liquibase in tests when production relies on it.\n- Do not replace an existing shared container base with a duplicate lifecycle.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize for GitHub Copilot, Claude Code, and Codex \u2014 concrete paths and commands over essays.\n\nOutput format:\n1. Short plan (slice + images + lifecycle)\n2. File diffs\n3. Commands run + outcomes\n4. What remains mocked (and why)\n5. Residual risks (CI Docker, parallel suites, image pull time)\n\nStart from {{MODULE_PATH}} and existing `src/test`. Prefer patches over vague advice.\n" }, { "id": "harden-spring-oauth2-resource-server", @@ -348,7 +348,7 @@ "security" ], "formatNotes": "All three. Point the tool at the security config package, application*.yml, and existing auth tests first. Prefer patching the existing SecurityFilterChain over adding a second permissive chain.", - "body": "Task: Harden the Spring Boot OAuth2 resource-server configuration for the module at the path I provide.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / service path: {{MODULE_PATH}}\n- IdP issuer URL: {{ISSUER_URI}}\n- Expected audience / API identifier: {{AUDIENCE}}\n- Token type: {{TOKEN_TYPE}} (jwt | opaque)\n- Authority source: {{AUTHORITY_CLAIM}} (e.g. scope → SCOPE_, roles claim path, Keycloak realm_access)\n- Build / test command: {{TEST_COMMAND}} (e.g. ./mvnw -pl service-api test)\n- Mixed browser+API app?: {{MIXED_CLIENTS}} (yes | no)\n\nRequirements:\n\n1. Inventory\n - Existing `SecurityFilterChain`, `oauth2ResourceServer`, `JwtDecoder`, converters\n - `spring.security.oauth2.resourceserver.*` properties per profile\n - CSRF, session creation policy, CORS, actuator exposure\n - Current tests (`@WithMockUser`, `jwt()` post-processor, mock `JwtDecoder`)\n - Any `permitAll`, disabled security, or multi-issuer hacks\n\n2. Design\n - Prefer `issuer-uri` for {{TOKEN_TYPE}}=jwt; if only JWKS is possible, add issuer + audience validators\n - Enforce {{AUDIENCE}}; reject wrong-`aud` tokens\n - Map {{AUTHORITY_CLAIM}} via `JwtAuthenticationConverter` when non-default\n - If {{MIXED_CLIENTS}}=yes, split filter chains (cookie/CSRF vs stateless bearer); if no, STATELESS + CSRF off with a one-line rationale\n - Keep actuators authenticated or on a separate management port — not anonymous on the public API port\n - Opaque tokens: introspection config only; do not parse as JWT\n\n3. Author artifacts (prefer concrete diffs)\n - Security config + property updates for {{ISSUER_URI}} / validators\n - Converter + route/`@PreAuthorize` alignment (minimal path set)\n - Tests: valid scoped call; 401 expired/wrong iss/aud; 403 missing scope\n - Do not add IdP client secrets to git; use env/Key Vault placeholders already in-repo\n\n4. Verification\n - Run {{TEST_COMMAND}} and show results\n - Grep for `permitAll`, `csrf.disable`, `security.enable=false`, hard-coded PEMs, and logged `Authorization` headers\n - Confirm prod profile still requires JWT validation\n\nConstraints:\n- Do not invent tenant IDs, real client secrets, or JWKS PEMs — use placeholders if missing.\n- Do not disable security under prod (or default) profiles.\n- Do not replace an existing well-structured filter chain with a permissive catch-all.\n- Keep the diff minimal; no unrelated refactors or dependency upgrades unless required for resource-server.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete paths and commands over essays.\n\nOutput format:\n1. Short plan (decoder, audience, authority map, CSRF/session choice)\n2. File diffs\n3. Commands run + outcomes\n4. Remaining `permitAll` / anonymous paths (and why)\n5. Residual risks (multi-tenant issuers, opaque revocation, actuator network exposure)\n\nStart from {{MODULE_PATH}} security config and `application*.yml`. Prefer patches over vague advice.\n" + "body": "Task: Harden the Spring Boot OAuth2 resource-server configuration for the module at the path I provide.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / service path: {{MODULE_PATH}}\n- IdP issuer URL: {{ISSUER_URI}}\n- Expected audience / API identifier: {{AUDIENCE}}\n- Token type: {{TOKEN_TYPE}} (jwt | opaque)\n- Authority source: {{AUTHORITY_CLAIM}} (e.g. scope \u2192 SCOPE_, roles claim path, Keycloak realm_access)\n- Build / test command: {{TEST_COMMAND}} (e.g. ./mvnw -pl service-api test)\n- Mixed browser+API app?: {{MIXED_CLIENTS}} (yes | no)\n\nRequirements:\n\n1. Inventory\n - Existing `SecurityFilterChain`, `oauth2ResourceServer`, `JwtDecoder`, converters\n - `spring.security.oauth2.resourceserver.*` properties per profile\n - CSRF, session creation policy, CORS, actuator exposure\n - Current tests (`@WithMockUser`, `jwt()` post-processor, mock `JwtDecoder`)\n - Any `permitAll`, disabled security, or multi-issuer hacks\n\n2. Design\n - Prefer `issuer-uri` for {{TOKEN_TYPE}}=jwt; if only JWKS is possible, add issuer + audience validators\n - Enforce {{AUDIENCE}}; reject wrong-`aud` tokens\n - Map {{AUTHORITY_CLAIM}} via `JwtAuthenticationConverter` when non-default\n - If {{MIXED_CLIENTS}}=yes, split filter chains (cookie/CSRF vs stateless bearer); if no, STATELESS + CSRF off with a one-line rationale\n - Keep actuators authenticated or on a separate management port \u2014 not anonymous on the public API port\n - Opaque tokens: introspection config only; do not parse as JWT\n\n3. Author artifacts (prefer concrete diffs)\n - Security config + property updates for {{ISSUER_URI}} / validators\n - Converter + route/`@PreAuthorize` alignment (minimal path set)\n - Tests: valid scoped call; 401 expired/wrong iss/aud; 403 missing scope\n - Do not add IdP client secrets to git; use env/Key Vault placeholders already in-repo\n\n4. Verification\n - Run {{TEST_COMMAND}} and show results\n - Grep for `permitAll`, `csrf.disable`, `security.enable=false`, hard-coded PEMs, and logged `Authorization` headers\n - Confirm prod profile still requires JWT validation\n\nConstraints:\n- Do not invent tenant IDs, real client secrets, or JWKS PEMs \u2014 use placeholders if missing.\n- Do not disable security under prod (or default) profiles.\n- Do not replace an existing well-structured filter chain with a permissive catch-all.\n- Keep the diff minimal; no unrelated refactors or dependency upgrades unless required for resource-server.\n- Optimize for GitHub Copilot, Claude Code, and Codex \u2014 concrete paths and commands over essays.\n\nOutput format:\n1. Short plan (decoder, audience, authority map, CSRF/session choice)\n2. File diffs\n3. Commands run + outcomes\n4. Remaining `permitAll` / anonymous paths (and why)\n5. Residual risks (multi-tenant issuers, opaque revocation, actuator network exposure)\n\nStart from {{MODULE_PATH}} security config and `application*.yml`. Prefer patches over vague advice.\n" }, { "id": "wire-gha-oidc-azure-login", @@ -369,12 +369,12 @@ "migration" ], "formatNotes": "All three. Point the tool at `.github/workflows` and any existing `azure/login` or `AZURE_CLIENT_SECRET` usage first. Prefer replacing secret-based login over adding a parallel OIDC path. Copilot: apply instructions to workflow YAML. Claude Code: skill + workflow edits. Codex: AGENTS.md CI/OIDC section plus concrete workflow diff.", - "body": "Task: Wire GitHub Actions OIDC login to Azure (Microsoft Entra federated identity credentials) for the repository and environment I specify. Replace client-secret login where present.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Repository: {{REPO}} (org/name)\n- Entra application (client) ID: {{AZURE_CLIENT_ID}}\n- Tenant ID: {{AZURE_TENANT_ID}}\n- Subscription ID: {{AZURE_SUBSCRIPTION_ID}}\n- Target GitHub Environment (if used): {{TARGET_ENV}} (e.g. production, staging — or \"none\")\n- Azure RBAC roles needed by the pipeline: {{AZURE_ROLES}} (e.g. AcrPush on registry X, Contributor on RG Y)\n- Workflow file to change or create: {{WORKFLOW_PATH}}\n- FIC subject strategy: {{SUBJECT_STRATEGY}} (ref | environment | workflow_ref)\n- Use immutable GitHub OIDC subject (2026 guidance): {{IMMUTABLE_SUB}} (yes | no)\n\nRequirements:\n\n1. Inventory\n - Workflows for `azure/login`, `AZURE_CLIENT_SECRET`, or secret-based `az login`\n - `permissions:` defaults; `pull_request` / fork exposure\n - GitHub Environments and protection rules for {{TARGET_ENV}}\n - Existing Entra FIC (issuer, audience, subject)\n\n2. Design\n - OIDC `azure/login` with {{AZURE_CLIENT_ID}}, {{AZURE_TENANT_ID}}, {{AZURE_SUBSCRIPTION_ID}} (vars/secrets names only in output)\n - Job-level `permissions: id-token: write` on the Azure job only\n - FIC subject for {{SUBJECT_STRATEGY}} (ref / environment:{{TARGET_ENV}} / workflow_ref on {{WORKFLOW_PATH}})\n - If {{IMMUTABLE_SUB}}=yes: dual-FIC migration (add immutable, validate, remove name-based); note Flexible FIC / repository_id checks if available\n - Audience `api://AzureADTokenExchange` unless repo documents custom aud end-to-end\n - RBAC: {{AZURE_ROLES}} at minimal scope; no subscription Owner for CI\n - Deny fork `pull_request` paths from OIDC + {{TARGET_ENV}} deploy\n\n3. Author artifacts (prefer concrete diffs)\n - Workflow at {{WORKFLOW_PATH}}: pinned `azure/login`, permissions, triggers\n - PR notes: FIC fields (issuer, audience, exact subject string) — no secret values\n - RBAC bullets: role + scope; remove secret login — no parallel OIDC + secret paths\n\n4. Verification\n - Subject match checklist (GitHub `sub` vs Entra FIC)\n - Dry reasoning: allowed ref/env succeeds; wrong branch/env fails\n - Fork PR cannot get `id-token: write` with cloud deploy\n - Grep: no `AZURE_CLIENT_SECRET`, no token echo, pinned SHAs\n\nConstraints:\n- Do not invent IDs or client secrets — placeholders if missing.\n- No broad FIC subjects (`repo:ORG/REPO:*`).\n- Minimal diff; no unrelated workflow refactors.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete YAML and checklists.\n\nOutput format:\n1. Plan (subject, permissions, RBAC)\n2. Workflow diff for {{WORKFLOW_PATH}}\n3. Entra FIC + RBAC setup notes\n4. Verification checklist + fork PR denial\n5. Residual risks (immutable sub window, shared identity)\n\nStart from `.github/workflows` and {{WORKFLOW_PATH}}. Prefer replacing secret login over a second login path.\n" + "body": "Task: Wire GitHub Actions OIDC login to Azure (Microsoft Entra federated identity credentials) for the repository and environment I specify. Replace client-secret login where present.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Repository: {{REPO}} (org/name)\n- Entra application (client) ID: {{AZURE_CLIENT_ID}}\n- Tenant ID: {{AZURE_TENANT_ID}}\n- Subscription ID: {{AZURE_SUBSCRIPTION_ID}}\n- Target GitHub Environment (if used): {{TARGET_ENV}} (e.g. production, staging \u2014 or \"none\")\n- Azure RBAC roles needed by the pipeline: {{AZURE_ROLES}} (e.g. AcrPush on registry X, Contributor on RG Y)\n- Workflow file to change or create: {{WORKFLOW_PATH}}\n- FIC subject strategy: {{SUBJECT_STRATEGY}} (ref | environment | workflow_ref)\n- Use immutable GitHub OIDC subject (2026 guidance): {{IMMUTABLE_SUB}} (yes | no)\n\nRequirements:\n\n1. Inventory\n - Workflows for `azure/login`, `AZURE_CLIENT_SECRET`, or secret-based `az login`\n - `permissions:` defaults; `pull_request` / fork exposure\n - GitHub Environments and protection rules for {{TARGET_ENV}}\n - Existing Entra FIC (issuer, audience, subject)\n\n2. Design\n - OIDC `azure/login` with {{AZURE_CLIENT_ID}}, {{AZURE_TENANT_ID}}, {{AZURE_SUBSCRIPTION_ID}} (vars/secrets names only in output)\n - Job-level `permissions: id-token: write` on the Azure job only\n - FIC subject for {{SUBJECT_STRATEGY}} (ref / environment:{{TARGET_ENV}} / workflow_ref on {{WORKFLOW_PATH}})\n - If {{IMMUTABLE_SUB}}=yes: dual-FIC migration (add immutable, validate, remove name-based); note Flexible FIC / repository_id checks if available\n - Audience `api://AzureADTokenExchange` unless repo documents custom aud end-to-end\n - RBAC: {{AZURE_ROLES}} at minimal scope; no subscription Owner for CI\n - Deny fork `pull_request` paths from OIDC + {{TARGET_ENV}} deploy\n\n3. Author artifacts (prefer concrete diffs)\n - Workflow at {{WORKFLOW_PATH}}: pinned `azure/login`, permissions, triggers\n - PR notes: FIC fields (issuer, audience, exact subject string) \u2014 no secret values\n - RBAC bullets: role + scope; remove secret login \u2014 no parallel OIDC + secret paths\n\n4. Verification\n - Subject match checklist (GitHub `sub` vs Entra FIC)\n - Dry reasoning: allowed ref/env succeeds; wrong branch/env fails\n - Fork PR cannot get `id-token: write` with cloud deploy\n - Grep: no `AZURE_CLIENT_SECRET`, no token echo, pinned SHAs\n\nConstraints:\n- Do not invent IDs or client secrets \u2014 placeholders if missing.\n- No broad FIC subjects (`repo:ORG/REPO:*`).\n- Minimal diff; no unrelated workflow refactors.\n- Optimize for GitHub Copilot, Claude Code, and Codex \u2014 concrete YAML and checklists.\n\nOutput format:\n1. Plan (subject, permissions, RBAC)\n2. Workflow diff for {{WORKFLOW_PATH}}\n3. Entra FIC + RBAC setup notes\n4. Verification checklist + fork PR denial\n5. Residual risks (immutable sub window, shared identity)\n\nStart from `.github/workflows` and {{WORKFLOW_PATH}}. Prefer replacing secret login over a second login path.\n" }, { "id": "review-spring-data-jpa-queries", "title": "Review These Spring Data JPA Queries", - "whenToUse": "You need a PR-ready review or refactor of Spring Data JPA repositories, entity fetch plans, and service-layer query usage — N+1, pagination, projections, @Query safety, and index notes.", + "whenToUse": "You need a PR-ready review or refactor of Spring Data JPA repositories, entity fetch plans, and service-layer query usage \u2014 N+1, pagination, projections, @Query safety, and index notes.", "tools": [ "copilot", "claude-code", @@ -390,7 +390,7 @@ "review" ], "formatNotes": "All three. Point the tool at the repository package, entity package, and the service/controller call sites first. Prefer fixing fetch plans and projections over enabling open-in-view. Copilot: apply path-scoped instructions for `**/*Repository.java` and entity packages.", - "body": "Task: Review and harden Spring Data JPA queries and fetch plans for the feature I specify. Eliminate N+1 and pagination traps; prefer DTO projections on read paths; keep @Query parameterized and transactional boundaries clear.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / package root: {{PACKAGE_ROOT}} (e.g. com.example.orders)\n- Primary entities: {{ENTITIES}} (comma-separated)\n- Hot endpoints or use cases: {{USE_CASES}} (e.g. list orders, order detail, admin search)\n- Pagination style required: {{PAGINATION}} (Page | Slice | keyset | none)\n- Max page size: {{MAX_PAGE_SIZE}}\n- Open-in-view policy: {{OPEN_IN_VIEW}} (off | on-legacy | unknown)\n- Soft-delete in play: {{SOFT_DELETE}} (yes | no | unknown)\n- DB dialect: {{DB_DIALECT}} (PostgreSQL | MySQL | SQL Server | other)\n- Query-budget test harness available: {{QUERY_BUDGET}} (datasource-proxy | Hibernate statistics | none)\n\nRequirements:\n\n1. Inventory\n - Repositories under {{PACKAGE_ROOT}} touching {{ENTITIES}}\n - FetchType on associations; existing `@EntityGraph`, `JOIN FETCH`, `@BatchSize`\n - Call sites for {{USE_CASES}} (controller → service → repository)\n - Any `Pageable` + collection fetch combinations; `findAll` without bounds\n - Native/`@Query` strings; modifying queries; soft-delete filters if {{SOFT_DELETE}}=yes\n\n2. Design\n - Per {{USE_CASES}}: projection vs entity graph vs fetch join vs batch fetch\n - If {{PAGINATION}} needs collections: two-step ID page then fetch-by-ids (never collection JOIN FETCH + Pageable)\n - Cap page size at {{MAX_PAGE_SIZE}}; whitelist sort properties\n - Respect {{OPEN_IN_VIEW}}: if off/unknown, fetch or project inside `@Transactional(readOnly = true)`\n - Index notes for new WHERE/ORDER BY under {{DB_DIALECT}}\n - If {{QUERY_BUDGET}} ≠ none: add or outline a statement-count assertion for the hottest list path\n\n3. Author artifacts (prefer concrete diffs)\n - Repository method changes (`@EntityGraph`, `@Query`, projections)\n - Service transaction + DTO mapping adjustments\n - Optional Flyway/Liquibase index stub only if filters changed (do not invent unrelated schema)\n - Test sketches: result correctness + query budget when {{QUERY_BUDGET}} allows\n\n4. Verification\n - Explain why N+1 is gone for {{USE_CASES}}\n - Confirm no HHH90003004-style in-memory pagination\n - Grep: no entity returns on public API for list paths; no string-concat query parameters\n - Soft-delete + uniqueness notes if {{SOFT_DELETE}}=yes\n\nConstraints:\n- Do not invent schema or indexes unrelated to {{USE_CASES}}.\n- Minimal diff; match existing repository style (derived vs `@Query`).\n- No enabling open-in-view as a “fix” for LazyInitializationException.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete Java and checklists.\n\nOutput format:\n1. Plan (fetch strategy per use case)\n2. Code diffs (repository/service/DTO)\n3. Index / migration notes (if any)\n4. Verification checklist + query-budget evidence\n5. Residual risks (cartesian joins, soft-delete, count query cost)\n\nStart from repositories and entities under {{PACKAGE_ROOT}}. Prefer projections and explicit fetch plans over EAGER mappings or open-in-view.\n" + "body": "Task: Review and harden Spring Data JPA queries and fetch plans for the feature I specify. Eliminate N+1 and pagination traps; prefer DTO projections on read paths; keep @Query parameterized and transactional boundaries clear.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / package root: {{PACKAGE_ROOT}} (e.g. com.example.orders)\n- Primary entities: {{ENTITIES}} (comma-separated)\n- Hot endpoints or use cases: {{USE_CASES}} (e.g. list orders, order detail, admin search)\n- Pagination style required: {{PAGINATION}} (Page | Slice | keyset | none)\n- Max page size: {{MAX_PAGE_SIZE}}\n- Open-in-view policy: {{OPEN_IN_VIEW}} (off | on-legacy | unknown)\n- Soft-delete in play: {{SOFT_DELETE}} (yes | no | unknown)\n- DB dialect: {{DB_DIALECT}} (PostgreSQL | MySQL | SQL Server | other)\n- Query-budget test harness available: {{QUERY_BUDGET}} (datasource-proxy | Hibernate statistics | none)\n\nRequirements:\n\n1. Inventory\n - Repositories under {{PACKAGE_ROOT}} touching {{ENTITIES}}\n - FetchType on associations; existing `@EntityGraph`, `JOIN FETCH`, `@BatchSize`\n - Call sites for {{USE_CASES}} (controller \u2192 service \u2192 repository)\n - Any `Pageable` + collection fetch combinations; `findAll` without bounds\n - Native/`@Query` strings; modifying queries; soft-delete filters if {{SOFT_DELETE}}=yes\n\n2. Design\n - Per {{USE_CASES}}: projection vs entity graph vs fetch join vs batch fetch\n - If {{PAGINATION}} needs collections: two-step ID page then fetch-by-ids (never collection JOIN FETCH + Pageable)\n - Cap page size at {{MAX_PAGE_SIZE}}; whitelist sort properties\n - Respect {{OPEN_IN_VIEW}}: if off/unknown, fetch or project inside `@Transactional(readOnly = true)`\n - Index notes for new WHERE/ORDER BY under {{DB_DIALECT}}\n - If {{QUERY_BUDGET}} \u2260 none: add or outline a statement-count assertion for the hottest list path\n\n3. Author artifacts (prefer concrete diffs)\n - Repository method changes (`@EntityGraph`, `@Query`, projections)\n - Service transaction + DTO mapping adjustments\n - Optional Flyway/Liquibase index stub only if filters changed (do not invent unrelated schema)\n - Test sketches: result correctness + query budget when {{QUERY_BUDGET}} allows\n\n4. Verification\n - Explain why N+1 is gone for {{USE_CASES}}\n - Confirm no HHH90003004-style in-memory pagination\n - Grep: no entity returns on public API for list paths; no string-concat query parameters\n - Soft-delete + uniqueness notes if {{SOFT_DELETE}}=yes\n\nConstraints:\n- Do not invent schema or indexes unrelated to {{USE_CASES}}.\n- Minimal diff; match existing repository style (derived vs `@Query`).\n- No enabling open-in-view as a \u201cfix\u201d for LazyInitializationException.\n- Optimize for GitHub Copilot, Claude Code, and Codex \u2014 concrete Java and checklists.\n\nOutput format:\n1. Plan (fetch strategy per use case)\n2. Code diffs (repository/service/DTO)\n3. Index / migration notes (if any)\n4. Verification checklist + query-budget evidence\n5. Residual risks (cartesian joins, soft-delete, count query cost)\n\nStart from repositories and entities under {{PACKAGE_ROOT}}. Prefer projections and explicit fetch plans over EAGER mappings or open-in-view.\n" }, { "id": "wire-spring-cache-redis", @@ -430,7 +430,28 @@ "multi-module" ], "formatNotes": "All three. Point the tool at the root pom, module list, and the workflow that runs Maven. Prefer setup-java cache: maven over a custom actions/cache unless the repo already standardized on one. Copilot: path-scoped instructions for pom.xml and workflows. Claude Code: skill plus the workflow file. Codex: AGENTS.md Maven CI section, then the diff.", - "body": "Task: Tune or add Maven dependency caching and multi-module CI flags for the workflow I specify. Produce a small diff: correct cache paths/keys, wrapper usage, reactor command, and a short verification note.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Workflow path: {{WORKFLOW}}\n- Reactor root: {{REACTOR_ROOT}} (directory with the top-level pom.xml)\n- Modules of interest: {{MODULES}} (all | comma-separated artifactIds)\n- Cache style: {{CACHE_STYLE}} (setup-java | actions-cache | keep-existing)\n- Parallelism: {{PARALLEL}} (off | 1C | N threads)\n- Selective build: {{SELECTIVE}} (full-reactor | pl-am | pl-am-amd)\n- JDK version already in workflow: {{JDK}}\n\nRequirements:\n\n1. Inventory\n - Existing `actions/setup-java` / `actions/cache` steps and their paths, keys, restore-keys\n - Whether `./mvnw` exists and which Maven version the wrapper pins\n - Root packaging (`pom`) and module list under {{REACTOR_ROOT}}\n - Current Maven goals/flags (`verify`, `test`, `-DskipTests`, profiles)\n - Any committed or generated `settings.xml` / server credentials (names only — do not print secret values)\n - Prior CI duration clues in workflow comments or README, if any\n\n2. Design\n - {{CACHE_STYLE}}=setup-java: set `cache: maven` (and distribution/temurin or whatever the workflow already uses) with {{JDK}}. Do not add a second overlapping m2 cache unless keep-existing requires it.\n - {{CACHE_STYLE}}=actions-cache: `path: ~/.m2/repository`, key includes `runner.os` + hash of all relevant `pom.xml` (+ wrapper props). restore-keys prefix by OS only.\n - Never cache `**/target`. Remove such paths if present.\n - Invoke the wrapper from {{REACTOR_ROOT}} with `-B` and `-ntp`.\n - {{SELECTIVE}}=full-reactor: `./mvnw -B -ntp verify` (or the repo's standard lifecycle).\n - {{SELECTIVE}}=pl-am or pl-am-amd: document how {{MODULES}} are chosen; include `-am` / `-amd` as specified so the reactor resolves parents and dependents.\n - {{PARALLEL}}: add `-T 1C` or `-T N` only when safe; otherwise leave serial and say why.\n\n3. Author the workflow (and tiny docs) diff\n - Update {{WORKFLOW}} only as needed for cache + Maven command\n - If AGENTS.md / copilot-instructions already mention CI, add one line about m2 cache vs target — no new markdown files unless the repo already keeps agent docs\n - No new dependencies in poms unless the build cannot run without a fix you found (prefer workflow-only changes)\n\n4. Verification checklist\n - [ ] Cache path is `~/.m2/repository` (or setup-java maven cache) only\n - [ ] Key inputs include every pom that affects the reactor classpath\n - [ ] No `target/` in cache paths\n - [ ] Wrapper + `-B` (+ `-ntp`) used\n - [ ] {{SELECTIVE}} and {{PARALLEL}} match the workflow command\n - [ ] No secrets or mirror passwords introduced\n - [ ] Summarize expected HIT/MISS behavior after a leaf pom dependency bump\n\nConstraints:\n- Minimal diff. Match existing workflow style (action majors, concurrency, permissions).\n- Do not weaken `permissions:` or add `pull_request_target`.\n- Do not skip tests on the primary verify job unless the workflow already splits compile/test and you only touch the compile job's cache warm-up.\n- Optimize for GitHub Copilot, Claude Code, and Codex: concrete paths and checklists.\n\nOutput format:\n1. Plan (cache style, key inputs, reactor command)\n2. Diff (workflow, optional one-line agent doc)\n3. Verification checklist with what you would run\n4. Residual risks (snapshot churn, unsafe `-T`, selective-build gaps)\n\nStart from {{WORKFLOW}} and {{REACTOR_ROOT}}. Prefer `setup-java` `cache: maven` when {{CACHE_STYLE}} allows it.\n" + "body": "Task: Tune or add Maven dependency caching and multi-module CI flags for the workflow I specify. Produce a small diff: correct cache paths/keys, wrapper usage, reactor command, and a short verification note.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Workflow path: {{WORKFLOW}}\n- Reactor root: {{REACTOR_ROOT}} (directory with the top-level pom.xml)\n- Modules of interest: {{MODULES}} (all | comma-separated artifactIds)\n- Cache style: {{CACHE_STYLE}} (setup-java | actions-cache | keep-existing)\n- Parallelism: {{PARALLEL}} (off | 1C | N threads)\n- Selective build: {{SELECTIVE}} (full-reactor | pl-am | pl-am-amd)\n- JDK version already in workflow: {{JDK}}\n\nRequirements:\n\n1. Inventory\n - Existing `actions/setup-java` / `actions/cache` steps and their paths, keys, restore-keys\n - Whether `./mvnw` exists and which Maven version the wrapper pins\n - Root packaging (`pom`) and module list under {{REACTOR_ROOT}}\n - Current Maven goals/flags (`verify`, `test`, `-DskipTests`, profiles)\n - Any committed or generated `settings.xml` / server credentials (names only \u2014 do not print secret values)\n - Prior CI duration clues in workflow comments or README, if any\n\n2. Design\n - {{CACHE_STYLE}}=setup-java: set `cache: maven` (and distribution/temurin or whatever the workflow already uses) with {{JDK}}. Do not add a second overlapping m2 cache unless keep-existing requires it.\n - {{CACHE_STYLE}}=actions-cache: `path: ~/.m2/repository`, key includes `runner.os` + hash of all relevant `pom.xml` (+ wrapper props). restore-keys prefix by OS only.\n - Never cache `**/target`. Remove such paths if present.\n - Invoke the wrapper from {{REACTOR_ROOT}} with `-B` and `-ntp`.\n - {{SELECTIVE}}=full-reactor: `./mvnw -B -ntp verify` (or the repo's standard lifecycle).\n - {{SELECTIVE}}=pl-am or pl-am-amd: document how {{MODULES}} are chosen; include `-am` / `-amd` as specified so the reactor resolves parents and dependents.\n - {{PARALLEL}}: add `-T 1C` or `-T N` only when safe; otherwise leave serial and say why.\n\n3. Author the workflow (and tiny docs) diff\n - Update {{WORKFLOW}} only as needed for cache + Maven command\n - If AGENTS.md / copilot-instructions already mention CI, add one line about m2 cache vs target \u2014 no new markdown files unless the repo already keeps agent docs\n - No new dependencies in poms unless the build cannot run without a fix you found (prefer workflow-only changes)\n\n4. Verification checklist\n - [ ] Cache path is `~/.m2/repository` (or setup-java maven cache) only\n - [ ] Key inputs include every pom that affects the reactor classpath\n - [ ] No `target/` in cache paths\n - [ ] Wrapper + `-B` (+ `-ntp`) used\n - [ ] {{SELECTIVE}} and {{PARALLEL}} match the workflow command\n - [ ] No secrets or mirror passwords introduced\n - [ ] Summarize expected HIT/MISS behavior after a leaf pom dependency bump\n\nConstraints:\n- Minimal diff. Match existing workflow style (action majors, concurrency, permissions).\n- Do not weaken `permissions:` or add `pull_request_target`.\n- Do not skip tests on the primary verify job unless the workflow already splits compile/test and you only touch the compile job's cache warm-up.\n- Optimize for GitHub Copilot, Claude Code, and Codex: concrete paths and checklists.\n\nOutput format:\n1. Plan (cache style, key inputs, reactor command)\n2. Diff (workflow, optional one-line agent doc)\n3. Verification checklist with what you would run\n4. Residual risks (snapshot churn, unsafe `-T`, selective-build gaps)\n\nStart from {{WORKFLOW}} and {{REACTOR_ROOT}}. Prefer `setup-java` `cache: maven` when {{CACHE_STYLE}} allows it.\n" + }, + { + "id": "wire-k8s-probes-and-graceful-shutdown", + "title": "Wire Kubernetes Probes and Graceful Shutdown", + "whenToUse": "Add or fix startup/liveness/readiness probes and coordinated graceful shutdown (preStop + SIGTERM + app drain) for a Spring Boot or HTTP service on AKS/Kubernetes.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "kubernetes", + "aks", + "spring-boot", + "probes", + "graceful-shutdown", + "actuator", + "reliability" + ], + "formatNotes": "All three. Point the tool at the Deployment or Helm chart values/templates and the Spring `application*.yml` (or equivalent). Prefer Actuator liveness/readiness groups when the app is Spring Boot; otherwise `/livez` and `/readyz`. Copilot: path-scoped instructions for manifests and application config. Claude Code: skill plus the workload manifest. Codex: AGENTS.md probes section, then the diff.", + "body": "Task: Wire or harden Kubernetes probes and graceful shutdown for the workload I specify. Produce a small diff: probe block, lifecycle preStop, terminationGracePeriodSeconds, and app shutdown config \u2014 plus a short verification note.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Workload manifest or chart: {{WORKLOAD}} (Deployment YAML path or Helm chart dir)\n- App config path: {{APP_CONFIG}} (application.yml / application.properties / none)\n- Runtime: {{RUNTIME}} (spring-boot | generic-http)\n- Probe port: {{PROBE_PORT}} (main | management | number)\n- Cold-start budget seconds: {{STARTUP_BUDGET}} (e.g. 120)\n- Drain budget seconds: {{DRAIN_BUDGET}} (preStop sleep + shutdown phase, e.g. 45)\n- Health base path: {{HEALTH_BASE}} (default /actuator/health or /)\n\nRequirements:\n\n1. Inventory\n - Existing startupProbe / livenessProbe / readinessProbe paths, ports, timings\n - Whether Actuator (or livez/readyz) exists and on which port\n - Current `server.shutdown`, lifecycle timeouts, entrypoint/CMD (signal forwarding)\n - Current `terminationGracePeriodSeconds` and any `lifecycle.preStop`\n - RollingUpdate strategy / PDB if present (do not redesign capacity unless probes force it)\n\n2. Design\n - {{RUNTIME}}=spring-boot: enable health probes if needed; liveness \u2192 `{{HEALTH_BASE}}/liveness`; readiness \u2192 `{{HEALTH_BASE}}/readiness`; keep liveness free of DB/broker checks\n - {{RUNTIME}}=generic-http: use `/livez` and `/readyz` (or the repo\u2019s existing paths); do not invent a heavyweight health stack\n - Add startupProbe with period/failureThreshold covering {{STARTUP_BUDGET}}\n - Set readiness/liveness periods and failureThresholds that tolerate brief GC without restart storms\n - Enable graceful shutdown in {{APP_CONFIG}} when Spring Boot; set `spring.lifecycle.timeout-per-shutdown-phase` to a value that fits {{DRAIN_BUDGET}}\n - Add `preStop` sleep (10\u201315s unless the chart already standardized another value)\n - Set `terminationGracePeriodSeconds` \u2265 preStop + shutdown phase + ~5\u201310s buffer\n - Probe {{PROBE_PORT}} consistently with the containerPort that serves that path\n\n3. Author the diff\n - Update {{WORKLOAD}} (and {{APP_CONFIG}} if Spring) only as needed\n - Match existing YAML style (Helm helpers, indent, probe field order)\n - One-line comment above non-default thresholds explaining the startup/drain math is welcome; no new markdown files unless the repo already keeps agent docs\n - Do not widen Actuator exposure (`include=*`) or publish management on a public Service \u2014 flag that for a separate change if you find it\n\n4. Verification checklist\n - [ ] startup / liveness / readiness are distinct and paths match the app\n - [ ] Liveness has no remote dependency checks\n - [ ] Graceful shutdown config present (or N/A with justification for generic-http)\n - [ ] preStop sleep + shutdown timeout fit inside terminationGracePeriodSeconds\n - [ ] Probe port matches containerPort / management port layout\n - [ ] Summarize expected behavior on rolling update and on brief dependency outage\n\nConstraints:\n- Minimal diff. Do not refactor unrelated chart structure, mesh config, or HPA.\n- Do not switch probe type to exec/tcp unless HTTP truly cannot work.\n- Optimize for GitHub Copilot, Claude Code, and Codex: concrete paths and checklists.\n- No secrets, no cluster-admin changes, no AI/tool attribution in commits.\n\nOutput format:\n1. Plan (probe paths/ports, startup math, drain budget)\n2. Diff (manifest/chart + app config)\n3. Verification checklist with kubectl/port-forward steps\n4. Residual risks (signal forwarding, mesh drain, management-port split-brain)\n\nStart from {{WORKLOAD}} and {{APP_CONFIG}}. Prefer Actuator liveness/readiness groups when {{RUNTIME}} is spring-boot.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index f53f256..bf6e007 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -21,8 +21,8 @@ "spring-boot", "microservices" ], - "formatNotes": "All three: paste the body as standing project guidance. Copilot → `.github/copilot-instructions.md` or `.github/instructions/spring.instructions.md` with applyTo for `**/*.{java,xml,yml}`. Claude Code → `.claude/skills/spring-boot-guardrails/SKILL.md` (YAML frontmatter + body) or a short pointer in `CLAUDE.md`. Codex → section in root `AGENTS.md` or a linked `docs/agents/spring-boot.md`.", - "body": "# Skill: Spring Boot Service Guardrails\n\n## Goal\nProduce production-ready Spring Boot changes that are secure, testable, and consistent with layered architecture.\n\n## When to apply\n- New REST endpoints, services, repositories, or configuration\n- Refactors that touch request validation, auth, or persistence\n\n## Architecture rules\n1. Keep controllers thin: validate input, map DTO ↔ domain, call one service method, map errors.\n2. Business rules live in services; repositories do persistence only.\n3. Prefer constructor injection; never field-inject `@Autowired` on production beans.\n4. Use explicit DTOs at the API boundary; do not expose JPA entities in responses.\n5. Fail closed on authz: deny by default, document required authorities on each endpoint.\n\n## Implementation steps\n1. Locate existing package layout and match naming (`...controller`, `...service`, `...repository`).\n2. Add/adjust request validation (`@Valid`, Bean Validation constraints) before business logic.\n3. Map domain errors to stable problem responses (status + code + safe message).\n4. Add unit tests for service rules and at least one WebMvc/WebTestClient slice for the endpoint.\n5. Update OpenAPI/annotations only when the public contract changes.\n\n## Constraints\n- No secrets in code, logs, or test fixtures.\n- Do not weaken CSRF/security config unless the change is explicitly about security and reviewed.\n- Prefer existing project libraries over new dependencies.\n- Keep methods small; extract helpers instead of deep nesting.\n\n## Output format\n- Summary of files touched (bullets)\n- Code changes ready to apply\n- Test plan: commands to run + cases covered\n- Residual risks (auth, migrations, breaking API)" + "formatNotes": "All three: paste the body as standing project guidance. Copilot \u2192 `.github/copilot-instructions.md` or `.github/instructions/spring.instructions.md` with applyTo for `**/*.{java,xml,yml}`. Claude Code \u2192 `.claude/skills/spring-boot-guardrails/SKILL.md` (YAML frontmatter + body) or a short pointer in `CLAUDE.md`. Codex \u2192 section in root `AGENTS.md` or a linked `docs/agents/spring-boot.md`.", + "body": "# Skill: Spring Boot Service Guardrails\n\n## Goal\nProduce production-ready Spring Boot changes that are secure, testable, and consistent with layered architecture.\n\n## When to apply\n- New REST endpoints, services, repositories, or configuration\n- Refactors that touch request validation, auth, or persistence\n\n## Architecture rules\n1. Keep controllers thin: validate input, map DTO \u2194 domain, call one service method, map errors.\n2. Business rules live in services; repositories do persistence only.\n3. Prefer constructor injection; never field-inject `@Autowired` on production beans.\n4. Use explicit DTOs at the API boundary; do not expose JPA entities in responses.\n5. Fail closed on authz: deny by default, document required authorities on each endpoint.\n\n## Implementation steps\n1. Locate existing package layout and match naming (`...controller`, `...service`, `...repository`).\n2. Add/adjust request validation (`@Valid`, Bean Validation constraints) before business logic.\n3. Map domain errors to stable problem responses (status + code + safe message).\n4. Add unit tests for service rules and at least one WebMvc/WebTestClient slice for the endpoint.\n5. Update OpenAPI/annotations only when the public contract changes.\n\n## Constraints\n- No secrets in code, logs, or test fixtures.\n- Do not weaken CSRF/security config unless the change is explicitly about security and reviewed.\n- Prefer existing project libraries over new dependencies.\n- Keep methods small; extract helpers instead of deep nesting.\n\n## Output format\n- Summary of files touched (bullets)\n- Code changes ready to apply\n- Test plan: commands to run + cases covered\n- Residual risks (auth, migrations, breaking API)" }, { "id": "aks-workload-hardening", @@ -39,7 +39,7 @@ "kubernetes" ], "formatNotes": "All three. Copilot path-scoped instructions for `**/k8s/**`, `**/helm/**`, `**/*.{yaml,yml}`. Claude Code skill under `.claude/skills/aks-hardening/SKILL.md`. Codex: nested `deploy/AGENTS.md` or root `AGENTS.md` section titled AKS.", - "body": "# Skill: AKS Workload Hardening\n\n## Goal\nShip Kubernetes workloads to AKS that are operable, least-privilege, and reviewable.\n\n## When to apply\n- New Deployment/StatefulSet/Job, Service, Ingress/Gateway, HPA, NetworkPolicy, or Helm values\n- Reviews of manifests before merge to the deploy path\n\n## Checklist (apply in order)\n1. **Identity**: prefer workload identity / managed identity over long-lived secrets in pods.\n2. **Resources**: set requests and limits; document why limits differ from requests.\n3. **Probes**: readiness + liveness (and startup when cold start is slow); probes must not be identical if that hides failure.\n4. **Security context**: runAsNonRoot, readOnlyRootFilesystem when feasible, drop ALL capabilities, no privileged.\n5. **Networking**: explicit Service ports; NetworkPolicy default-deny + allowlist if the cluster uses policies.\n6. **Rollouts**: rollingUpdate maxUnavailable/maxSurge; PodDisruptionBudget for user-facing services.\n7. **Observability**: consistent labels (`app`, `version`, `team`); scrape annotations or OpenTelemetry only if the platform expects them.\n8. **Secrets**: reference Key Vault / CSI / external secrets — never commit raw credentials.\n\n## Azure-specific notes\n- Prefer Azure CNI / documented cluster networking patterns already used in-repo.\n- Align ingress class, TLS secrets, and public vs private exposure with existing apps.\n- For AKS node pools, avoid hostPath and hostNetwork unless the platform team already uses them for that component.\n\n## Constraints\n- Do not invent cluster-wide CRDs or operators that are not already installed.\n- Keep manifests idempotent and environment-parameterized (overlays/values), not hardcoded subscription IDs in app charts.\n\n## Output format\n- Diff-oriented manifest changes\n- Table: control → status (pass/fail/n/a) → note\n- Commands to validate (`kubectl dry-run` / `helm template` / policy checks used in-repo)" + "body": "# Skill: AKS Workload Hardening\n\n## Goal\nShip Kubernetes workloads to AKS that are operable, least-privilege, and reviewable.\n\n## When to apply\n- New Deployment/StatefulSet/Job, Service, Ingress/Gateway, HPA, NetworkPolicy, or Helm values\n- Reviews of manifests before merge to the deploy path\n\n## Checklist (apply in order)\n1. **Identity**: prefer workload identity / managed identity over long-lived secrets in pods.\n2. **Resources**: set requests and limits; document why limits differ from requests.\n3. **Probes**: readiness + liveness (and startup when cold start is slow); probes must not be identical if that hides failure.\n4. **Security context**: runAsNonRoot, readOnlyRootFilesystem when feasible, drop ALL capabilities, no privileged.\n5. **Networking**: explicit Service ports; NetworkPolicy default-deny + allowlist if the cluster uses policies.\n6. **Rollouts**: rollingUpdate maxUnavailable/maxSurge; PodDisruptionBudget for user-facing services.\n7. **Observability**: consistent labels (`app`, `version`, `team`); scrape annotations or OpenTelemetry only if the platform expects them.\n8. **Secrets**: reference Key Vault / CSI / external secrets \u2014 never commit raw credentials.\n\n## Azure-specific notes\n- Prefer Azure CNI / documented cluster networking patterns already used in-repo.\n- Align ingress class, TLS secrets, and public vs private exposure with existing apps.\n- For AKS node pools, avoid hostPath and hostNetwork unless the platform team already uses them for that component.\n\n## Constraints\n- Do not invent cluster-wide CRDs or operators that are not already installed.\n- Keep manifests idempotent and environment-parameterized (overlays/values), not hardcoded subscription IDs in app charts.\n\n## Output format\n- Diff-oriented manifest changes\n- Table: control \u2192 status (pass/fail/n/a) \u2192 note\n- Commands to validate (`kubectl dry-run` / `helm template` / policy checks used in-repo)" }, { "id": "gha-devsecops-pipeline", @@ -56,7 +56,7 @@ "ci" ], "formatNotes": "All three. Copilot: `.github/instructions/actions.instructions.md` with applyTo `**/.github/workflows/*.yml`. Claude Code: skill `gha-devsecops`. Codex: `AGENTS.md` CI section + link to workflow conventions.", - "body": "# Skill: GitHub Actions DevSecOps Pipeline\n\n## Goal\nProduce workflows that are pinned, least-privilege, cached sensibly, and fail on real security findings.\n\n## When to apply\n- New CI/CD workflows or reusable workflows\n- Adding scanners, OIDC deploy, or environment protections\n\n## Required patterns\n1. Pin actions by full commit SHA (not floating major tags) when the repo already does so; otherwise pin to a verified major and note follow-up.\n2. Set `permissions:` explicitly at workflow or job level — default to read, escalate per job.\n3. Prefer OIDC to cloud roles over long-lived cloud keys in GitHub secrets.\n4. Separate build/test from deploy; deploy only from protected environments/branches.\n5. Cache dependencies with precise keys; never cache credentials or built secrets.\n6. Upload SBOMs / scan results as artifacts when the pipeline already expects them.\n\n## Security gates (minimum)\n- Dependency vulnerability scan (language-appropriate)\n- Secret scan on the diff or full repo as configured by the org\n- SAST or linter gate that blocks on high severity when tools exist in-repo\n- Container image scan before push/promote if images are produced\n\n## Implementation steps\n1. Mirror structure of an existing healthy workflow in the repo.\n2. Add jobs with clear names; use `needs:` for the security → build → deploy chain.\n3. Parameterize versions via `env:` at the top.\n4. Document required secrets/vars in a short header comment (names only, never values).\n5. Add a dry-run or `workflow_dispatch` path for risky deploys.\n\n## Constraints\n- No `pull_request_target` with untrusted checkout + secrets unless following org-approved pattern.\n- Avoid `curl | bash` installers; use setup actions or package managers.\n- Do not echo secrets; mask sensitive outputs.\n\n## Output format\n- Complete workflow YAML (or surgical patch)\n- Permission matrix per job\n- How to verify locally / with `act` if used\n- Residual risks and follow-ups" + "body": "# Skill: GitHub Actions DevSecOps Pipeline\n\n## Goal\nProduce workflows that are pinned, least-privilege, cached sensibly, and fail on real security findings.\n\n## When to apply\n- New CI/CD workflows or reusable workflows\n- Adding scanners, OIDC deploy, or environment protections\n\n## Required patterns\n1. Pin actions by full commit SHA (not floating major tags) when the repo already does so; otherwise pin to a verified major and note follow-up.\n2. Set `permissions:` explicitly at workflow or job level \u2014 default to read, escalate per job.\n3. Prefer OIDC to cloud roles over long-lived cloud keys in GitHub secrets.\n4. Separate build/test from deploy; deploy only from protected environments/branches.\n5. Cache dependencies with precise keys; never cache credentials or built secrets.\n6. Upload SBOMs / scan results as artifacts when the pipeline already expects them.\n\n## Security gates (minimum)\n- Dependency vulnerability scan (language-appropriate)\n- Secret scan on the diff or full repo as configured by the org\n- SAST or linter gate that blocks on high severity when tools exist in-repo\n- Container image scan before push/promote if images are produced\n\n## Implementation steps\n1. Mirror structure of an existing healthy workflow in the repo.\n2. Add jobs with clear names; use `needs:` for the security \u2192 build \u2192 deploy chain.\n3. Parameterize versions via `env:` at the top.\n4. Document required secrets/vars in a short header comment (names only, never values).\n5. Add a dry-run or `workflow_dispatch` path for risky deploys.\n\n## Constraints\n- No `pull_request_target` with untrusted checkout + secrets unless following org-approved pattern.\n- Avoid `curl | bash` installers; use setup actions or package managers.\n- Do not echo secrets; mask sensitive outputs.\n\n## Output format\n- Complete workflow YAML (or surgical patch)\n- Permission matrix per job\n- How to verify locally / with `act` if used\n- Residual risks and follow-ups" }, { "id": "jwt-oauth-security-review", @@ -72,8 +72,8 @@ "oauth", "security" ], - "formatNotes": "All three. Keep this skill concise — security rules first. Copilot instructions file for auth packages; Claude Code skill with clear description triggers; Codex `AGENTS.md` Security section.", - "body": "# Skill: JWT / OAuth Security Review\n\n## Goal\nEnsure token-based auth is validated correctly and fails safely.\n\n## When to apply\n- Resource server / API gateway JWT middleware\n- Authorization code + PKCE, client credentials, or token exchange flows\n- Custom claim mapping into roles/permissions\n\n## Validation requirements\n1. Verify signature with the correct JWKS/issuer keys; reject `alg=none` and unexpected algorithms.\n2. Validate `iss`, `aud` (or equivalent), `exp`, `nbf`, and token use (`typ` / `token_use`) as required by the IdP.\n3. Prefer asymmetric algorithms (RS256/ES256) over shared HMAC for multi-service APIs.\n4. Map scopes/roles explicitly; do not treat presence of a JWT as authorization for every route.\n5. Clock skew: small leeway only; document the value.\n\n## Common anti-patterns to reject\n- Decoding payload without verifying signature\n- Accepting tokens from multiple issuers without an allowlist\n- Logging raw tokens or authorization headers\n- Storing refresh tokens in localStorage for confidential apps without a deliberate threat model\n- Using access tokens as proof of email/identity without checking IdP claims\n\n## Review steps\n1. Identify token entry points (filters, middleware, gateway).\n2. Trace claim → permission mapping.\n3. Confirm error paths return generic 401/403 without leaking key material.\n4. Check test coverage for expired, wrong-aud, wrong-iss, and tampered tokens.\n\n## Output format\n- Findings ordered by severity (blocker / major / minor)\n- Recommended code or config change per finding\n- Test cases to add (table)\n- Explicit “out of scope” notes" + "formatNotes": "All three. Keep this skill concise \u2014 security rules first. Copilot instructions file for auth packages; Claude Code skill with clear description triggers; Codex `AGENTS.md` Security section.", + "body": "# Skill: JWT / OAuth Security Review\n\n## Goal\nEnsure token-based auth is validated correctly and fails safely.\n\n## When to apply\n- Resource server / API gateway JWT middleware\n- Authorization code + PKCE, client credentials, or token exchange flows\n- Custom claim mapping into roles/permissions\n\n## Validation requirements\n1. Verify signature with the correct JWKS/issuer keys; reject `alg=none` and unexpected algorithms.\n2. Validate `iss`, `aud` (or equivalent), `exp`, `nbf`, and token use (`typ` / `token_use`) as required by the IdP.\n3. Prefer asymmetric algorithms (RS256/ES256) over shared HMAC for multi-service APIs.\n4. Map scopes/roles explicitly; do not treat presence of a JWT as authorization for every route.\n5. Clock skew: small leeway only; document the value.\n\n## Common anti-patterns to reject\n- Decoding payload without verifying signature\n- Accepting tokens from multiple issuers without an allowlist\n- Logging raw tokens or authorization headers\n- Storing refresh tokens in localStorage for confidential apps without a deliberate threat model\n- Using access tokens as proof of email/identity without checking IdP claims\n\n## Review steps\n1. Identify token entry points (filters, middleware, gateway).\n2. Trace claim \u2192 permission mapping.\n3. Confirm error paths return generic 401/403 without leaking key material.\n4. Check test coverage for expired, wrong-aud, wrong-iss, and tampered tokens.\n\n## Output format\n- Findings ordered by severity (blocker / major / minor)\n- Recommended code or config change per finding\n- Test cases to add (table)\n- Explicit \u201cout of scope\u201d notes" }, { "id": "data-platform-pipeline-review", @@ -90,7 +90,7 @@ "pipelines" ], "formatNotes": "All three. Avoid embedding tenant-specific connection strings. Copilot path rules for notebook/ETL folders; Claude Code skill; Codex nested `AGENTS.md` under data pipelines.", - "body": "# Skill: Data Platform Pipeline Review\n\n## Goal\nDeliver data pipelines that are idempotent, observable, and safe for sensitive fields.\n\n## When to apply\n- New Databricks jobs/notebooks, Spark transformations, or ADF/Fabric-style pipelines\n- Schema changes, backfills, or catch-up loads\n\n## Design rules\n1. **Contracts first**: define input/output schemas and ownership before coding transforms.\n2. **Idempotency**: merges/upserts keyed by business keys; safe re-runs without duplicating facts.\n3. **Partitioning**: choose partition columns for query patterns; avoid tiny-file explosion.\n4. **Quality gates**: null checks, referential checks, and row-count anomalies before publish.\n5. **PII/PHI**: classify columns; tokenize/hash/mask per platform standards; least-privilege access.\n6. **Orchestration**: clear dependencies, retries with backoff, and dead-letter / failure paths.\n7. **Cost**: cache only when reused; prune unused columns early; right-size clusters/pools.\n\n## Implementation steps\n1. Sketch source → bronze/silver/gold (or in-repo layering names) data flow.\n2. Implement transforms with explicit schemas; avoid `select *` across trust boundaries.\n3. Add data quality checks as jobs/tasks that block downstream publish on failure.\n4. Emit metrics/logs with run id, batch window, and row counts.\n5. Document backfill procedure and watermark strategy.\n\n## Constraints\n- Do not invent employer-specific catalog names, secrets, or subscription IDs.\n- Prefer existing platform libraries and patterns in the repository.\n- No production writes from ad-hoc interactive sessions in committed jobs.\n\n## Output format\n- Pipeline diagram (mermaid or bullet edges)\n- Task list with inputs/outputs\n- Risk register (data loss, late data, PII)\n- Validation queries / checks to run after deploy" + "body": "# Skill: Data Platform Pipeline Review\n\n## Goal\nDeliver data pipelines that are idempotent, observable, and safe for sensitive fields.\n\n## When to apply\n- New Databricks jobs/notebooks, Spark transformations, or ADF/Fabric-style pipelines\n- Schema changes, backfills, or catch-up loads\n\n## Design rules\n1. **Contracts first**: define input/output schemas and ownership before coding transforms.\n2. **Idempotency**: merges/upserts keyed by business keys; safe re-runs without duplicating facts.\n3. **Partitioning**: choose partition columns for query patterns; avoid tiny-file explosion.\n4. **Quality gates**: null checks, referential checks, and row-count anomalies before publish.\n5. **PII/PHI**: classify columns; tokenize/hash/mask per platform standards; least-privilege access.\n6. **Orchestration**: clear dependencies, retries with backoff, and dead-letter / failure paths.\n7. **Cost**: cache only when reused; prune unused columns early; right-size clusters/pools.\n\n## Implementation steps\n1. Sketch source \u2192 bronze/silver/gold (or in-repo layering names) data flow.\n2. Implement transforms with explicit schemas; avoid `select *` across trust boundaries.\n3. Add data quality checks as jobs/tasks that block downstream publish on failure.\n4. Emit metrics/logs with run id, batch window, and row counts.\n5. Document backfill procedure and watermark strategy.\n\n## Constraints\n- Do not invent employer-specific catalog names, secrets, or subscription IDs.\n- Prefer existing platform libraries and patterns in the repository.\n- No production writes from ad-hoc interactive sessions in committed jobs.\n\n## Output format\n- Pipeline diagram (mermaid or bullet edges)\n- Task list with inputs/outputs\n- Risk register (data loss, late data, PII)\n- Validation queries / checks to run after deploy" }, { "id": "llm-eval-agent-workflow", @@ -109,7 +109,7 @@ "codex" ], "formatNotes": "Written for all three tools with format notes inline. Copilot: keep under ~2k tokens in `copilot-instructions.md`; put long procedures in linked docs. Claude Code: keep `CLAUDE.md` short; put this procedure in `.claude/skills/llm-eval/SKILL.md`. Codex: root `AGENTS.md` points to `docs/agents/llm-eval.md` so the main file stays small.", - "body": "# Skill: LLM Eval and Agent Workflow Pack\n\n## Goal\nRun agentic coding tasks with measurable quality bars and portable instructions across Copilot, Claude Code, and Codex.\n\n## Tool placement (read this first)\n- **GitHub Copilot**: project rules in `.github/copilot-instructions.md`; path-specific `*.instructions.md` with `applyTo`. Keep critical security rules first.\n- **Claude Code**: durable facts in `CLAUDE.md` (< ~200 lines). Multi-step procedures belong in `.claude/skills//SKILL.md` with `description` / `when_to_use`. Optional `@AGENTS.md` import for shared text.\n- **Codex**: durable ops in `AGENTS.md` (and nested / `AGENTS.override.md`). Keep concise; link out for long eval rubrics.\n\n## Eval workflow\n1. **Define the task card**: goal, constraints, in-scope paths, out-of-scope, Definition of Done.\n2. **Golden checks**: commands that must pass (unit/integration/lint). No silent skips.\n3. **Rubric** (score 0–2 each): correctness, safety (secrets/PII), diff discipline, test updates, docs/runbook touch.\n4. **Baseline**: run once without the skill/instructions, once with — compare rubric and token/time cost.\n5. **Regressions**: store failing prompts in an `evals/` list; re-run after instruction edits.\n\n## Agent loop (all tools)\n1. Restate goal and constraints in one short paragraph.\n2. Explore only relevant paths; avoid repo-wide rewrites.\n3. Implement smallest viable change; keep commits/PR focused.\n4. Run verification commands; fix failures before claiming done.\n5. Report: summary, files changed, commands run, residual risks.\n\n## Constraints\n- Never exfiltrate secrets or customer data into prompts, logs, or fixtures.\n- Prefer patching existing patterns over new frameworks.\n- If instructions conflict, stop and list conflicts instead of guessing.\n\n## Output format\n- Task restatement\n- Plan (3–7 steps)\n- Changes + verification evidence\n- Rubric scores + next instruction tweak (if any)" + "body": "# Skill: LLM Eval and Agent Workflow Pack\n\n## Goal\nRun agentic coding tasks with measurable quality bars and portable instructions across Copilot, Claude Code, and Codex.\n\n## Tool placement (read this first)\n- **GitHub Copilot**: project rules in `.github/copilot-instructions.md`; path-specific `*.instructions.md` with `applyTo`. Keep critical security rules first.\n- **Claude Code**: durable facts in `CLAUDE.md` (< ~200 lines). Multi-step procedures belong in `.claude/skills//SKILL.md` with `description` / `when_to_use`. Optional `@AGENTS.md` import for shared text.\n- **Codex**: durable ops in `AGENTS.md` (and nested / `AGENTS.override.md`). Keep concise; link out for long eval rubrics.\n\n## Eval workflow\n1. **Define the task card**: goal, constraints, in-scope paths, out-of-scope, Definition of Done.\n2. **Golden checks**: commands that must pass (unit/integration/lint). No silent skips.\n3. **Rubric** (score 0\u20132 each): correctness, safety (secrets/PII), diff discipline, test updates, docs/runbook touch.\n4. **Baseline**: run once without the skill/instructions, once with \u2014 compare rubric and token/time cost.\n5. **Regressions**: store failing prompts in an `evals/` list; re-run after instruction edits.\n\n## Agent loop (all tools)\n1. Restate goal and constraints in one short paragraph.\n2. Explore only relevant paths; avoid repo-wide rewrites.\n3. Implement smallest viable change; keep commits/PR focused.\n4. Run verification commands; fix failures before claiming done.\n5. Report: summary, files changed, commands run, residual risks.\n\n## Constraints\n- Never exfiltrate secrets or customer data into prompts, logs, or fixtures.\n- Prefer patching existing patterns over new frameworks.\n- If instructions conflict, stop and list conflicts instead of guessing.\n\n## Output format\n- Task restatement\n- Plan (3\u20137 steps)\n- Changes + verification evidence\n- Rubric scores + next instruction tweak (if any)" }, { "id": "otel-aks-observability", @@ -127,7 +127,7 @@ "azure" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/otel.instructions.md` with applyTo for `**/*.{java,ts,go,yml,yaml}` plus optional `.github/skills/otel-aks/SKILL.md`. Claude Code: `.claude/skills/otel-aks/SKILL.md` (YAML name+description) and a one-line pointer in CLAUDE.md. Codex: keep root AGENTS.md short; put the procedure in `docs/agents/otel-aks.md` or a nested `deploy/AGENTS.md` so you stay under the ~32KiB project-doc budget.", - "body": "# Skill: OpenTelemetry on AKS Services\n\n## Goal\nAdd or harden traces, metrics, and logs for services on Azure AKS so signals correlate and SLIs drive alerts—without leaking PII.\n\n## When to apply\n- New service missing OTel instrumentation\n- Existing AKS workload with sparse traces, high cardinality, or uncorrelated logs\n- Collector / exporter / sampling changes in-repo\n\n## Instrumentation checklist\n1. **Traces**: instrument inbound HTTP/gRPC, outbound clients, DB/messaging; propagate W3C trace context.\n2. **Metrics**: RED/USE or domain SLIs (latency, error rate, saturation); avoid high-cardinality labels (raw user ids, URLs with ids).\n3. **Logs**: include `trace_id` / `span_id` on every request log line; keep severity consistent.\n4. **Semantic conventions**: prefer OTel HTTP/DB/RPC attribute names; do not invent parallel keys.\n5. **Resource attributes**: set `service.name`, `service.version`, `deployment.environment` (and cluster/namespace if available).\n6. **Exporters**: OTLP to the in-cluster collector endpoint already used by the repo; no ad-hoc SaaS SDKs unless already present.\n7. **Sampling**: head/tail sampling policy documented; raise sample rate only for error/slow paths when needed.\n8. **PII redaction**: scrub tokens, emails, phone numbers, auth headers before export; never log raw JWTs.\n9. **Dashboards / alerts**: map panels and alerts to SLIs (availability, latency p95/p99, error budget)—not vanity graphs.\n\n## AKS notes\n- Prefer **in-process** SDK when the language runtime already has one in this repo; use sidecar only if that pattern already exists.\n- Collector: reuse existing **DaemonSet** (node agent) or **Gateway** deployment patterns in-repo—do not introduce a second collector stack.\n- Ensure NetworkPolicy / private endpoints allow pod → collector OTLP; keep scrape ports off the public Service.\n\n## Constraints\n- Do not invent collector charts or CRDs not already in the repo.\n- Do not disable sampling “temporarily” in production manifests.\n- Prefer smallest diff: SDK config + attributes before new infra.\n\n## Output format\n- Summary of gaps found\n- Files / manifests to change (bullet list)\n- Checklist results (pass/fail per item above)\n- Residual risks (cardinality, cost, missing SLIs)" + "body": "# Skill: OpenTelemetry on AKS Services\n\n## Goal\nAdd or harden traces, metrics, and logs for services on Azure AKS so signals correlate and SLIs drive alerts\u2014without leaking PII.\n\n## When to apply\n- New service missing OTel instrumentation\n- Existing AKS workload with sparse traces, high cardinality, or uncorrelated logs\n- Collector / exporter / sampling changes in-repo\n\n## Instrumentation checklist\n1. **Traces**: instrument inbound HTTP/gRPC, outbound clients, DB/messaging; propagate W3C trace context.\n2. **Metrics**: RED/USE or domain SLIs (latency, error rate, saturation); avoid high-cardinality labels (raw user ids, URLs with ids).\n3. **Logs**: include `trace_id` / `span_id` on every request log line; keep severity consistent.\n4. **Semantic conventions**: prefer OTel HTTP/DB/RPC attribute names; do not invent parallel keys.\n5. **Resource attributes**: set `service.name`, `service.version`, `deployment.environment` (and cluster/namespace if available).\n6. **Exporters**: OTLP to the in-cluster collector endpoint already used by the repo; no ad-hoc SaaS SDKs unless already present.\n7. **Sampling**: head/tail sampling policy documented; raise sample rate only for error/slow paths when needed.\n8. **PII redaction**: scrub tokens, emails, phone numbers, auth headers before export; never log raw JWTs.\n9. **Dashboards / alerts**: map panels and alerts to SLIs (availability, latency p95/p99, error budget)\u2014not vanity graphs.\n\n## AKS notes\n- Prefer **in-process** SDK when the language runtime already has one in this repo; use sidecar only if that pattern already exists.\n- Collector: reuse existing **DaemonSet** (node agent) or **Gateway** deployment patterns in-repo\u2014do not introduce a second collector stack.\n- Ensure NetworkPolicy / private endpoints allow pod \u2192 collector OTLP; keep scrape ports off the public Service.\n\n## Constraints\n- Do not invent collector charts or CRDs not already in the repo.\n- Do not disable sampling \u201ctemporarily\u201d in production manifests.\n- Prefer smallest diff: SDK config + attributes before new infra.\n\n## Output format\n- Summary of gaps found\n- Files / manifests to change (bullet list)\n- Checklist results (pass/fail per item above)\n- Residual risks (cardinality, cost, missing SLIs)" }, { "id": "secure-pr-review-guardrails", @@ -144,7 +144,7 @@ "devsecops" ], "formatNotes": "All three. Copilot Chat/agent prompt or `.github/skills/secure-pr-review/SKILL.md`. Claude Code skill with a keyword-rich description (PR review, secrets, authz). Codex: section in AGENTS.md titled Secure review, or invoke as a pasted checklist.", - "body": "# Skill: Secure Pull Request Review\n\n## Goal\nReview a pull request for security defects—secrets leakage, authn/authz gaps, injection classes, and supply-chain risk—before merge.\n\n## When to apply\n- Any PR touching auth, crypto, CI permissions, dependencies, or public endpoints\n- Pre-merge security gate when a human asks for a secure review\n- After dependency bumps or workflow changes\n\n## Review order\n1. **Secrets / credentials**: hardcoded keys, tokens, connection strings, private keys, `.env` committed, debug dumps.\n2. **Authn / authz**: missing checks, IDOR, privilege escalation, overly broad roles, trust of client-supplied identity.\n3. **Injection / XSS / SSRF**: unsanitized input to SQL/NoSQL/shell/HTML; open redirects; server-side fetches to user-controlled URLs.\n4. **Dependency / lockfile / supply chain**: unexpected lockfile churn, new postinstall scripts, unpinned Actions, suspicious publishers.\n5. **Dangerous CI permissions**: `write-all`, unchecked `pull_request_target`, secrets to untrusted forks, mutable Action tags.\n6. **Data exposure / logging**: PII in logs, verbose errors to clients, overly broad CORS, public buckets.\n\n## Required findings format\nFor each issue:\n- **Severity**: critical | high | medium | low | info\n- **Location**: `file:line` (or hunk)\n- **Exploit sketch**: one short paragraph on how it could be abused\n- **Fix**: concrete remediation\n\n## Pass criteria\n- No unresolved critical/high findings\n- Medium findings acknowledged with owner or follow-up issue\n- No real secrets pasted into chat or review comments\n\n## Constraints\n- Do not invent vulnerabilities without evidence in the diff or reachable code.\n- Do not paste real secrets into chat—reference redacted shapes only.\n- Stay inside the PR diff plus minimal necessary context files.\n\n## Output format\n- Verdict: approve with notes | request changes | block\n- Findings table (severity, location, sketch, fix)\n- Residual risks / out-of-scope notes" + "body": "# Skill: Secure Pull Request Review\n\n## Goal\nReview a pull request for security defects\u2014secrets leakage, authn/authz gaps, injection classes, and supply-chain risk\u2014before merge.\n\n## When to apply\n- Any PR touching auth, crypto, CI permissions, dependencies, or public endpoints\n- Pre-merge security gate when a human asks for a secure review\n- After dependency bumps or workflow changes\n\n## Review order\n1. **Secrets / credentials**: hardcoded keys, tokens, connection strings, private keys, `.env` committed, debug dumps.\n2. **Authn / authz**: missing checks, IDOR, privilege escalation, overly broad roles, trust of client-supplied identity.\n3. **Injection / XSS / SSRF**: unsanitized input to SQL/NoSQL/shell/HTML; open redirects; server-side fetches to user-controlled URLs.\n4. **Dependency / lockfile / supply chain**: unexpected lockfile churn, new postinstall scripts, unpinned Actions, suspicious publishers.\n5. **Dangerous CI permissions**: `write-all`, unchecked `pull_request_target`, secrets to untrusted forks, mutable Action tags.\n6. **Data exposure / logging**: PII in logs, verbose errors to clients, overly broad CORS, public buckets.\n\n## Required findings format\nFor each issue:\n- **Severity**: critical | high | medium | low | info\n- **Location**: `file:line` (or hunk)\n- **Exploit sketch**: one short paragraph on how it could be abused\n- **Fix**: concrete remediation\n\n## Pass criteria\n- No unresolved critical/high findings\n- Medium findings acknowledged with owner or follow-up issue\n- No real secrets pasted into chat or review comments\n\n## Constraints\n- Do not invent vulnerabilities without evidence in the diff or reachable code.\n- Do not paste real secrets into chat\u2014reference redacted shapes only.\n- Stay inside the PR diff plus minimal necessary context files.\n\n## Output format\n- Verdict: approve with notes | request changes | block\n- Findings table (severity, location, sketch, fix)\n- Residual risks / out-of-scope notes" }, { "id": "azure-bicep-iac-guardrails", @@ -161,7 +161,7 @@ "iac" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/bicep.instructions.md` with applyTo `**/*.{bicep,bicepparam}`. Claude Code: `.claude/skills/azure-bicep-guardrails/SKILL.md`. Codex: nested `infra/AGENTS.md` or root `AGENTS.md` Azure IaC section.", - "body": "# Skill: Azure Bicep IaC Guardrails\n\n## Goal\nProduce Bicep that is least-privilege, parameterized, and safe to review before Azure deployment.\n\n## When to apply\n- New or changed `.bicep` / `.bicepparam` modules\n- Reviews of infra PRs that touch resource IDs, RBAC, networking, or secrets\n\n## Rules\n1. Prefer modules with clear inputs/outputs; avoid giant monolithic main files when the repo already uses modules.\n2. Parameterize environment-specific values (names, SKUs, CIDRs); never hardcode subscription IDs or secrets in committed params.\n3. Use `@secure()` for secrets and Key Vault references where the pattern already exists; never echo secure params in outputs.\n4. Scope RBAC to the narrowest principal and role; prefer role assignments at resource/RG scope over subscription-wide.\n5. Explicitly set required tags used by the platform (owner, env, cost-center) when the repo already expects them.\n6. Prefer existing verified modules / patterns in-repo over inventing new resource types.\n7. For public endpoints: justify exposure; prefer private endpoints / VNet integration when sibling modules do.\n8. Keep API versions pinned and consistent with neighboring modules; do not float to latest without a reason.\n\n## Review checklist\n- What resources are created/updated/deleted?\n- Any wildcard `*` permissions or Owner assignments?\n- Are diagnostics / logging hooks aligned with existing modules?\n- Are dependsOn / existing resource references correct?\n- What is the rollback story if deploy fails mid-way?\n\n## Constraints\n- Do not invent tenant, subscription, or object IDs — use parameters or existing symbols.\n- Do not weaken network or RBAC controls \"just to make deploy work\".\n- Prefer what-if / validation commands the repo already documents.\n\n## Output format\n- Summary of modules/files touched\n- Bicep diffs ready to apply\n- Parameter changes (names only for secrets)\n- Validation commands (`az bicep build`, what-if, or repo scripts)\n- Residual risks" + "body": "# Skill: Azure Bicep IaC Guardrails\n\n## Goal\nProduce Bicep that is least-privilege, parameterized, and safe to review before Azure deployment.\n\n## When to apply\n- New or changed `.bicep` / `.bicepparam` modules\n- Reviews of infra PRs that touch resource IDs, RBAC, networking, or secrets\n\n## Rules\n1. Prefer modules with clear inputs/outputs; avoid giant monolithic main files when the repo already uses modules.\n2. Parameterize environment-specific values (names, SKUs, CIDRs); never hardcode subscription IDs or secrets in committed params.\n3. Use `@secure()` for secrets and Key Vault references where the pattern already exists; never echo secure params in outputs.\n4. Scope RBAC to the narrowest principal and role; prefer role assignments at resource/RG scope over subscription-wide.\n5. Explicitly set required tags used by the platform (owner, env, cost-center) when the repo already expects them.\n6. Prefer existing verified modules / patterns in-repo over inventing new resource types.\n7. For public endpoints: justify exposure; prefer private endpoints / VNet integration when sibling modules do.\n8. Keep API versions pinned and consistent with neighboring modules; do not float to latest without a reason.\n\n## Review checklist\n- What resources are created/updated/deleted?\n- Any wildcard `*` permissions or Owner assignments?\n- Are diagnostics / logging hooks aligned with existing modules?\n- Are dependsOn / existing resource references correct?\n- What is the rollback story if deploy fails mid-way?\n\n## Constraints\n- Do not invent tenant, subscription, or object IDs \u2014 use parameters or existing symbols.\n- Do not weaken network or RBAC controls \"just to make deploy work\".\n- Prefer what-if / validation commands the repo already documents.\n\n## Output format\n- Summary of modules/files touched\n- Bicep diffs ready to apply\n- Parameter changes (names only for secrets)\n- Validation commands (`az bicep build`, what-if, or repo scripts)\n- Residual risks" }, { "id": "container-image-hardening", @@ -179,12 +179,12 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/docker.instructions.md` with applyTo for `**/Dockerfile*`, `**/*Containerfile*`, `**/docker-compose*.{yml,yaml}`. Claude Code: `.claude/skills/container-image-hardening/SKILL.md` (YAML name + keyword-rich description). Codex: section in root or `deploy/AGENTS.md`, or `.agents/skills/container-image-hardening/SKILL.md`.", - "body": "# Skill: Container Image Hardening\n\n## Goal\nProduce lean, reproducible, least-privilege container images that are safe to run on AKS (or similar).\n\n## When to apply\n- New or changed Dockerfile / Containerfile / buildah scripts\n- Multi-stage builds, base-image upgrades, or image used by a Deployment\n\n## Hardening checklist (apply in order)\n1. **Pin bases**: digest-pin (`@sha256:…`) or immutable tags used by the platform; never `:latest` in production paths.\n2. **Multi-stage**: build in a fat stage; copy only runtime artifacts into a minimal final stage.\n3. **Non-root**: final USER is a non-root uid/gid; avoid running as root even if the orchestrator could override.\n4. **No secrets in layers**: never COPY `.env`, key files, or `npmrc` with tokens; use BuildKit secrets / runtime mounts.\n5. **Minimal attack surface**: no unused shells/package managers in the final image when feasible; drop build tools from runtime.\n6. **Health signal**: document the process model (PID 1, signal handling); prefer a dumb-init/tini only if the stack already uses it.\n7. **Metadata**: useful OCI labels (`org.opencontainers.image.*`) without leaking internal hostnames or personal data.\n8. **Supply chain**: generate or consume SBOM when the pipeline expects it; note image scan gate before promote.\n\n## Dockerfile patterns\n- Prefer `COPY --from=build` of exact paths over copying the whole build context into runtime.\n- Order layers for cache: dependency manifests before source.\n- `RUN` apt/apk with cleanup in the same layer; pin package versions when the repo already does.\n- Expose only required ports; do not bake environment-specific URLs into the image when config can be runtime.\n\n## Constraints\n- Do not invent private base images or registries that are not evidenced in-repo.\n- Do not weaken existing IMAGE signing / admission policy for convenience.\n- Keep local `docker build` / `buildx` commands accurate for this repo.\n\n## Output format\n- Patched Dockerfile(s) or clear unified diff\n- Table: control → status (pass/fail/n/a) → note\n- Suggested scan/SBOM commands matching repo CI\n- Residual risks (base CVEs, privileged bits, secret leakage)" + "body": "# Skill: Container Image Hardening\n\n## Goal\nProduce lean, reproducible, least-privilege container images that are safe to run on AKS (or similar).\n\n## When to apply\n- New or changed Dockerfile / Containerfile / buildah scripts\n- Multi-stage builds, base-image upgrades, or image used by a Deployment\n\n## Hardening checklist (apply in order)\n1. **Pin bases**: digest-pin (`@sha256:\u2026`) or immutable tags used by the platform; never `:latest` in production paths.\n2. **Multi-stage**: build in a fat stage; copy only runtime artifacts into a minimal final stage.\n3. **Non-root**: final USER is a non-root uid/gid; avoid running as root even if the orchestrator could override.\n4. **No secrets in layers**: never COPY `.env`, key files, or `npmrc` with tokens; use BuildKit secrets / runtime mounts.\n5. **Minimal attack surface**: no unused shells/package managers in the final image when feasible; drop build tools from runtime.\n6. **Health signal**: document the process model (PID 1, signal handling); prefer a dumb-init/tini only if the stack already uses it.\n7. **Metadata**: useful OCI labels (`org.opencontainers.image.*`) without leaking internal hostnames or personal data.\n8. **Supply chain**: generate or consume SBOM when the pipeline expects it; note image scan gate before promote.\n\n## Dockerfile patterns\n- Prefer `COPY --from=build` of exact paths over copying the whole build context into runtime.\n- Order layers for cache: dependency manifests before source.\n- `RUN` apt/apk with cleanup in the same layer; pin package versions when the repo already does.\n- Expose only required ports; do not bake environment-specific URLs into the image when config can be runtime.\n\n## Constraints\n- Do not invent private base images or registries that are not evidenced in-repo.\n- Do not weaken existing IMAGE signing / admission policy for convenience.\n- Keep local `docker build` / `buildx` commands accurate for this repo.\n\n## Output format\n- Patched Dockerfile(s) or clear unified diff\n- Table: control \u2192 status (pass/fail/n/a) \u2192 note\n- Suggested scan/SBOM commands matching repo CI\n- Residual risks (base CVEs, privileged bits, secret leakage)" }, { "id": "azure-key-vault-app-integration", "title": "Azure Key Vault App Integration", - "whenToUse": "Wiring an app or service to Azure Key Vault for secrets, certificates, or keys — or reviewing a PR that still embeds credentials.", + "whenToUse": "Wiring an app or service to Azure Key Vault for secrets, certificates, or keys \u2014 or reviewing a PR that still embeds credentials.", "tools": [ "copilot", "claude-code", @@ -197,12 +197,12 @@ "security" ], "formatNotes": "All three. Copilot: `.github/instructions/keyvault.instructions.md` with applyTo for `**/*.{java,cs,ts,js,yml,yaml,bicep,tf}` and `**/appsettings*.json`. Claude Code: `.claude/skills/azure-key-vault/SKILL.md`. Codex: section in root `AGENTS.md` or `docs/agents/key-vault.md` linked from AGENTS.md.", - "body": "# Skill: Azure Key Vault App Integration\n\n## Goal\nIntegrate applications with Azure Key Vault so secrets are fetched via identity, rotated safely, and never committed or logged.\n\n## When to apply\n- New or existing services that need DB passwords, API keys, certificates, or signing keys\n- Reviews that find secrets in config files, env samples committed with real values, or long-lived connection strings\n- Migrations from App Settings / Kubernetes secrets / `.env` files into Key Vault\n\n## Preferred patterns\n1. **Identity over keys**: prefer managed identity / workload identity to Key Vault; avoid embedding vault access keys or client secrets when identity is available.\n2. **Least privilege**: grant get/list only on the secrets the app needs; separate read vs admin principals.\n3. **Names and versions**: use stable secret names; pin to a version only when required for rollback, otherwise take the current version deliberately.\n4. **Caching**: cache secret values in-process with a short TTL and refresh on failure; do not dump full secret maps into logs.\n5. **Local/dev**: use user secrets, `.env` (gitignored), or a non-prod vault — never commit real values; document required secret *names* only.\n6. **Rotation**: design callers to tolerate rotation (reconnect pools, reload config) without redeploying for every rotate when the platform supports it.\n\n## Implementation steps\n1. Inventory secrets the change introduces or touches (name, owner, environments).\n2. Confirm vault and RBAC/access policy patterns already used in-repo; match them.\n3. Replace inline secret material with references (Key Vault reference, CSI driver, SDK getSecret, etc. as used by the stack).\n4. Ensure startup fails closed if required secrets are missing (clear error, no half-boot with empty credentials).\n5. Add or update tests/mocks so unit tests never need real vault credentials.\n6. Update runbooks: where secrets live, who can rotate, and how to verify after rotate.\n\n## Constraints\n- Do not print secret values, full connection strings, or private keys in logs, traces, or PR descriptions.\n- Do not weaken TLS or disable certificate validation to “make Key Vault work.”\n- Prefer platform-native Key Vault integration already in the repo over new SDKs or sidecar patterns.\n- Keep IaC changes aligned with existing modules (Bicep/Terraform/Helm) — no one-off portal-only grants in production paths.\n\n## Output format\n- Summary of secrets moved or referenced (names only)\n- Code/IaC/config diffs\n- Identity and RBAC changes required\n- Verification steps (app start, rotate drill, negative test for missing secret)\n- Residual risks (caching, dual-read during migration, break-glass)" + "body": "# Skill: Azure Key Vault App Integration\n\n## Goal\nIntegrate applications with Azure Key Vault so secrets are fetched via identity, rotated safely, and never committed or logged.\n\n## When to apply\n- New or existing services that need DB passwords, API keys, certificates, or signing keys\n- Reviews that find secrets in config files, env samples committed with real values, or long-lived connection strings\n- Migrations from App Settings / Kubernetes secrets / `.env` files into Key Vault\n\n## Preferred patterns\n1. **Identity over keys**: prefer managed identity / workload identity to Key Vault; avoid embedding vault access keys or client secrets when identity is available.\n2. **Least privilege**: grant get/list only on the secrets the app needs; separate read vs admin principals.\n3. **Names and versions**: use stable secret names; pin to a version only when required for rollback, otherwise take the current version deliberately.\n4. **Caching**: cache secret values in-process with a short TTL and refresh on failure; do not dump full secret maps into logs.\n5. **Local/dev**: use user secrets, `.env` (gitignored), or a non-prod vault \u2014 never commit real values; document required secret *names* only.\n6. **Rotation**: design callers to tolerate rotation (reconnect pools, reload config) without redeploying for every rotate when the platform supports it.\n\n## Implementation steps\n1. Inventory secrets the change introduces or touches (name, owner, environments).\n2. Confirm vault and RBAC/access policy patterns already used in-repo; match them.\n3. Replace inline secret material with references (Key Vault reference, CSI driver, SDK getSecret, etc. as used by the stack).\n4. Ensure startup fails closed if required secrets are missing (clear error, no half-boot with empty credentials).\n5. Add or update tests/mocks so unit tests never need real vault credentials.\n6. Update runbooks: where secrets live, who can rotate, and how to verify after rotate.\n\n## Constraints\n- Do not print secret values, full connection strings, or private keys in logs, traces, or PR descriptions.\n- Do not weaken TLS or disable certificate validation to \u201cmake Key Vault work.\u201d\n- Prefer platform-native Key Vault integration already in the repo over new SDKs or sidecar patterns.\n- Keep IaC changes aligned with existing modules (Bicep/Terraform/Helm) \u2014 no one-off portal-only grants in production paths.\n\n## Output format\n- Summary of secrets moved or referenced (names only)\n- Code/IaC/config diffs\n- Identity and RBAC changes required\n- Verification steps (app start, rotate drill, negative test for missing secret)\n- Residual risks (caching, dual-read during migration, break-glass)" }, { "id": "spring-boot-resilience4j", "title": "Spring Boot Resilience4j Guardrails", - "whenToUse": "Adding timeouts, retries, circuit breakers, or bulkheads to a Spring Boot service — or reviewing a PR that calls unreliable dependencies without resilience.", + "whenToUse": "Adding timeouts, retries, circuit breakers, or bulkheads to a Spring Boot service \u2014 or reviewing a PR that calls unreliable dependencies without resilience.", "tools": [ "copilot", "claude-code", @@ -215,7 +215,7 @@ "microservices" ], "formatNotes": "All three. Copilot: `.github/instructions/resilience.instructions.md` with applyTo for `**/*.{java,yml,yaml}` and Spring config. Claude Code: `.claude/skills/spring-resilience4j/SKILL.md`. Codex: section in root `AGENTS.md` or `docs/agents/resilience4j.md` linked from AGENTS.md.", - "body": "# Skill: Spring Boot Resilience4j Guardrails\n\n## Goal\nAdd timeouts, retries, circuit breakers, and bulkheads to Spring Boot 3 services so outbound calls fail predictably and recover safely.\n\n## When to apply\n- HTTP/DB/messaging clients without explicit resilience\n- PRs calling unreliable dependencies with only default timeouts\n- Hardening services that rely on ad-hoc try/catch\n\n## Preferred patterns\n1. **TimeLimiter** — bound every outbound call; prefer fail-fast over hanging threads.\n2. **Retry** — exponential backoff + jitter; only idempotent ops and transient faults (timeouts, 502/503/504), never business 4xx.\n3. **CircuitBreaker** — open on error-rate/slow-call thresholds; choose fail-fast vs fail-open explicitly.\n4. **Bulkhead / RateLimiter** — isolate concurrency so one dependency cannot starve the JVM.\n5. **YAML config** — named instances in `application.yml`; avoid magic defaults in code.\n6. **Metrics & health** — expose breaker state via Actuator/health already in-repo.\n\n## Implementation steps\n1. Inventory outbound calls; mark which are idempotent.\n2. Match existing Resilience4j / Spring Boot starter usage in-repo.\n3. Decorate with named `@TimeLimiter`, `@Retry`, `@CircuitBreaker`, `@Bulkhead` / `@RateLimiter`.\n4. Fallbacks return safe degraded responses or typed errors — never swallow exceptions.\n5. Wire YAML per instance; document fail-fast vs fail-open per dependency.\n6. Tests: open-circuit, retry exhaustion, fallback, no retries on non-idempotent calls.\n\n## Review checklist\n- End-to-end timeouts (client + resilience layer)\n- Retries gated on idempotency + transient errors only\n- CircuitBreaker thresholds and half-open behavior documented\n- Bulkhead/RateLimiter prevents thread-pool exhaustion\n- No silent catch-and-ignore; stable API/problem error mapping\n- Metrics/health visible; config in YAML not hardcoded literals\n\n## Done when\nNamed Resilience4j protection, YAML config, open-circuit/fallback tests, and a fail-fast vs fail-open note per dependency are in place." + "body": "# Skill: Spring Boot Resilience4j Guardrails\n\n## Goal\nAdd timeouts, retries, circuit breakers, and bulkheads to Spring Boot 3 services so outbound calls fail predictably and recover safely.\n\n## When to apply\n- HTTP/DB/messaging clients without explicit resilience\n- PRs calling unreliable dependencies with only default timeouts\n- Hardening services that rely on ad-hoc try/catch\n\n## Preferred patterns\n1. **TimeLimiter** \u2014 bound every outbound call; prefer fail-fast over hanging threads.\n2. **Retry** \u2014 exponential backoff + jitter; only idempotent ops and transient faults (timeouts, 502/503/504), never business 4xx.\n3. **CircuitBreaker** \u2014 open on error-rate/slow-call thresholds; choose fail-fast vs fail-open explicitly.\n4. **Bulkhead / RateLimiter** \u2014 isolate concurrency so one dependency cannot starve the JVM.\n5. **YAML config** \u2014 named instances in `application.yml`; avoid magic defaults in code.\n6. **Metrics & health** \u2014 expose breaker state via Actuator/health already in-repo.\n\n## Implementation steps\n1. Inventory outbound calls; mark which are idempotent.\n2. Match existing Resilience4j / Spring Boot starter usage in-repo.\n3. Decorate with named `@TimeLimiter`, `@Retry`, `@CircuitBreaker`, `@Bulkhead` / `@RateLimiter`.\n4. Fallbacks return safe degraded responses or typed errors \u2014 never swallow exceptions.\n5. Wire YAML per instance; document fail-fast vs fail-open per dependency.\n6. Tests: open-circuit, retry exhaustion, fallback, no retries on non-idempotent calls.\n\n## Review checklist\n- End-to-end timeouts (client + resilience layer)\n- Retries gated on idempotency + transient errors only\n- CircuitBreaker thresholds and half-open behavior documented\n- Bulkhead/RateLimiter prevents thread-pool exhaustion\n- No silent catch-and-ignore; stable API/problem error mapping\n- Metrics/health visible; config in YAML not hardcoded literals\n\n## Done when\nNamed Resilience4j protection, YAML config, open-circuit/fallback tests, and a fail-fast vs fail-open note per dependency are in place." }, { "id": "helm-chart-aks-guardrails", @@ -233,7 +233,7 @@ "kubernetes" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/helm.instructions.md` with applyTo for `**/charts/**`, `**/helm/**`, `**/values*.yaml`. Claude Code: `.claude/skills/helm-aks-guardrails/SKILL.md`. Codex: `deploy/AGENTS.md` or root `AGENTS.md` section titled Helm/AKS.", - "body": "# Skill: Helm Chart Guardrails for AKS\n\n## Goal\nProduce Helm charts that render secure, operable workloads on Azure AKS and are reviewable in PR.\n\n## When to apply\n- New or changed chart templates, helpers, values.yaml, values.schema.json\n- Chart bumps that touch ServiceAccount, RBAC, Ingress, probes, or secrets\n\n## Chart structure rules\n1. Keep templates DRY via `_helpers.tpl`; name resources with the chart fullname helper.\n2. Prefer `values.schema.json` for required keys and safe defaults; document every public value.\n3. Defaults must be production-safe (ClusterIP, non-root, resources set); loosen only in env overlays.\n4. Pin image repository + tag (or digest); never default to `latest`.\n5. Separate chart config from secrets: no raw credentials in values committed to git.\n\n## Security and operability checklist\n1. **Pod/container securityContext**: runAsNonRoot, allowPrivilegeEscalation false, drop ALL capabilities, readOnlyRootFilesystem when feasible, seccomp RuntimeDefault when the platform supports it.\n2. **Resources**: requests and limits on every container; note intentional burstable cases.\n3. **Probes**: readiness + liveness (startup when slow); avoid identical probes that hide failures.\n4. **Identity/secrets on AKS**: prefer Workload Identity + Key Vault CSI / external secrets over long-lived kube secrets in values.\n5. **RBAC**: least-privilege Role/RoleBinding; no ClusterRole unless justified and documented.\n6. **Networking**: configurable Service type (default ClusterIP); NetworkPolicy templates optional but default-deny when the chart ships policies.\n7. **Rollouts**: sensible rollingUpdate; PodDisruptionBudget for user-facing services; checksum annotations for ConfigMap/Secret changes that should restart pods.\n\n## Validation steps\n1. `helm lint` on the chart.\n2. `helm template` for at least two value overlays (e.g. base + prod-like).\n3. Dry-run apply or kubeconform/kubeval if the repo already uses them.\n4. Confirm rendered manifests match in-repo AKS conventions (ingress class, labels, identity annotations).\n\n## Constraints\n- Do not invent cluster operators/CRDs not evidenced in-repo.\n- Do not hardcode subscription, tenant, or Key Vault URIs — parameterize.\n- Keep NOTES.txt accurate and free of secrets.\n\n## Output format\n- Files touched + why\n- Key values additions (names + purpose)\n- Rendered-manifest highlights or patches\n- Commands run / to run\n- Residual risks (RBAC breadth, secret path, ingress exposure)" + "body": "# Skill: Helm Chart Guardrails for AKS\n\n## Goal\nProduce Helm charts that render secure, operable workloads on Azure AKS and are reviewable in PR.\n\n## When to apply\n- New or changed chart templates, helpers, values.yaml, values.schema.json\n- Chart bumps that touch ServiceAccount, RBAC, Ingress, probes, or secrets\n\n## Chart structure rules\n1. Keep templates DRY via `_helpers.tpl`; name resources with the chart fullname helper.\n2. Prefer `values.schema.json` for required keys and safe defaults; document every public value.\n3. Defaults must be production-safe (ClusterIP, non-root, resources set); loosen only in env overlays.\n4. Pin image repository + tag (or digest); never default to `latest`.\n5. Separate chart config from secrets: no raw credentials in values committed to git.\n\n## Security and operability checklist\n1. **Pod/container securityContext**: runAsNonRoot, allowPrivilegeEscalation false, drop ALL capabilities, readOnlyRootFilesystem when feasible, seccomp RuntimeDefault when the platform supports it.\n2. **Resources**: requests and limits on every container; note intentional burstable cases.\n3. **Probes**: readiness + liveness (startup when slow); avoid identical probes that hide failures.\n4. **Identity/secrets on AKS**: prefer Workload Identity + Key Vault CSI / external secrets over long-lived kube secrets in values.\n5. **RBAC**: least-privilege Role/RoleBinding; no ClusterRole unless justified and documented.\n6. **Networking**: configurable Service type (default ClusterIP); NetworkPolicy templates optional but default-deny when the chart ships policies.\n7. **Rollouts**: sensible rollingUpdate; PodDisruptionBudget for user-facing services; checksum annotations for ConfigMap/Secret changes that should restart pods.\n\n## Validation steps\n1. `helm lint` on the chart.\n2. `helm template` for at least two value overlays (e.g. base + prod-like).\n3. Dry-run apply or kubeconform/kubeval if the repo already uses them.\n4. Confirm rendered manifests match in-repo AKS conventions (ingress class, labels, identity annotations).\n\n## Constraints\n- Do not invent cluster operators/CRDs not evidenced in-repo.\n- Do not hardcode subscription, tenant, or Key Vault URIs \u2014 parameterize.\n- Keep NOTES.txt accurate and free of secrets.\n\n## Output format\n- Files touched + why\n- Key values additions (names + purpose)\n- Rendered-manifest highlights or patches\n- Commands run / to run\n- Residual risks (RBAC breadth, secret path, ingress exposure)" }, { "id": "aks-networkpolicy-zero-trust", @@ -252,7 +252,7 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/networkpolicy.instructions.md` with applyTo for `**/networkpolicy/**`, `**/*network*policy*.yaml`, `**/cilium/**`. Claude Code: `.claude/skills/aks-networkpolicy-zero-trust/SKILL.md`. Codex: nested `deploy/AGENTS.md` or a NetworkPolicy section in root `AGENTS.md`.", - "body": "# Skill: AKS NetworkPolicy Zero-Trust Guardrails\n\n## Goal\nShip namespace-scoped network policies that enforce default-deny east-west traffic on Azure AKS, with explicit allow paths that are reviewable in PR.\n\n## When to apply\n- New or changed NetworkPolicy / CiliumNetworkPolicy manifests\n- Service extractions that introduce new pod-to-pod or egress paths\n- Chart or Kustomize overlays that touch networking for AKS\n\n## Baseline posture\n1. Assume the cluster starts open: unrestricted pod-to-pod until a selecting policy exists.\n2. Prefer **default deny** per application namespace for both Ingress and Egress (or Ingress-first if egress is staged).\n3. Prefer standard `networking.k8s.io/v1` NetworkPolicy when it covers the need; use Cilium CRDs only when the cluster clearly runs Azure CNI Powered by Cilium (or Calico) and L7/FQDN features are required and supported.\n4. Never invent a CNI or policy engine not evidenced in-repo or in the cluster notes.\n\n## Policy authoring rules\n1. **Selectors first**: every allow rule names concrete `podSelector` / `namespaceSelector` labels that already exist on workloads.\n2. **Ports + protocols**: pin TCP/UDP ports; avoid open port ranges unless justified.\n3. **Cross-namespace**: include namespace identity explicitly (label selectors), never rely on “same cluster = trusted”.\n4. **DNS on egress deny**: if egress is default-deny, allow kube-dns / CoreDNS (usually UDP/TCP 53) before anything else, or apps break silently.\n5. **Probes and system paths**: account for kubelet probes and required platform agents; do not blanket-allow node CIDRs unless the platform docs require it and `ipBlock` is valid for the CNI (Azure CNI Cilium has `ipBlock` limitations for pod/node IPs — prefer selectors).\n6. **Ingress controllers / mesh**: allow only the ingress or mesh identity that terminates traffic; document TLS termination assumptions.\n7. **Egress to Azure PaaS**: prefer private endpoints / service tags documented in-repo; do not hardcode subscription-specific IPs in policies without a values/overlay escape hatch.\n\n## Structure and naming\n1. One default-deny object per namespace; separate allow policies per intent (`allow-frontend-to-api`, `allow-api-to-redis`).\n2. Stable metadata names; label policies with app/component for grep and policy inventory.\n3. Keep examples under `deploy/`, `k8s/`, or chart templates consistent with existing layout.\n\n## Validation steps\n1. `kubectl apply --dry-run=server` (or kubeconform) on the manifests.\n2. Describe expected flows in the PR: source → destination:port for each allow.\n3. After apply in a non-prod namespace: confirm deny (blocked path) and allow (happy path) with a short curl/nc from a debug pod.\n4. If Cilium: check endpoint enforcement / Hubble flows when those tools are already in the cluster.\n\n## Constraints\n- Do not weaken default-deny with broad `ipBlock: 0.0.0.0/0` “temporary” allows.\n- Do not put secrets, connection strings, or environment-specific hostnames into policy comments that will rot.\n- Parameterize environment differences via Kustomize/Helm values, not copy-pasted YAML forks.\n\n## Output format\n- Files touched + why\n- Flow table (src → dst:port / direction)\n- Default-deny coverage (ingress/egress, namespaces)\n- Residual risks (DNS, probes, ingress identity, CNI limits)\n- Commands run / to run\n" + "body": "# Skill: AKS NetworkPolicy Zero-Trust Guardrails\n\n## Goal\nShip namespace-scoped network policies that enforce default-deny east-west traffic on Azure AKS, with explicit allow paths that are reviewable in PR.\n\n## When to apply\n- New or changed NetworkPolicy / CiliumNetworkPolicy manifests\n- Service extractions that introduce new pod-to-pod or egress paths\n- Chart or Kustomize overlays that touch networking for AKS\n\n## Baseline posture\n1. Assume the cluster starts open: unrestricted pod-to-pod until a selecting policy exists.\n2. Prefer **default deny** per application namespace for both Ingress and Egress (or Ingress-first if egress is staged).\n3. Prefer standard `networking.k8s.io/v1` NetworkPolicy when it covers the need; use Cilium CRDs only when the cluster clearly runs Azure CNI Powered by Cilium (or Calico) and L7/FQDN features are required and supported.\n4. Never invent a CNI or policy engine not evidenced in-repo or in the cluster notes.\n\n## Policy authoring rules\n1. **Selectors first**: every allow rule names concrete `podSelector` / `namespaceSelector` labels that already exist on workloads.\n2. **Ports + protocols**: pin TCP/UDP ports; avoid open port ranges unless justified.\n3. **Cross-namespace**: include namespace identity explicitly (label selectors), never rely on \u201csame cluster = trusted\u201d.\n4. **DNS on egress deny**: if egress is default-deny, allow kube-dns / CoreDNS (usually UDP/TCP 53) before anything else, or apps break silently.\n5. **Probes and system paths**: account for kubelet probes and required platform agents; do not blanket-allow node CIDRs unless the platform docs require it and `ipBlock` is valid for the CNI (Azure CNI Cilium has `ipBlock` limitations for pod/node IPs \u2014 prefer selectors).\n6. **Ingress controllers / mesh**: allow only the ingress or mesh identity that terminates traffic; document TLS termination assumptions.\n7. **Egress to Azure PaaS**: prefer private endpoints / service tags documented in-repo; do not hardcode subscription-specific IPs in policies without a values/overlay escape hatch.\n\n## Structure and naming\n1. One default-deny object per namespace; separate allow policies per intent (`allow-frontend-to-api`, `allow-api-to-redis`).\n2. Stable metadata names; label policies with app/component for grep and policy inventory.\n3. Keep examples under `deploy/`, `k8s/`, or chart templates consistent with existing layout.\n\n## Validation steps\n1. `kubectl apply --dry-run=server` (or kubeconform) on the manifests.\n2. Describe expected flows in the PR: source \u2192 destination:port for each allow.\n3. After apply in a non-prod namespace: confirm deny (blocked path) and allow (happy path) with a short curl/nc from a debug pod.\n4. If Cilium: check endpoint enforcement / Hubble flows when those tools are already in the cluster.\n\n## Constraints\n- Do not weaken default-deny with broad `ipBlock: 0.0.0.0/0` \u201ctemporary\u201d allows.\n- Do not put secrets, connection strings, or environment-specific hostnames into policy comments that will rot.\n- Parameterize environment differences via Kustomize/Helm values, not copy-pasted YAML forks.\n\n## Output format\n- Files touched + why\n- Flow table (src \u2192 dst:port / direction)\n- Default-deny coverage (ingress/egress, namespaces)\n- Residual risks (DNS, probes, ingress identity, CNI limits)\n- Commands run / to run\n" }, { "id": "aks-workload-identity-guardrails", @@ -272,7 +272,7 @@ "identity" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/aks-workload-identity.instructions.md` with applyTo for `**/deploy/**`, `**/k8s/**`, `**/*.{yml,yaml,bicep,tf}`, `**/serviceaccount*.yaml`, and app credential wiring files. Claude Code: `.claude/skills/aks-workload-identity-guardrails/SKILL.md` (plus a short CLAUDE.md fact that WI is preferred over pod secrets / aadpodidentity). Codex: nested `deploy/AGENTS.md` or an Identity section in root `AGENTS.md`.", - "body": "# Skill: AKS Workload Identity Guardrails\n\n## Goal\nGive every AKS workload a federated identity path: a Kubernetes ServiceAccount mapped to a user-assigned managed identity via Azure Workload Identity, so apps obtain Azure tokens without client secrets in the cluster.\n\n## When to apply\n- New AKS deployments that call Azure AD–protected resources (Key Vault, Storage, Event Hubs, ACR pull via MI, Azure SQL, etc.)\n- Migrations off client secrets, SP passwords, or connection strings stored as Kubernetes Secrets\n- Replacing legacy Azure AD Pod Identity (`aadpodidentity`, AzureIdentity / AzureIdentityBinding)\n- Reviews of Helm/Kustomize that still inject `AZURE_CLIENT_SECRET` or similar\n\n## Baseline rules\n1. **Prefer Workload Identity** (OIDC federation on the AKS cluster + user-assigned MI) over secrets and over AAD Pod Identity.\n2. **One identity intent per workload** (or tightly related set): map ServiceAccount → user-assigned MI; avoid a shared “cluster MI” for unrelated apps.\n3. **Least privilege RBAC** on the MI: grant only the Azure roles/data-plane permissions the app needs on specific resource scopes (RG/resource), never Owner/Contributor at subscription by default.\n4. **Namespace labels**: ensure the namespace opted into WI (`azure.workload.identity/use: \"true\"` on the namespace, per current AKS WI docs your platform follows).\n5. **ServiceAccount**: annotate with client id (and tenant if required by your platform pattern):\n - `azure.workload.identity/client-id: `\n - Optional audience / tenant annotations only when your platform standard requires them.\n6. **Pod**: use that ServiceAccount; label pods that participate with `azure.workload.identity/use: \"true\"` when required by the WI mutating webhook in your cluster version.\n7. **Federated credential** on the user-assigned MI must match the issuer of the AKS OIDC issuer and the subject `system:serviceaccount::` (exact SA name and namespace — typos break auth silently).\n8. **App code**: use Azure Identity SDK `DefaultAzureCredential` / equivalent chain that picks up the WI-injected env (`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE`). Do not hardcode secrets “for local only” into the same Deployment env.\n9. **Key Vault**: prefer CSI Secrets Store with WI, or SDK access with the same MI — do not sync long-lived secret values into etcd if CSI + SDK can avoid it.\n10. **Local / CI fallback**: document Azure CLI / env credential / user auth for laptop and pipeline; keep that path out of the in-cluster Deployment manifest.\n\n## Structure\n1. Infra (Bicep/Terraform/az): user-assigned MI + federated identity credential bound to SA subject + OIDC issuer.\n2. Cluster: WI addon / OIDC issuer enabled (do not invent enablement steps if the platform repo already owns cluster bootstrap).\n3. App manifests: Namespace label → ServiceAccount (annotated) → Deployment/StatefulSet `serviceAccountName` + WI use label → no client-secret env vars.\n4. Azure RBAC assignments scoped to the resources the app actually calls.\n5. README or runbook: how to rotate by swapping MI / federated credential, and how to validate token acquisition.\n\n## Validation\n1. Confirm OIDC issuer URL on the cluster matches the federated credential issuer.\n2. Confirm SA name/namespace in the federated credential subject equal the live ServiceAccount.\n3. From a debug shell in the pod (non-prod): check projected token file exists and Azure SDK / `az login --federated-token` (or equivalent) can obtain an access token for a known resource.\n4. Negative test: wrong SA or missing annotation fails closed (no silent fallback to a shared secret).\n5. PR checklist: no `AZURE_CLIENT_SECRET`, no SP password in Secrets, no `aadpodidbinding` / AzureIdentityBinding leftovers for this app.\n\n## Anti-patterns\n- Storing Azure client secrets or SP passwords in Kubernetes Secrets “temporarily”\n- Re-introducing Azure AD Pod Identity CRDs for new work\n- One shared MI with broad Contributor for every namespace\n- Hardcoding subscription-specific client IDs in app code instead of SA annotation / chart values\n- Mounting the federated token path world-readable or logging token contents\n- Leaving both WI and a client-secret env var so the SDK prefers the secret path\n- Copying federated credential subjects across environments without updating namespace/SA\n\n## Output format\n- Identity map: namespace / SA / UAMI client id / federated subject / Azure roles\n- Manifest and IaC files touched\n- Secrets / aadpodidentity objects to delete\n- Validation commands and residual risks (local-dev, CSI vs SDK, privileged roles)\n" + "body": "# Skill: AKS Workload Identity Guardrails\n\n## Goal\nGive every AKS workload a federated identity path: a Kubernetes ServiceAccount mapped to a user-assigned managed identity via Azure Workload Identity, so apps obtain Azure tokens without client secrets in the cluster.\n\n## When to apply\n- New AKS deployments that call Azure AD\u2013protected resources (Key Vault, Storage, Event Hubs, ACR pull via MI, Azure SQL, etc.)\n- Migrations off client secrets, SP passwords, or connection strings stored as Kubernetes Secrets\n- Replacing legacy Azure AD Pod Identity (`aadpodidentity`, AzureIdentity / AzureIdentityBinding)\n- Reviews of Helm/Kustomize that still inject `AZURE_CLIENT_SECRET` or similar\n\n## Baseline rules\n1. **Prefer Workload Identity** (OIDC federation on the AKS cluster + user-assigned MI) over secrets and over AAD Pod Identity.\n2. **One identity intent per workload** (or tightly related set): map ServiceAccount \u2192 user-assigned MI; avoid a shared \u201ccluster MI\u201d for unrelated apps.\n3. **Least privilege RBAC** on the MI: grant only the Azure roles/data-plane permissions the app needs on specific resource scopes (RG/resource), never Owner/Contributor at subscription by default.\n4. **Namespace labels**: ensure the namespace opted into WI (`azure.workload.identity/use: \"true\"` on the namespace, per current AKS WI docs your platform follows).\n5. **ServiceAccount**: annotate with client id (and tenant if required by your platform pattern):\n - `azure.workload.identity/client-id: `\n - Optional audience / tenant annotations only when your platform standard requires them.\n6. **Pod**: use that ServiceAccount; label pods that participate with `azure.workload.identity/use: \"true\"` when required by the WI mutating webhook in your cluster version.\n7. **Federated credential** on the user-assigned MI must match the issuer of the AKS OIDC issuer and the subject `system:serviceaccount::` (exact SA name and namespace \u2014 typos break auth silently).\n8. **App code**: use Azure Identity SDK `DefaultAzureCredential` / equivalent chain that picks up the WI-injected env (`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE`). Do not hardcode secrets \u201cfor local only\u201d into the same Deployment env.\n9. **Key Vault**: prefer CSI Secrets Store with WI, or SDK access with the same MI \u2014 do not sync long-lived secret values into etcd if CSI + SDK can avoid it.\n10. **Local / CI fallback**: document Azure CLI / env credential / user auth for laptop and pipeline; keep that path out of the in-cluster Deployment manifest.\n\n## Structure\n1. Infra (Bicep/Terraform/az): user-assigned MI + federated identity credential bound to SA subject + OIDC issuer.\n2. Cluster: WI addon / OIDC issuer enabled (do not invent enablement steps if the platform repo already owns cluster bootstrap).\n3. App manifests: Namespace label \u2192 ServiceAccount (annotated) \u2192 Deployment/StatefulSet `serviceAccountName` + WI use label \u2192 no client-secret env vars.\n4. Azure RBAC assignments scoped to the resources the app actually calls.\n5. README or runbook: how to rotate by swapping MI / federated credential, and how to validate token acquisition.\n\n## Validation\n1. Confirm OIDC issuer URL on the cluster matches the federated credential issuer.\n2. Confirm SA name/namespace in the federated credential subject equal the live ServiceAccount.\n3. From a debug shell in the pod (non-prod): check projected token file exists and Azure SDK / `az login --federated-token` (or equivalent) can obtain an access token for a known resource.\n4. Negative test: wrong SA or missing annotation fails closed (no silent fallback to a shared secret).\n5. PR checklist: no `AZURE_CLIENT_SECRET`, no SP password in Secrets, no `aadpodidbinding` / AzureIdentityBinding leftovers for this app.\n\n## Anti-patterns\n- Storing Azure client secrets or SP passwords in Kubernetes Secrets \u201ctemporarily\u201d\n- Re-introducing Azure AD Pod Identity CRDs for new work\n- One shared MI with broad Contributor for every namespace\n- Hardcoding subscription-specific client IDs in app code instead of SA annotation / chart values\n- Mounting the federated token path world-readable or logging token contents\n- Leaving both WI and a client-secret env var so the SDK prefers the secret path\n- Copying federated credential subjects across environments without updating namespace/SA\n\n## Output format\n- Identity map: namespace / SA / UAMI client id / federated subject / Azure roles\n- Manifest and IaC files touched\n- Secrets / aadpodidentity objects to delete\n- Validation commands and residual risks (local-dev, CSI vs SDK, privileged roles)\n" }, { "id": "spring-boot-actuator-hardening", @@ -290,7 +290,7 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-boot-actuator-hardening.instructions.md` with applyTo for `**/application*.{yml,yaml,properties}`, `**/Management*Config*.java`, `**/Security*Config*.java`, and `**/actuator/**`. Claude Code: `.claude/skills/spring-boot-actuator-hardening/SKILL.md` (plus a short CLAUDE.md fact that Actuator must not expose env/heapdump/shutdown publicly). Codex: an Actuator / management endpoints section in root `AGENTS.md` or nested `src/main/AGENTS.md`.", - "body": "# Skill: Spring Boot Actuator Hardening\n\n## Goal\nKeep Spring Boot Actuator useful for ops (liveness/readiness, basic info, authenticated metrics) while preventing public or unauthenticated exposure of sensitive management endpoints that leak config, memory, threads, or cloud metadata.\n\n## When to apply\n- New Spring Boot 2.x/3.x services enabling `spring-boot-starter-actuator`\n- Reviews of `management.endpoints.*` / `management.server.*` before production\n- Kubernetes Deployments where probes hit `/actuator/health` (or a custom base-path)\n- Apps that scrape Micrometer/Prometheus metrics or attach continuous profilers\n- Any change that widens `include=*` exposure or moves Actuator onto the public port\n\n## Baseline rules\n1. **Expose only what ops needs.** Prefer `health` and `info` (and `prometheus`/`metrics` only if scrape auth is in place). Never ship `include=*` in production.\n2. **Never expose publicly:** `env`, `heapdump`, `threaddump`, `logfile`, `shutdown`, `configprops`, `beans`, `mappings`, `conditions`, `httptrace`/`httpexchanges`, and similar high-sensitivity endpoints — even \"temporarily\".\n3. **Separate management port when the app has a public HTTP surface.** Use `management.server.port` (and optionally `management.server.address`) so probes/scrapes do not share the user-facing listener. Document the port in Deployment/Service manifests.\n4. **Same-port pitfalls.** If Actuator stays on the app port, treat every exposed path as internet-facing unless a gateway/ingress explicitly blocks `/actuator/**` (or your `management.endpoints.web.base-path`). Prefer deny-by-default at the edge plus app-level auth.\n5. **Spring Boot 3 exposure knobs.** Use `management.endpoints.web.exposure.include` / `.exclude` explicitly; set `management.endpoints.web.base-path` deliberately (default `/actuator`). Do not rely on framework defaults differing across Boot 2→3 upgrades.\n6. **Health details.** Keep `management.endpoint.health.show-details` and `show-components` at `never` for anonymous callers; use `when_authorized` only when Spring Security roles for operators are real and tested.\n7. **Secure sensitive endpoints with Spring Security.** Anything beyond anonymous health/info must require authentication (HTTP basic for scrapers only over mTLS/private network, or OAuth2/JWT roles for humans). Map Actuator under a dedicated `SecurityFilterChain` with `EndpointRequest.to(...)` / `toAnyEndpoint()` rather than ad-hoc path matchers alone.\n8. **Kubernetes probes vs public routes.** Point `livenessProbe`/`readinessProbe` at the management port (or an edge-blocked path). Do not publish the management Service/port on a public LoadBalancer/Ingress. Use a ClusterIP + NetworkPolicy when scrapers live in-cluster.\n9. **Metrics / Pyroscope / profiler scrape auth.** Prometheus scrapes and continuous profiling agents must authenticate or run on a private network path. Do not leave `/actuator/prometheus` or profiler ports open on the public Service. Prefer scrape configs with bearer tokens or mTLS; document the contract in the chart/values.\n10. **CSRF for browser-facing management.** If Actuator is reachable from a browser session (same-site cookies), keep CSRF protection enabled for state-changing endpoint POSTs (e.g. `shutdown`). Machine scrapers should use non-browser auth that is CSRF-exempt by design — do not disable CSRF globally to \"fix\" Actuator.\n11. **Cloud metadata leakage.** The `env` endpoint and over-broad `info` contributors can surface container/cloud metadata, K8s service account paths, and secret-backed env vars. Keep `env` off the exposure list; scrub custom `info` contributors; never mirror `AWS_*/AZURE_*/GCP_*` or mounted token paths into public payloads.\n12. **Shutdown and write endpoints.** Disable or tightly role-gate `shutdown` and any custom write-capable endpoints. Production should not allow remote process death via HTTP without break-glass controls.\n\n## Structure\n1. Dependencies: `spring-boot-starter-actuator` (+ Security, Micrometer registry only as needed).\n2. Config: `application.yml` / profile-specific files with explicit exposure, base-path, health show-details, and optional `management.server.port`.\n3. Security: dedicated `SecurityFilterChain` for management (`EndpointRequest`), separate from the API chain when useful.\n4. Platform: Deployment probes → management port; Service/Ingress must not publish management publicly; scrape auth documented.\n5. Docs/runbook: which endpoints exist, who may call them, and how to verify from inside the cluster.\n\n## Validation\n1. Hit public base URL: `/actuator` (or custom base-path) should not list sensitive links anonymously; unauthenticated `env`/`heapdump`/`threaddump`/`shutdown` → 401/404/403.\n2. Probes succeed against the intended health path on the management port (or private path).\n3. With an operator credential: `health` details appear only when `when_authorized` is configured and the principal has the expected role.\n4. Confirm scrape job works with auth and fails closed without credentials.\n5. Grep config for `include: \"*\"`, `show-details: always`, and exposed `env`/`heapdump`/`shutdown` before merge.\n6. PR checklist: management port (if used) not on public Ingress; no secret values in `info`; CSRF not globally disabled for browser sessions.\n\n## Anti-patterns\n- `management.endpoints.web.exposure.include: \"*\"` in any shared or prod profile\n- `show-details: always` on publicly reachable health\n- Actuator on the public port with no Security filter and no ingress deny\n- Publishing management port via public LoadBalancer \"for convenience\"\n- Leaving `env` enabled so cloud metadata and secret-backed variables leak\n- Disabling CSRF application-wide so `shutdown` works from a browser\n- Relying only on \"security through obscure base-path\" (`/secret-actuator`)\n- Copying local-dev `include=*` settings into the default/prod profile\n\n## Output format\n- Exposure matrix: endpoint → anonymous / authenticated role / disabled\n- Config + `SecurityFilterChain` diffs (and management port if introduced)\n- Probe / Service / Ingress patches\n- Validation commands (curl from inside vs outside the cluster) and residual risks\n" + "body": "# Skill: Spring Boot Actuator Hardening\n\n## Goal\nKeep Spring Boot Actuator useful for ops (liveness/readiness, basic info, authenticated metrics) while preventing public or unauthenticated exposure of sensitive management endpoints that leak config, memory, threads, or cloud metadata.\n\n## When to apply\n- New Spring Boot 2.x/3.x services enabling `spring-boot-starter-actuator`\n- Reviews of `management.endpoints.*` / `management.server.*` before production\n- Kubernetes Deployments where probes hit `/actuator/health` (or a custom base-path)\n- Apps that scrape Micrometer/Prometheus metrics or attach continuous profilers\n- Any change that widens `include=*` exposure or moves Actuator onto the public port\n\n## Baseline rules\n1. **Expose only what ops needs.** Prefer `health` and `info` (and `prometheus`/`metrics` only if scrape auth is in place). Never ship `include=*` in production.\n2. **Never expose publicly:** `env`, `heapdump`, `threaddump`, `logfile`, `shutdown`, `configprops`, `beans`, `mappings`, `conditions`, `httptrace`/`httpexchanges`, and similar high-sensitivity endpoints \u2014 even \"temporarily\".\n3. **Separate management port when the app has a public HTTP surface.** Use `management.server.port` (and optionally `management.server.address`) so probes/scrapes do not share the user-facing listener. Document the port in Deployment/Service manifests.\n4. **Same-port pitfalls.** If Actuator stays on the app port, treat every exposed path as internet-facing unless a gateway/ingress explicitly blocks `/actuator/**` (or your `management.endpoints.web.base-path`). Prefer deny-by-default at the edge plus app-level auth.\n5. **Spring Boot 3 exposure knobs.** Use `management.endpoints.web.exposure.include` / `.exclude` explicitly; set `management.endpoints.web.base-path` deliberately (default `/actuator`). Do not rely on framework defaults differing across Boot 2\u21923 upgrades.\n6. **Health details.** Keep `management.endpoint.health.show-details` and `show-components` at `never` for anonymous callers; use `when_authorized` only when Spring Security roles for operators are real and tested.\n7. **Secure sensitive endpoints with Spring Security.** Anything beyond anonymous health/info must require authentication (HTTP basic for scrapers only over mTLS/private network, or OAuth2/JWT roles for humans). Map Actuator under a dedicated `SecurityFilterChain` with `EndpointRequest.to(...)` / `toAnyEndpoint()` rather than ad-hoc path matchers alone.\n8. **Kubernetes probes vs public routes.** Point `livenessProbe`/`readinessProbe` at the management port (or an edge-blocked path). Do not publish the management Service/port on a public LoadBalancer/Ingress. Use a ClusterIP + NetworkPolicy when scrapers live in-cluster.\n9. **Metrics / Pyroscope / profiler scrape auth.** Prometheus scrapes and continuous profiling agents must authenticate or run on a private network path. Do not leave `/actuator/prometheus` or profiler ports open on the public Service. Prefer scrape configs with bearer tokens or mTLS; document the contract in the chart/values.\n10. **CSRF for browser-facing management.** If Actuator is reachable from a browser session (same-site cookies), keep CSRF protection enabled for state-changing endpoint POSTs (e.g. `shutdown`). Machine scrapers should use non-browser auth that is CSRF-exempt by design \u2014 do not disable CSRF globally to \"fix\" Actuator.\n11. **Cloud metadata leakage.** The `env` endpoint and over-broad `info` contributors can surface container/cloud metadata, K8s service account paths, and secret-backed env vars. Keep `env` off the exposure list; scrub custom `info` contributors; never mirror `AWS_*/AZURE_*/GCP_*` or mounted token paths into public payloads.\n12. **Shutdown and write endpoints.** Disable or tightly role-gate `shutdown` and any custom write-capable endpoints. Production should not allow remote process death via HTTP without break-glass controls.\n\n## Structure\n1. Dependencies: `spring-boot-starter-actuator` (+ Security, Micrometer registry only as needed).\n2. Config: `application.yml` / profile-specific files with explicit exposure, base-path, health show-details, and optional `management.server.port`.\n3. Security: dedicated `SecurityFilterChain` for management (`EndpointRequest`), separate from the API chain when useful.\n4. Platform: Deployment probes \u2192 management port; Service/Ingress must not publish management publicly; scrape auth documented.\n5. Docs/runbook: which endpoints exist, who may call them, and how to verify from inside the cluster.\n\n## Validation\n1. Hit public base URL: `/actuator` (or custom base-path) should not list sensitive links anonymously; unauthenticated `env`/`heapdump`/`threaddump`/`shutdown` \u2192 401/404/403.\n2. Probes succeed against the intended health path on the management port (or private path).\n3. With an operator credential: `health` details appear only when `when_authorized` is configured and the principal has the expected role.\n4. Confirm scrape job works with auth and fails closed without credentials.\n5. Grep config for `include: \"*\"`, `show-details: always`, and exposed `env`/`heapdump`/`shutdown` before merge.\n6. PR checklist: management port (if used) not on public Ingress; no secret values in `info`; CSRF not globally disabled for browser sessions.\n\n## Anti-patterns\n- `management.endpoints.web.exposure.include: \"*\"` in any shared or prod profile\n- `show-details: always` on publicly reachable health\n- Actuator on the public port with no Security filter and no ingress deny\n- Publishing management port via public LoadBalancer \"for convenience\"\n- Leaving `env` enabled so cloud metadata and secret-backed variables leak\n- Disabling CSRF application-wide so `shutdown` works from a browser\n- Relying only on \"security through obscure base-path\" (`/secret-actuator`)\n- Copying local-dev `include=*` settings into the default/prod profile\n\n## Output format\n- Exposure matrix: endpoint \u2192 anonymous / authenticated role / disabled\n- Config + `SecurityFilterChain` diffs (and management port if introduced)\n- Probe / Service / Ingress patches\n- Validation commands (curl from inside vs outside the cluster) and residual risks\n" }, { "id": "flyway-migration-guardrails", @@ -309,12 +309,12 @@ "database" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/flyway-migration-guardrails.instructions.md` with applyTo for `**/db/migration/**`, `**/db/callback/**`, `**/application*.{yml,yaml,properties}`, and `**/*Flyway*.java`. Claude Code: `.claude/skills/flyway-migration-guardrails/SKILL.md` (plus a short CLAUDE.md fact that schema changes must be expand/contract and never drop in the same release as a code cutover). Codex: a Flyway / schema migration section in root `AGENTS.md` or nested `src/main/resources/AGENTS.md`.", - "body": "# Skill: Flyway Schema Migration Guardrails\n\n## Goal\nShip ordered, reversible-in-practice schema changes for Spring Boot apps using Flyway (or Liquibase-equivalent concepts) so migrations are forward-only, expandable before contract, CI-validated, secret-free, and safe to promote across environments alongside zero-downtime deploys on AKS/Kubernetes.\n\n## When to apply\n- Adding or changing Flyway (or Liquibase) migrations in a Spring Boot service\n- Reviews of `db/migration`, `spring.flyway.*`, or CI jobs that run migrate/validate\n- Schema cutovers that must not break rolling Deployments (old and new pods temporarily coexist)\n- Multi-env promotion (dev → test → staging → prod) where checksum/history drift is a risk\n- Any PR that drops columns/tables, renames, backfills, or changes constraints under load\n\n## Baseline rules\n1. **Forward-only versions.** Prefer `V{version}__description.sql` with monotonically increasing versions. Treat applied migrations as immutable history — never edit a shipped checksum to \"fix\" prod; add a new version instead.\n2. **Expand / contract, never big-bang cutover.** Expand first (add nullable column, new table, dual-write path); deploy code that tolerates both shapes; backfill; then contract (drop old column/table) in a later release after all pods and readers have moved on.\n3. **No destructive drops in the same release as a code cutover.** Do not `DROP COLUMN` / `DROP TABLE` / rename-in-place in the migration that ships with the app version that still reads the old shape. Split across releases with an explicit soak window.\n4. **Lock and statement timeouts.** Set DB session lock/statement timeouts appropriate to the engine (e.g. `lock_timeout`, `statement_timeout` on PostgreSQL; equivalent session settings elsewhere) so a blocked migrate fails fast instead of holding exclusive locks forever. Prefer online / concurrent patterns where the engine supports them.\n5. **Repeatable migrations sparingly.** Use `R__*.sql` only for idempotent views, functions, or reference seed that must re-apply when checksum changes. Never put irreversible DDL or one-shot data fixes in repeatables.\n6. **Out-of-order policy is deliberate.** Keep `spring.flyway.out-of-order` false in shared and prod profiles unless you have a documented hotfix branch process and repair playbook. Accidental out-of-order applies are a common multi-branch footgun.\n7. **CI must validate before merge.** Run `flyway info` / `flyway validate` (or Spring Boot test that boots with validate-on-migrate) on every PR. Fail on checksum mismatch, missing migrations, or failed pending scripts. Prefer an ephemeral DB (Testcontainers / service container) over mocking Flyway away.\n8. **Multi-env promotion is append-only.** The same versioned files promote unchanged. Do not maintain env-specific DDL forks. Seed/config that differs by env belongs in app config or controlled seed jobs — not in versioned migrations with secrets.\n9. **Secrets never in SQL.** No passwords, API keys, connection strings, or PII dumps in migration files. Use placeholders only for non-secret identifiers if needed; inject credentials via Key Vault / env / sealed secrets outside SQL.\n10. **Rollback and repair are operational, not automatic.** Flyway does not magically undo DDL. Plan expand/contract so \"rollback\" means redeploy previous app bits against a still-compatible schema. Use `flyway repair` only for known metadata/checksum fixes after intentional history correction — never as a routine merge step.\n11. **Pair with zero-downtime deploys.** On AKS/K8s, assume N and N-1 pods during rolling update. Migrations must leave the schema readable/writable by both code generations. Prefer init/Job migrate-before-rollout or a controlled migrate step with pod disruption awareness — not racing concurrent migrators without a lock story.\n12. **Naming and ownership.** One team owns the migration sequence. Version numbers (or Flyway Teams/Community versioning scheme you adopt) must be coordinated across branches; rebase rather than invent colliding versions.\n\n## Steps\n1. **Inventory.** Locate `classpath:db/migration` (or configured locations), Flyway/Liquibase dependency, `spring.flyway.*` / `spring.liquibase.*`, and any CI migrate/validate jobs. Note DB engine and whether migrate runs in-app on startup, as a Job, or in pipeline.\n2. **Classify the change.** Additive (safe expand), backfill, constraint tighten, rename, or destructive contract. If destructive or rename, split into expand → dual-support code → backfill → contract PRs.\n3. **Author the next version.** Create `V{next}__short_snake_description.sql` with explicit, idempotent-as-possible DDL for the engine. Prefer additive nullables and new objects first. Avoid multi-statement ambiguous transactions on engines that auto-commit DDL.\n4. **Wire app tolerance.** Update entities/repositories/SQL to tolerate old+new shapes when expand is incomplete. Feature-flag dual-write if needed. Do not require the contracted schema in the same Deployment revision as the expand.\n5. **CI gate.** Ensure PR pipeline runs validate/info against a clean and against a DB that already applied prior versions. Assert checksum stability for already-merged files.\n6. **Promotion checklist.** Confirm the same artifact/migration set will apply in higher envs; document expected lock duration and any required maintenance window; verify K8s rollout strategy (maxUnavailable / migrate Job ordering).\n7. **Contract later.** After soak and traffic proof, open a follow-up migration that drops obsolete objects — only when N-1 code is gone.\n\n## Constraints\n- Do not edit or delete already-applied versioned files on shared branches.\n- Do not embed secrets, prod hostnames with credentials, or real PII in SQL or README samples.\n- Do not enable `clean` / `clean-disabled=false` in non-ephemeral environments.\n- Do not assume Liquibase `rollback` blocks exist for Flyway workflows; spell out expand/contract instead.\n- Keep examples engine-aware (call out PostgreSQL vs others) without inventing proprietary vendor runbooks.\n- Prefer minimal diffs; no unrelated Flyway config refactors in the same PR unless required for safety (timeouts, validate-on-migrate).\n\n## Examples\n- **Expand:** `V42__add_orders_fulfillment_status.sql` adds nullable `fulfillment_status` with a default or null; app N writes both legacy flag and new column; app N+1 reads new column; later `V55__drop_orders_legacy_fulfilled_flag.sql` contracts.\n- **CI:** PR job starts Postgres service, runs app tests with `spring.flyway.validate-on-migrate=true`, and fails if `flyway validate` reports checksum mismatch.\n- **AKS:** Migrate Job (or pre-sync hook) completes successfully before Deployment rollout; readiness only passes when schema version ≥ required; old ReplicaSet drained only after dual-read code is live.\n- **Repair caveat:** After an emergency hotfix that required rewriting an unapplied local file, repair metadata in lower envs with documented approval — never silently repair prod checksums from a laptop.\n\n## Verification\n1. `flyway info` (or Boot Actuator/Flyway endpoint if intentionally exposed to operators only) shows pending → success without error; applied versions match git.\n2. `flyway validate` clean on CI against the migration folder; no checksum diffs on historical versions.\n3. Integration test: boot app against Testcontainers DB twice (migrate fresh + restart) without failure.\n4. Expand PR: old app binary still reads/writes successfully against the expanded schema.\n5. Grep migrations for password/secret patterns and for `DROP`/`RENAME` colocated with feature cutover code in the same PR.\n6. Confirm `out-of-order` and `clean` remain unsafe-default in prod profile; lock/statement timeouts present or documented.\n7. Rollout dry-run notes: N and N-1 compatibility acknowledged; contract migration scheduled separately.\n\n## Output format\n- Change classification (expand / backfill / contract / config-only)\n- New `V*__*.sql` (and any repeatable) with engine notes\n- `spring.flyway.*` diffs if timeouts/validate/out-of-order need tightening\n- CI validate/info steps\n- K8s/AKS ordering notes for zero-downtime\n- Verification checklist and residual risks (lock duration, long backfills)\n" + "body": "# Skill: Flyway Schema Migration Guardrails\n\n## Goal\nShip ordered, reversible-in-practice schema changes for Spring Boot apps using Flyway (or Liquibase-equivalent concepts) so migrations are forward-only, expandable before contract, CI-validated, secret-free, and safe to promote across environments alongside zero-downtime deploys on AKS/Kubernetes.\n\n## When to apply\n- Adding or changing Flyway (or Liquibase) migrations in a Spring Boot service\n- Reviews of `db/migration`, `spring.flyway.*`, or CI jobs that run migrate/validate\n- Schema cutovers that must not break rolling Deployments (old and new pods temporarily coexist)\n- Multi-env promotion (dev \u2192 test \u2192 staging \u2192 prod) where checksum/history drift is a risk\n- Any PR that drops columns/tables, renames, backfills, or changes constraints under load\n\n## Baseline rules\n1. **Forward-only versions.** Prefer `V{version}__description.sql` with monotonically increasing versions. Treat applied migrations as immutable history \u2014 never edit a shipped checksum to \"fix\" prod; add a new version instead.\n2. **Expand / contract, never big-bang cutover.** Expand first (add nullable column, new table, dual-write path); deploy code that tolerates both shapes; backfill; then contract (drop old column/table) in a later release after all pods and readers have moved on.\n3. **No destructive drops in the same release as a code cutover.** Do not `DROP COLUMN` / `DROP TABLE` / rename-in-place in the migration that ships with the app version that still reads the old shape. Split across releases with an explicit soak window.\n4. **Lock and statement timeouts.** Set DB session lock/statement timeouts appropriate to the engine (e.g. `lock_timeout`, `statement_timeout` on PostgreSQL; equivalent session settings elsewhere) so a blocked migrate fails fast instead of holding exclusive locks forever. Prefer online / concurrent patterns where the engine supports them.\n5. **Repeatable migrations sparingly.** Use `R__*.sql` only for idempotent views, functions, or reference seed that must re-apply when checksum changes. Never put irreversible DDL or one-shot data fixes in repeatables.\n6. **Out-of-order policy is deliberate.** Keep `spring.flyway.out-of-order` false in shared and prod profiles unless you have a documented hotfix branch process and repair playbook. Accidental out-of-order applies are a common multi-branch footgun.\n7. **CI must validate before merge.** Run `flyway info` / `flyway validate` (or Spring Boot test that boots with validate-on-migrate) on every PR. Fail on checksum mismatch, missing migrations, or failed pending scripts. Prefer an ephemeral DB (Testcontainers / service container) over mocking Flyway away.\n8. **Multi-env promotion is append-only.** The same versioned files promote unchanged. Do not maintain env-specific DDL forks. Seed/config that differs by env belongs in app config or controlled seed jobs \u2014 not in versioned migrations with secrets.\n9. **Secrets never in SQL.** No passwords, API keys, connection strings, or PII dumps in migration files. Use placeholders only for non-secret identifiers if needed; inject credentials via Key Vault / env / sealed secrets outside SQL.\n10. **Rollback and repair are operational, not automatic.** Flyway does not magically undo DDL. Plan expand/contract so \"rollback\" means redeploy previous app bits against a still-compatible schema. Use `flyway repair` only for known metadata/checksum fixes after intentional history correction \u2014 never as a routine merge step.\n11. **Pair with zero-downtime deploys.** On AKS/K8s, assume N and N-1 pods during rolling update. Migrations must leave the schema readable/writable by both code generations. Prefer init/Job migrate-before-rollout or a controlled migrate step with pod disruption awareness \u2014 not racing concurrent migrators without a lock story.\n12. **Naming and ownership.** One team owns the migration sequence. Version numbers (or Flyway Teams/Community versioning scheme you adopt) must be coordinated across branches; rebase rather than invent colliding versions.\n\n## Steps\n1. **Inventory.** Locate `classpath:db/migration` (or configured locations), Flyway/Liquibase dependency, `spring.flyway.*` / `spring.liquibase.*`, and any CI migrate/validate jobs. Note DB engine and whether migrate runs in-app on startup, as a Job, or in pipeline.\n2. **Classify the change.** Additive (safe expand), backfill, constraint tighten, rename, or destructive contract. If destructive or rename, split into expand \u2192 dual-support code \u2192 backfill \u2192 contract PRs.\n3. **Author the next version.** Create `V{next}__short_snake_description.sql` with explicit, idempotent-as-possible DDL for the engine. Prefer additive nullables and new objects first. Avoid multi-statement ambiguous transactions on engines that auto-commit DDL.\n4. **Wire app tolerance.** Update entities/repositories/SQL to tolerate old+new shapes when expand is incomplete. Feature-flag dual-write if needed. Do not require the contracted schema in the same Deployment revision as the expand.\n5. **CI gate.** Ensure PR pipeline runs validate/info against a clean and against a DB that already applied prior versions. Assert checksum stability for already-merged files.\n6. **Promotion checklist.** Confirm the same artifact/migration set will apply in higher envs; document expected lock duration and any required maintenance window; verify K8s rollout strategy (maxUnavailable / migrate Job ordering).\n7. **Contract later.** After soak and traffic proof, open a follow-up migration that drops obsolete objects \u2014 only when N-1 code is gone.\n\n## Constraints\n- Do not edit or delete already-applied versioned files on shared branches.\n- Do not embed secrets, prod hostnames with credentials, or real PII in SQL or README samples.\n- Do not enable `clean` / `clean-disabled=false` in non-ephemeral environments.\n- Do not assume Liquibase `rollback` blocks exist for Flyway workflows; spell out expand/contract instead.\n- Keep examples engine-aware (call out PostgreSQL vs others) without inventing proprietary vendor runbooks.\n- Prefer minimal diffs; no unrelated Flyway config refactors in the same PR unless required for safety (timeouts, validate-on-migrate).\n\n## Examples\n- **Expand:** `V42__add_orders_fulfillment_status.sql` adds nullable `fulfillment_status` with a default or null; app N writes both legacy flag and new column; app N+1 reads new column; later `V55__drop_orders_legacy_fulfilled_flag.sql` contracts.\n- **CI:** PR job starts Postgres service, runs app tests with `spring.flyway.validate-on-migrate=true`, and fails if `flyway validate` reports checksum mismatch.\n- **AKS:** Migrate Job (or pre-sync hook) completes successfully before Deployment rollout; readiness only passes when schema version \u2265 required; old ReplicaSet drained only after dual-read code is live.\n- **Repair caveat:** After an emergency hotfix that required rewriting an unapplied local file, repair metadata in lower envs with documented approval \u2014 never silently repair prod checksums from a laptop.\n\n## Verification\n1. `flyway info` (or Boot Actuator/Flyway endpoint if intentionally exposed to operators only) shows pending \u2192 success without error; applied versions match git.\n2. `flyway validate` clean on CI against the migration folder; no checksum diffs on historical versions.\n3. Integration test: boot app against Testcontainers DB twice (migrate fresh + restart) without failure.\n4. Expand PR: old app binary still reads/writes successfully against the expanded schema.\n5. Grep migrations for password/secret patterns and for `DROP`/`RENAME` colocated with feature cutover code in the same PR.\n6. Confirm `out-of-order` and `clean` remain unsafe-default in prod profile; lock/statement timeouts present or documented.\n7. Rollout dry-run notes: N and N-1 compatibility acknowledged; contract migration scheduled separately.\n\n## Output format\n- Change classification (expand / backfill / contract / config-only)\n- New `V*__*.sql` (and any repeatable) with engine notes\n- `spring.flyway.*` diffs if timeouts/validate/out-of-order need tightening\n- CI validate/info steps\n- K8s/AKS ordering notes for zero-downtime\n- Verification checklist and residual risks (lock duration, long backfills)\n" }, { "id": "spring-boot-testcontainers", "title": "Spring Boot Testcontainers Guardrails", - "whenToUse": "Adding or reviewing Spring Boot integration tests that need real Postgres, Kafka, Redis, LocalStack, or other dependencies in Docker via Testcontainers — keep suites fast, hermetic, CI-friendly, and free of shared-env flakiness.", + "whenToUse": "Adding or reviewing Spring Boot integration tests that need real Postgres, Kafka, Redis, LocalStack, or other dependencies in Docker via Testcontainers \u2014 keep suites fast, hermetic, CI-friendly, and free of shared-env flakiness.", "tools": [ "copilot", "claude-code", @@ -328,12 +328,12 @@ "docker" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-boot-testcontainers.instructions.md` with applyTo for `**/src/test/**/*IT.java`, `**/src/test/**/*IntegrationTest.java`, `**/src/test/**/Abstract*Container*.java`, and `**/src/test/resources/application*.{yml,yaml,properties}`. Claude Code: `.claude/skills/spring-boot-testcontainers/SKILL.md` (plus a short CLAUDE.md fact that integration tests use Testcontainers, not shared staging DBs). Codex: a Testcontainers / integration-test section in root `AGENTS.md` or nested `src/test/AGENTS.md`.", - "body": "# Skill: Spring Boot Testcontainers Guardrails\n\n## Goal\nShip hermetic Spring Boot integration tests that boot real dependencies (Postgres, Kafka, Redis, LocalStack, etc.) via Testcontainers so suites stay reproducible on developer laptops and CI, never share mutable staging state, and fail for the right reasons.\n\n## When to apply\n- Adding `@SpringBootTest` / slice tests that need a database, broker, or cloud emulator\n- Replacing `@MockBean`-heavy tests that hide wiring bugs at the repository/adapter boundary\n- Reviews of `src/test` that hit shared Docker hosts, hardcoded ports, or remote staging credentials\n- CI jobs that intermittently fail with \"connection refused\", dirty schema, or port conflicts\n- Pairing with Flyway/Liquibase migrations that must be validated against a real engine\n\n## Baseline rules\n1. **Real dependency, fake network.** Prefer Testcontainers (or the Spring Boot 3.1+ service-connection support) over mocking the JDBC/driver layer when the bug class is SQL dialect, migrations, serialization, or broker semantics.\n2. **No shared staging DBs in unit/CI gates.** Integration tests must not require VPN, shared Postgres, or hand-provisioned Redis. If a test needs those, it is an external contract test and belongs in a separate, opt-in job.\n3. **One container lifecycle strategy per suite.** Prefer singleton containers reused across tests in a JVM (static start + Ryuk cleanup) or Spring's `@ServiceConnection` / `DynamicPropertySource` — pick one pattern per module and stick to it. Do not start a new Postgres per `@Test` method unless isolation is the point under test.\n4. **Pin images.** Use explicit tags or digests (e.g. `postgres:16-alpine`), never `latest`. Document why a major bump is intentional.\n5. **Let Spring wire connections.** Prefer `@ServiceConnection` (Boot 3.1+) or a single `DynamicPropertySource` that sets JDBC URL/user/password from the container. Avoid copying host/port into `application-test.yml` by hand.\n6. **Migrations run in-test.** Enable Flyway/Liquibase on the test context (or run migrate in an initializer) so schema matches production promotion. Do not maintain a parallel hand-written test schema unless the product explicitly dual-supports it.\n7. **Keep the slice honest.** `@DataJpaTest` + Testcontainers is fine for persistence; full `@SpringBootTest` for HTTP→DB paths. Do not load the entire app when a slice proves the contract.\n8. **CI must have Docker.** Document that GitHub Actions (or Jenkins) runners need Docker-in-Docker / privileged / mounted docker.sock as your org standard requires. Fail fast with a clear assumption check if Docker is missing (`DockerClientFactory.instance().isDockerAvailable()`).\n9. **Parallelism is opt-in.** Default to sequential module tests when containers share a Docker daemon heavily. If you parallelize, isolate by unique database name / Kafka topic prefix / Redis DB index — never by hoping ports do not collide.\n10. **No secrets in test resources.** Use container defaults or generated credentials. Never commit cloud keys for LocalStack alternatives that talk to real AWS.\n\n## Workflow\n1. Inventory what the production code talks to (DB engine/version, broker, cache, object storage).\n2. Choose the narrowest Spring test slice that still exercises the real adapter.\n3. Add Testcontainers dependencies matching the Spring Boot BOM / testcontainers-bom already in the build (Maven or Gradle). Prefer `junit-jupiter` integration.\n4. Introduce a shared container base (abstract class or `@TestConfiguration`) with pinned image + `@ServiceConnection` / `DynamicPropertySource`.\n5. Write 2–3 tests: happy path, one constraint/validation failure, one failure mapping (e.g. duplicate key, missing row).\n6. Run locally: `./mvnw -pl test` or Gradle equivalent. Confirm Ryuk/containers stop cleanly.\n7. Ensure CI workflow already has Docker; add the module to the PR gate if new.\n8. In the PR description: list images used, whether migrations run, and any tests deliberately left as mocks (with why).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped instructions under `.github/instructions/` with `applyTo` globs for `*IT.java`, `*IntegrationTest.java`, and test `application-*.yml`.\n- Keep always-on `.github/copilot-instructions.md` to one line: integration tests use Testcontainers; no shared staging DBs.\n- Ask Copilot to extend the existing abstract container base rather than inventing a second lifecycle.\n\n### Claude Code\n- Put the procedure in `.claude/skills/spring-boot-testcontainers/SKILL.md`.\n- CLAUDE.md fact only: \"Integration tests use Testcontainers with pinned images; do not point tests at shared staging.\"\n- Have Claude run the module test command and paste output before claiming green.\n\n### Codex\n- Short `AGENTS.md` (or `src/test/AGENTS.md`) section: pinned images, `@ServiceConnection` preferred, Docker required in CI, no staging credentials.\n- Link to this skill or `docs/agents/spring-boot-testcontainers.md` if the body would bloat root AGENTS.md.\n\n## Anti-patterns\n- `localhost:5432` assumptions that pass on one laptop and fail in CI\n- Reusing a developer-installed Postgres with leftover schemas between runs\n- `@MockBean DataSource` / repository mocks for tests whose goal is SQL or migration correctness\n- `latest` image tags and unpinned Testcontainers modules drifting across CI days\n- Starting Postgres + Kafka + LocalStack for a pure mapper unit test\n- Sleeping (\"wait 10s\") instead of waiting on container readiness / Spring context refresh\n- Committing `TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX` hacks without documenting the mirror requirement\n- Disabling Flyway in tests while production relies on it\n\n## Done when\n- [ ] Pinned container image(s) declared in one shared place\n- [ ] Spring obtains JDBC/broker settings from the container (service connection or dynamic properties)\n- [ ] Migrations apply cleanly on a fresh container\n- [ ] At least one happy-path and one failure-path integration test pass locally\n- [ ] CI job has Docker and runs the same module tests\n- [ ] No staging URLs, VPN assumptions, or real cloud secrets in `src/test`\n- [ ] PR notes which boundaries stay mocked and why\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-testcontainers\ndescription: Use when adding or reviewing Spring Boot integration tests with Testcontainers (Postgres, Kafka, Redis, LocalStack). Enforces pinned images, @ServiceConnection or DynamicPropertySource, hermetic CI, and no shared staging databases.\n---\n\nFollow the Spring Boot Testcontainers Guardrails skill: pinned images, one lifecycle per suite, migrations on, Docker required in CI, no staging credentials.\n```\n" + "body": "# Skill: Spring Boot Testcontainers Guardrails\n\n## Goal\nShip hermetic Spring Boot integration tests that boot real dependencies (Postgres, Kafka, Redis, LocalStack, etc.) via Testcontainers so suites stay reproducible on developer laptops and CI, never share mutable staging state, and fail for the right reasons.\n\n## When to apply\n- Adding `@SpringBootTest` / slice tests that need a database, broker, or cloud emulator\n- Replacing `@MockBean`-heavy tests that hide wiring bugs at the repository/adapter boundary\n- Reviews of `src/test` that hit shared Docker hosts, hardcoded ports, or remote staging credentials\n- CI jobs that intermittently fail with \"connection refused\", dirty schema, or port conflicts\n- Pairing with Flyway/Liquibase migrations that must be validated against a real engine\n\n## Baseline rules\n1. **Real dependency, fake network.** Prefer Testcontainers (or the Spring Boot 3.1+ service-connection support) over mocking the JDBC/driver layer when the bug class is SQL dialect, migrations, serialization, or broker semantics.\n2. **No shared staging DBs in unit/CI gates.** Integration tests must not require VPN, shared Postgres, or hand-provisioned Redis. If a test needs those, it is an external contract test and belongs in a separate, opt-in job.\n3. **One container lifecycle strategy per suite.** Prefer singleton containers reused across tests in a JVM (static start + Ryuk cleanup) or Spring's `@ServiceConnection` / `DynamicPropertySource` \u2014 pick one pattern per module and stick to it. Do not start a new Postgres per `@Test` method unless isolation is the point under test.\n4. **Pin images.** Use explicit tags or digests (e.g. `postgres:16-alpine`), never `latest`. Document why a major bump is intentional.\n5. **Let Spring wire connections.** Prefer `@ServiceConnection` (Boot 3.1+) or a single `DynamicPropertySource` that sets JDBC URL/user/password from the container. Avoid copying host/port into `application-test.yml` by hand.\n6. **Migrations run in-test.** Enable Flyway/Liquibase on the test context (or run migrate in an initializer) so schema matches production promotion. Do not maintain a parallel hand-written test schema unless the product explicitly dual-supports it.\n7. **Keep the slice honest.** `@DataJpaTest` + Testcontainers is fine for persistence; full `@SpringBootTest` for HTTP\u2192DB paths. Do not load the entire app when a slice proves the contract.\n8. **CI must have Docker.** Document that GitHub Actions (or Jenkins) runners need Docker-in-Docker / privileged / mounted docker.sock as your org standard requires. Fail fast with a clear assumption check if Docker is missing (`DockerClientFactory.instance().isDockerAvailable()`).\n9. **Parallelism is opt-in.** Default to sequential module tests when containers share a Docker daemon heavily. If you parallelize, isolate by unique database name / Kafka topic prefix / Redis DB index \u2014 never by hoping ports do not collide.\n10. **No secrets in test resources.** Use container defaults or generated credentials. Never commit cloud keys for LocalStack alternatives that talk to real AWS.\n\n## Workflow\n1. Inventory what the production code talks to (DB engine/version, broker, cache, object storage).\n2. Choose the narrowest Spring test slice that still exercises the real adapter.\n3. Add Testcontainers dependencies matching the Spring Boot BOM / testcontainers-bom already in the build (Maven or Gradle). Prefer `junit-jupiter` integration.\n4. Introduce a shared container base (abstract class or `@TestConfiguration`) with pinned image + `@ServiceConnection` / `DynamicPropertySource`.\n5. Write 2\u20133 tests: happy path, one constraint/validation failure, one failure mapping (e.g. duplicate key, missing row).\n6. Run locally: `./mvnw -pl test` or Gradle equivalent. Confirm Ryuk/containers stop cleanly.\n7. Ensure CI workflow already has Docker; add the module to the PR gate if new.\n8. In the PR description: list images used, whether migrations run, and any tests deliberately left as mocks (with why).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped instructions under `.github/instructions/` with `applyTo` globs for `*IT.java`, `*IntegrationTest.java`, and test `application-*.yml`.\n- Keep always-on `.github/copilot-instructions.md` to one line: integration tests use Testcontainers; no shared staging DBs.\n- Ask Copilot to extend the existing abstract container base rather than inventing a second lifecycle.\n\n### Claude Code\n- Put the procedure in `.claude/skills/spring-boot-testcontainers/SKILL.md`.\n- CLAUDE.md fact only: \"Integration tests use Testcontainers with pinned images; do not point tests at shared staging.\"\n- Have Claude run the module test command and paste output before claiming green.\n\n### Codex\n- Short `AGENTS.md` (or `src/test/AGENTS.md`) section: pinned images, `@ServiceConnection` preferred, Docker required in CI, no staging credentials.\n- Link to this skill or `docs/agents/spring-boot-testcontainers.md` if the body would bloat root AGENTS.md.\n\n## Anti-patterns\n- `localhost:5432` assumptions that pass on one laptop and fail in CI\n- Reusing a developer-installed Postgres with leftover schemas between runs\n- `@MockBean DataSource` / repository mocks for tests whose goal is SQL or migration correctness\n- `latest` image tags and unpinned Testcontainers modules drifting across CI days\n- Starting Postgres + Kafka + LocalStack for a pure mapper unit test\n- Sleeping (\"wait 10s\") instead of waiting on container readiness / Spring context refresh\n- Committing `TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX` hacks without documenting the mirror requirement\n- Disabling Flyway in tests while production relies on it\n\n## Done when\n- [ ] Pinned container image(s) declared in one shared place\n- [ ] Spring obtains JDBC/broker settings from the container (service connection or dynamic properties)\n- [ ] Migrations apply cleanly on a fresh container\n- [ ] At least one happy-path and one failure-path integration test pass locally\n- [ ] CI job has Docker and runs the same module tests\n- [ ] No staging URLs, VPN assumptions, or real cloud secrets in `src/test`\n- [ ] PR notes which boundaries stay mocked and why\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-testcontainers\ndescription: Use when adding or reviewing Spring Boot integration tests with Testcontainers (Postgres, Kafka, Redis, LocalStack). Enforces pinned images, @ServiceConnection or DynamicPropertySource, hermetic CI, and no shared staging databases.\n---\n\nFollow the Spring Boot Testcontainers Guardrails skill: pinned images, one lifecycle per suite, migrations on, Docker required in CI, no staging credentials.\n```\n" }, { "id": "spring-security-oauth2-resource-server", "title": "Spring Security OAuth2 Resource Server Guardrails", - "whenToUse": "Configuring or hardening a Spring Boot 3 / Spring Security 6 API as an OAuth2 resource server — JWT decoder (issuer-uri / JWK set), audience and issuer validation, scope-to-authority mapping, method security, and safe defaults for stateless APIs.", + "whenToUse": "Configuring or hardening a Spring Boot 3 / Spring Security 6 API as an OAuth2 resource server \u2014 JWT decoder (issuer-uri / JWK set), audience and issuer validation, scope-to-authority mapping, method security, and safe defaults for stateless APIs.", "tools": [ "copilot", "claude-code", @@ -348,12 +348,12 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-oauth2-resource-server.instructions.md` with applyTo for `**/Security*Config*.java`, `**/*SecurityFilterChain*.java`, `**/src/main/resources/application*.{yml,yaml,properties}`, and `**/src/test/**/*Security*Test*.java`. Claude Code: `.claude/skills/spring-security-oauth2-resource-server/SKILL.md` (plus a short CLAUDE.md fact that APIs validate JWT via oauth2ResourceServer and never disable security in prod profiles). Codex: a Resource Server / JWT section in root `AGENTS.md` or nested `src/main/java/**/security/AGENTS.md`.", - "body": "# Skill: Spring Security OAuth2 Resource Server Guardrails\n\n## Goal\nShip a Spring Boot 3 / Spring Security 6 API that validates bearer tokens correctly (signature, issuer, audience, lifetime), maps scopes/claims into authorities deliberately, keeps CSRF and session settings honest for stateless APIs, and fails closed without leaking token or key material.\n\n## When to apply\n- Adding `spring-boot-starter-oauth2-resource-server` or reviewing an existing `oauth2ResourceServer` `SecurityFilterChain`\n- Wiring JWT decoders via `issuer-uri`, `jwk-set-uri`, or a custom `JwtDecoder` bean\n- Mapping scopes / roles into `GrantedAuthority` and protecting routes or methods\n- Reviews that mention CSRF disabled, `permitAll` on actuators, multi-tenant issuers, or tests with security off\n- Pairing with gateway/BFF work where this service is the resource server, not the authorization server\n\n## Baseline rules\n1. **Prefer `issuer-uri` in production.** It discovers JWKS via OIDC metadata and validates `iss`. Use `jwk-set-uri` alone only when discovery is unavailable or startup must not call the IdP — then add explicit issuer (and audience) validators yourself.\n2. **Validate audience.** Default decoder checks signature, `iss` (with issuer-uri), and time claims; it does **not** enforce `aud`. Add an `OAuth2TokenValidator` so tokens minted for another API are rejected.\n3. **Pin algorithms.** Prefer asymmetric RS256/ES256 from JWKS. If you customize `NimbusJwtDecoder`, set allowed JWS algorithms explicitly; never accept `none` or mixed HMAC+RSA without a deliberate threat model.\n4. **Map authorities on purpose.** Default scope → `SCOPE_` prefix. For roles in `roles`, `realm_access`, or custom claims, use a `JwtAuthenticationConverter` and document the claim path. A valid JWT is not authorization for every route.\n5. **Authorize at the edge and in methods.** `authorizeHttpRequests` for coarse route rules; `@EnableMethodSecurity` + `@PreAuthorize` for finer checks. Keep authority names consistent across both.\n6. **CSRF off only for pure bearer APIs.** `SessionCreationPolicy.STATELESS` + CSRF disabled fits `Authorization: Bearer` with no cookie session. If the same app also serves browser cookie sessions, split filter chains — do not blanket-disable CSRF.\n7. **Opaque vs JWT is a product choice.** JWT: local JWKS validation. Opaque: introspection via `opaquetoken` properties. Do not parse opaque tokens as JWT; do not skip introspection client credentials.\n8. **Error responses stay boring.** 401 for missing/invalid tokens, 403 for insufficient scope. No stack traces, JWKS URLs, expected audiences, or raw tokens in bodies or logs.\n9. **Actuator and filter-order traps.** Do not `permitAll` on `/actuator/**` in the API chain. Prefer a separate management port or role gates. Custom filters before `BearerTokenAuthenticationFilter` must not short-circuit auth.\n10. **Multi-tenant issuers need an allowlist.** Multiple IdPs require a deliberate issuer→decoder map (or trusted-issuer list), not \"accept any `iss`\".\n11. **Test with JWT support, not only mocks.** `@WithMockUser` is fine for method-security units; resource-server integration tests should use `spring-security-test` JWT helpers (`jwt()` / `mockJwt`) or a test decoder that still enforces claim validators. Cover expired, wrong-`aud`, wrong-`iss`, and missing-scope cases.\n12. **Never disable security in prod profiles.** No permissive `SecurityFilterChain` under `prod`, no test-only bypass that leaks into default/prod. Test profiles may use a test decoder — production always validates against the real IdP JWKS/issuer.\n\n## Workflow\n1. Confirm this app is a **resource server** (validates tokens), not an authorization server.\n2. Inventory IdP: issuer, JWKS, expected `aud`, scope vs role claim shape, JWT vs opaque.\n3. Add the resource-server starter; set `spring.security.oauth2.resourceserver.jwt.issuer-uri` and an audience validator.\n4. Author the primary `SecurityFilterChain`: session policy, CSRF decision documented, `oauth2ResourceServer(jwt -> …)`, least-privilege matchers.\n5. Add a converter if authorities are non-default; enable method security where needed.\n6. Lock down actuators/internal paths; align management port / network policy.\n7. Add tests: happy path with required scope; 401 wrong iss/aud/expired; 403 missing scope.\n8. PR notes: issuer, audience, claim→authority map, CSRF rationale, remaining `permitAll` paths.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-oauth2-resource-server.instructions.md` with `applyTo` for security config, `application*.yml`, and `*Security*Test*.java`.\n- Always-on `.github/copilot-instructions.md`: one line — APIs use oauth2ResourceServer JWT validation with audience checks; never disable security in prod.\n- Extend the existing `SecurityFilterChain`; do not invent a second permissive chain.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-security-oauth2-resource-server/SKILL.md`.\n- CLAUDE.md fact: \"Resource APIs validate JWT via Spring oauth2ResourceServer (issuer + audience); do not permitAll actuators or disable CSRF without a bearer-only rationale.\"\n- Run module tests and show 401/403 cases before claiming done.\n\n### Codex\n- Short `AGENTS.md` (or `…/security/AGENTS.md`): issuer-uri preferred, audience required, SCOPE_ or documented converter, CSRF only off for stateless bearer, no prod bypass.\n- Link to this skill or `docs/agents/spring-oauth2-resource-server.md` if root AGENTS.md would bloat.\n\n## Anti-patterns\n- `jwk-set-uri` without issuer/audience validators in multi-API estates\n- Unrestricted JWS algorithms or accepting `alg=none` on a custom decoder\n- `csrf.disable()` on a chain that still uses cookie sessions\n- `anyRequest().permitAll()` left in main \"temporarily\"\n- Logging bearer tokens or full JWT payloads at INFO\n- `@WithMockUser` alone as proof that JWT validation works\n- Hard-coded JWKS PEMs in-repo (breaks key rotation)\n- One chain mixing form-login pages and bearer APIs without path separation\n- Multi-tenant decode-first without an issuer allowlist\n- `@Profile(\"test\")` security config accidentally active outside tests\n\n## Done when\n- [ ] `issuer-uri` (or documented `jwk-set-uri` + validators) configured per environment\n- [ ] Audience (or equivalent API identifier) validated\n- [ ] Scope/role → authority mapping documented and enforced\n- [ ] CSRF/session settings match bearer-only vs cookie reality (split chains if mixed)\n- [ ] Actuator/admin paths are not anonymous on the public port\n- [ ] Tests cover valid token, wrong iss/aud, expired, and insufficient scope\n- [ ] No prod profile disables `SecurityFilterChain` or JWT validation\n- [ ] PR states IdP, audience, claim map, and remaining `permitAll` paths\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-security-oauth2-resource-server\ndescription: Use when configuring or reviewing Spring Boot OAuth2 resource-server JWT/opaque security — issuer-uri/JWKS, audience validation, scope authorities, CSRF for stateless APIs, actuators, and tests. Never disable security in prod.\n---\n\nFollow the Spring Security OAuth2 Resource Server Guardrails skill: issuer + audience validation, deliberate authority mapping, bearer-only CSRF rationale, locked-down actuators, JWT-aware tests.\n```\n" + "body": "# Skill: Spring Security OAuth2 Resource Server Guardrails\n\n## Goal\nShip a Spring Boot 3 / Spring Security 6 API that validates bearer tokens correctly (signature, issuer, audience, lifetime), maps scopes/claims into authorities deliberately, keeps CSRF and session settings honest for stateless APIs, and fails closed without leaking token or key material.\n\n## When to apply\n- Adding `spring-boot-starter-oauth2-resource-server` or reviewing an existing `oauth2ResourceServer` `SecurityFilterChain`\n- Wiring JWT decoders via `issuer-uri`, `jwk-set-uri`, or a custom `JwtDecoder` bean\n- Mapping scopes / roles into `GrantedAuthority` and protecting routes or methods\n- Reviews that mention CSRF disabled, `permitAll` on actuators, multi-tenant issuers, or tests with security off\n- Pairing with gateway/BFF work where this service is the resource server, not the authorization server\n\n## Baseline rules\n1. **Prefer `issuer-uri` in production.** It discovers JWKS via OIDC metadata and validates `iss`. Use `jwk-set-uri` alone only when discovery is unavailable or startup must not call the IdP \u2014 then add explicit issuer (and audience) validators yourself.\n2. **Validate audience.** Default decoder checks signature, `iss` (with issuer-uri), and time claims; it does **not** enforce `aud`. Add an `OAuth2TokenValidator` so tokens minted for another API are rejected.\n3. **Pin algorithms.** Prefer asymmetric RS256/ES256 from JWKS. If you customize `NimbusJwtDecoder`, set allowed JWS algorithms explicitly; never accept `none` or mixed HMAC+RSA without a deliberate threat model.\n4. **Map authorities on purpose.** Default scope \u2192 `SCOPE_` prefix. For roles in `roles`, `realm_access`, or custom claims, use a `JwtAuthenticationConverter` and document the claim path. A valid JWT is not authorization for every route.\n5. **Authorize at the edge and in methods.** `authorizeHttpRequests` for coarse route rules; `@EnableMethodSecurity` + `@PreAuthorize` for finer checks. Keep authority names consistent across both.\n6. **CSRF off only for pure bearer APIs.** `SessionCreationPolicy.STATELESS` + CSRF disabled fits `Authorization: Bearer` with no cookie session. If the same app also serves browser cookie sessions, split filter chains \u2014 do not blanket-disable CSRF.\n7. **Opaque vs JWT is a product choice.** JWT: local JWKS validation. Opaque: introspection via `opaquetoken` properties. Do not parse opaque tokens as JWT; do not skip introspection client credentials.\n8. **Error responses stay boring.** 401 for missing/invalid tokens, 403 for insufficient scope. No stack traces, JWKS URLs, expected audiences, or raw tokens in bodies or logs.\n9. **Actuator and filter-order traps.** Do not `permitAll` on `/actuator/**` in the API chain. Prefer a separate management port or role gates. Custom filters before `BearerTokenAuthenticationFilter` must not short-circuit auth.\n10. **Multi-tenant issuers need an allowlist.** Multiple IdPs require a deliberate issuer\u2192decoder map (or trusted-issuer list), not \"accept any `iss`\".\n11. **Test with JWT support, not only mocks.** `@WithMockUser` is fine for method-security units; resource-server integration tests should use `spring-security-test` JWT helpers (`jwt()` / `mockJwt`) or a test decoder that still enforces claim validators. Cover expired, wrong-`aud`, wrong-`iss`, and missing-scope cases.\n12. **Never disable security in prod profiles.** No permissive `SecurityFilterChain` under `prod`, no test-only bypass that leaks into default/prod. Test profiles may use a test decoder \u2014 production always validates against the real IdP JWKS/issuer.\n\n## Workflow\n1. Confirm this app is a **resource server** (validates tokens), not an authorization server.\n2. Inventory IdP: issuer, JWKS, expected `aud`, scope vs role claim shape, JWT vs opaque.\n3. Add the resource-server starter; set `spring.security.oauth2.resourceserver.jwt.issuer-uri` and an audience validator.\n4. Author the primary `SecurityFilterChain`: session policy, CSRF decision documented, `oauth2ResourceServer(jwt -> \u2026)`, least-privilege matchers.\n5. Add a converter if authorities are non-default; enable method security where needed.\n6. Lock down actuators/internal paths; align management port / network policy.\n7. Add tests: happy path with required scope; 401 wrong iss/aud/expired; 403 missing scope.\n8. PR notes: issuer, audience, claim\u2192authority map, CSRF rationale, remaining `permitAll` paths.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-oauth2-resource-server.instructions.md` with `applyTo` for security config, `application*.yml`, and `*Security*Test*.java`.\n- Always-on `.github/copilot-instructions.md`: one line \u2014 APIs use oauth2ResourceServer JWT validation with audience checks; never disable security in prod.\n- Extend the existing `SecurityFilterChain`; do not invent a second permissive chain.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-security-oauth2-resource-server/SKILL.md`.\n- CLAUDE.md fact: \"Resource APIs validate JWT via Spring oauth2ResourceServer (issuer + audience); do not permitAll actuators or disable CSRF without a bearer-only rationale.\"\n- Run module tests and show 401/403 cases before claiming done.\n\n### Codex\n- Short `AGENTS.md` (or `\u2026/security/AGENTS.md`): issuer-uri preferred, audience required, SCOPE_ or documented converter, CSRF only off for stateless bearer, no prod bypass.\n- Link to this skill or `docs/agents/spring-oauth2-resource-server.md` if root AGENTS.md would bloat.\n\n## Anti-patterns\n- `jwk-set-uri` without issuer/audience validators in multi-API estates\n- Unrestricted JWS algorithms or accepting `alg=none` on a custom decoder\n- `csrf.disable()` on a chain that still uses cookie sessions\n- `anyRequest().permitAll()` left in main \"temporarily\"\n- Logging bearer tokens or full JWT payloads at INFO\n- `@WithMockUser` alone as proof that JWT validation works\n- Hard-coded JWKS PEMs in-repo (breaks key rotation)\n- One chain mixing form-login pages and bearer APIs without path separation\n- Multi-tenant decode-first without an issuer allowlist\n- `@Profile(\"test\")` security config accidentally active outside tests\n\n## Done when\n- [ ] `issuer-uri` (or documented `jwk-set-uri` + validators) configured per environment\n- [ ] Audience (or equivalent API identifier) validated\n- [ ] Scope/role \u2192 authority mapping documented and enforced\n- [ ] CSRF/session settings match bearer-only vs cookie reality (split chains if mixed)\n- [ ] Actuator/admin paths are not anonymous on the public port\n- [ ] Tests cover valid token, wrong iss/aud, expired, and insufficient scope\n- [ ] No prod profile disables `SecurityFilterChain` or JWT validation\n- [ ] PR states IdP, audience, claim map, and remaining `permitAll` paths\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-security-oauth2-resource-server\ndescription: Use when configuring or reviewing Spring Boot OAuth2 resource-server JWT/opaque security \u2014 issuer-uri/JWKS, audience validation, scope authorities, CSRF for stateless APIs, actuators, and tests. Never disable security in prod.\n---\n\nFollow the Spring Security OAuth2 Resource Server Guardrails skill: issuer + audience validation, deliberate authority mapping, bearer-only CSRF rationale, locked-down actuators, JWT-aware tests.\n```\n" }, { "id": "gha-oidc-azure-guardrails", "title": "GitHub Actions OIDC Azure Login Guardrails", - "whenToUse": "Wiring or reviewing GitHub Actions jobs that authenticate to Azure with OIDC (Microsoft Entra federated identity credentials) instead of long-lived client secrets — including subject-claim strategy, immutable sub migration, RBAC, and fork-PR safety.", + "whenToUse": "Wiring or reviewing GitHub Actions jobs that authenticate to Azure with OIDC (Microsoft Entra federated identity credentials) instead of long-lived client secrets \u2014 including subject-claim strategy, immutable sub migration, RBAC, and fork-PR safety.", "tools": [ "copilot", "claude-code", @@ -368,12 +368,12 @@ "ci" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/gha-oidc-azure.instructions.md` with applyTo `**/.github/workflows/*.{yml,yaml}` and any reusable workflow that calls `azure/login`. Claude Code: `.claude/skills/gha-oidc-azure-guardrails/SKILL.md` (plus a one-line CLAUDE.md fact that Azure deploy jobs use OIDC + least-privilege FIC subjects, never client secrets in git). Codex: a GitHub Actions / Azure OIDC section in root `AGENTS.md` or `.github/AGENTS.md` covering permissions, FIC subjects, and immutable sub migration.", - "body": "# Skill: GitHub Actions OIDC Azure Login Guardrails\n\n## Goal\nAuthenticate GitHub Actions jobs to Azure with short-lived tokens via OIDC federated identity credentials (FIC), scoped subjects, least-privilege RBAC, and safe workflow permissions — without long-lived `AZURE_CLIENT_SECRET` values in GitHub secrets.\n\n## When to apply\n- Adding or changing deploy/infra jobs that call `azure/login`, `az`, Terraform, Bicep, or Azure CLI against subscriptions\n- Migrating from service-principal client secrets or stored PATs to OIDC\n- Configuring Entra app registrations or user-assigned managed identities with FIC for GitHub's OIDC issuer\n- Reviews mentioning broad `sub` patterns, missing `id-token: write`, or fork PR workflows with cloud access\n- 2026 immutable OIDC subject-claim work (name-based `sub` recycling on rename/transfer)\n\n## Baseline rules\n1. **Prefer OIDC over long-lived secrets.** Use federated credentials so GitHub mints a job-scoped ID token Entra trusts. Do not keep `AZURE_CLIENT_SECRET` \"just in case\" after OIDC works.\n2. **Use official login action with explicit IDs.** `azure/login@v2` (or current verified release) with `client-id`, `tenant-id`, and `subscription-id` from GitHub **variables** or environment configuration — not hardcoded in public forks. Pin the action to a full commit SHA or a verified tag your repo already uses.\n3. **Grant `id-token: write` only where needed.** Set workflow default `permissions` to `contents: read` (and other read scopes as required). Add `permissions:\n id-token: write` (plus deploy scopes) on the **job** that logs into Azure — avoid repo-wide wildcard escalation if a narrower reusable workflow can own the token.\n4. **Pick the tightest FIC subject strategy.** Entra FIC `subject` must match GitHub's OIDC `sub` for that job context. Common patterns (least privilege first when they fit):\n - **Environment:** `repo:ORG/REPO:environment:NAME` — pair with GitHub Environments, required reviewers, and deployment branches for production.\n - **Ref (branch/tag):** `repo:ORG/REPO:ref:refs/heads/main` or tag ref — good for branch-locked promotion.\n - **Job workflow ref:** `repo:ORG/REPO:ref:refs/heads/main:workflow:FILE:job:JOB` — narrows to one workflow job; use when multiple jobs share a branch but only one may touch Azure.\n Avoid `repo:ORG/REPO:*` or other catch-all subjects that let any workflow job in the repo authenticate.\n5. **Audience defaults.** Use Entra's default federated audience `api://AzureADTokenExchange` unless every layer (FIC, token exchange, custom middleware) is deliberately configured for a custom `aud`. Mismatched audience is a common \"login works in one pipeline only\" failure.\n6. **2026 immutable subject claims.** GitHub can emit **name-based** subjects that embed `ORG/REPO` strings. Those strings can be **reused** after rename, transfer, or org restructuring — a recycled name must not inherit old FIC trust. **Prefer or migrate to immutable subjects** that bind to stable numeric IDs (repository and owner identifiers in the claim shape GitHub documents for your account tier). Migration playbook without downtime:\n - Add a **second** FIC with the immutable subject (keep the existing name-based FIC).\n - Run representative workflows; confirm Entra accepts the new `sub` and Azure RBAC still resolves.\n - Remove the name-based FIC after soak.\n Where supported, use **Flexible FIC** or supplemental claim checks (`repository_id`, `repository_owner_id`, etc.) as defense in depth so trust does not depend on display names alone.\n7. **RBAC on the Azure identity.** Grant only roles required for the pipeline task — e.g. `AcrPush` on a registry, `Key Vault Secrets User` on one vault, `Contributor` scoped to a resource group. Avoid `Owner` / `User Access Administrator` at subscription scope for CI. Separate identities per environment when blast radius differs.\n8. **Pin actions; protect tokens.** Pin third-party actions by SHA; do not `echo` ID tokens, `AZURE_*` env dumps, or `::debug::` secrets. Disable verbose logging on login steps in shared workflows.\n9. **Fork PR safety.** `pull_request` from forks must not receive `id-token: write` with cloud deploy secrets or environments that grant Azure. Use `pull_request_target` only under org-approved patterns; default to \"OIDC jobs run on `push` / `workflow_dispatch` / internal PRs only\".\n10. **Issuer validation stays on.** Entra FIC issuer must be `https://token.actions.githubusercontent.com` (GitHub's OIDC issuer). Do not disable issuer or audience validation in custom scripts that exchange tokens manually.\n\n## Workflow\n1. Inventory existing workflows under `.github/workflows` for `azure/login`, `AZURE_CLIENT_SECRET`, or `credentials: ${{ secrets.*}}` patterns.\n2. Choose identity type: app registration service principal vs user-assigned managed identity (UAMI) — match what platform team supports for FIC.\n3. Design FIC subjects per environment/job; document {{ORG}}, {{REPO}}, environment names, and branch refs in runbooks (not secrets).\n4. Author workflow: job-level `permissions`, pinned `azure/login`, subsequent `az`/IaC steps using OIDC session only.\n5. Assign Azure RBAC on the identity; remove unused secret-based login paths.\n6. If migrating immutable `sub`: dual-FIC → validate → retire name-based FIC.\n7. PR notes: subject strategy, roles granted, fork policy, and verification evidence.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/gha-oidc-azure.instructions.md` with `applyTo` for workflow YAML.\n- Always-on line: Azure jobs use OIDC + FIC; never add client secrets to git.\n- Extend existing deploy workflows; do not duplicate a secret-based login path.\n\n### Claude Code\n- Procedure in `.claude/skills/gha-oidc-azure-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Azure deploy from Actions uses OIDC (`id-token: write` on the deploy job only) and least-privilege FIC subjects.\"\n- Before claiming done, walk through subject match checklist and fork PR denial reasoning.\n\n### Codex\n- `AGENTS.md` CI/OIDC section: permissions model, FIC subject patterns, immutable sub migration, no secrets in YAML.\n- Link to this skill if root AGENTS.md would bloat.\n\n## Anti-patterns\n- Storing `AZURE_CLIENT_SECRET` alongside OIDC \"for rollback\"\n- FIC subject `repo:ORG/REPO:*` or environment `*` shared by prod and dev\n- Same Entra app + FIC for every environment and every repo in the org\n- Granting subscription `Owner` to a CI service principal\n- `permissions: write-all` or top-level `id-token: write` on every job including fork PR builds\n- Logging OIDC ID tokens or `ACTIONS_ID_TOKEN_REQUEST_TOKEN` output\n- Disabling issuer validation in custom token-exchange scripts\n- Relying solely on name-based `sub` after repo transfer without re-auditing FIC trust\n- Unpinned `azure/login@main` or other floating action refs\n\n## Verification checklist\n- [ ] Only deploy/login jobs have `id-token: write`; default permissions are read-mostly\n- [ ] FIC issuer is GitHub Actions OIDC; audience matches token exchange expectations\n- [ ] FIC `subject` equals the `sub` for the intended ref/environment/workflow job (document the expected string)\n- [ ] `azure/login` succeeds on allowed branch/environment; **fails** on wrong ref or unapproved environment\n- [ ] No `AZURE_CLIENT_SECRET` in GitHub secrets for this path (or tracked deprecation issue)\n- [ ] Fork `pull_request` workflows cannot reach OIDC + protected environment deploy\n- [ ] Action SHAs pinned; login steps do not echo tokens\n- [ ] Azure roles scoped to required resources only (list role + scope in PR)\n- [ ] If immutable sub migration: dual FIC tested before removing legacy FIC\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: gha-oidc-azure-guardrails\ndescription: Use when wiring GitHub Actions OIDC login to Azure/Entra — FIC subjects, id-token permissions, immutable sub migration, RBAC, fork PR safety. Prefer OIDC over client secrets.\n---\n\nFollow GitHub Actions OIDC Azure Login Guardrails: job-scoped id-token, least-privilege FIC subjects, pinned azure/login, no secrets in git, verify wrong-ref failures.\n```\n" + "body": "# Skill: GitHub Actions OIDC Azure Login Guardrails\n\n## Goal\nAuthenticate GitHub Actions jobs to Azure with short-lived tokens via OIDC federated identity credentials (FIC), scoped subjects, least-privilege RBAC, and safe workflow permissions \u2014 without long-lived `AZURE_CLIENT_SECRET` values in GitHub secrets.\n\n## When to apply\n- Adding or changing deploy/infra jobs that call `azure/login`, `az`, Terraform, Bicep, or Azure CLI against subscriptions\n- Migrating from service-principal client secrets or stored PATs to OIDC\n- Configuring Entra app registrations or user-assigned managed identities with FIC for GitHub's OIDC issuer\n- Reviews mentioning broad `sub` patterns, missing `id-token: write`, or fork PR workflows with cloud access\n- 2026 immutable OIDC subject-claim work (name-based `sub` recycling on rename/transfer)\n\n## Baseline rules\n1. **Prefer OIDC over long-lived secrets.** Use federated credentials so GitHub mints a job-scoped ID token Entra trusts. Do not keep `AZURE_CLIENT_SECRET` \"just in case\" after OIDC works.\n2. **Use official login action with explicit IDs.** `azure/login@v2` (or current verified release) with `client-id`, `tenant-id`, and `subscription-id` from GitHub **variables** or environment configuration \u2014 not hardcoded in public forks. Pin the action to a full commit SHA or a verified tag your repo already uses.\n3. **Grant `id-token: write` only where needed.** Set workflow default `permissions` to `contents: read` (and other read scopes as required). Add `permissions:\n id-token: write` (plus deploy scopes) on the **job** that logs into Azure \u2014 avoid repo-wide wildcard escalation if a narrower reusable workflow can own the token.\n4. **Pick the tightest FIC subject strategy.** Entra FIC `subject` must match GitHub's OIDC `sub` for that job context. Common patterns (least privilege first when they fit):\n - **Environment:** `repo:ORG/REPO:environment:NAME` \u2014 pair with GitHub Environments, required reviewers, and deployment branches for production.\n - **Ref (branch/tag):** `repo:ORG/REPO:ref:refs/heads/main` or tag ref \u2014 good for branch-locked promotion.\n - **Job workflow ref:** `repo:ORG/REPO:ref:refs/heads/main:workflow:FILE:job:JOB` \u2014 narrows to one workflow job; use when multiple jobs share a branch but only one may touch Azure.\n Avoid `repo:ORG/REPO:*` or other catch-all subjects that let any workflow job in the repo authenticate.\n5. **Audience defaults.** Use Entra's default federated audience `api://AzureADTokenExchange` unless every layer (FIC, token exchange, custom middleware) is deliberately configured for a custom `aud`. Mismatched audience is a common \"login works in one pipeline only\" failure.\n6. **2026 immutable subject claims.** GitHub can emit **name-based** subjects that embed `ORG/REPO` strings. Those strings can be **reused** after rename, transfer, or org restructuring \u2014 a recycled name must not inherit old FIC trust. **Prefer or migrate to immutable subjects** that bind to stable numeric IDs (repository and owner identifiers in the claim shape GitHub documents for your account tier). Migration playbook without downtime:\n - Add a **second** FIC with the immutable subject (keep the existing name-based FIC).\n - Run representative workflows; confirm Entra accepts the new `sub` and Azure RBAC still resolves.\n - Remove the name-based FIC after soak.\n Where supported, use **Flexible FIC** or supplemental claim checks (`repository_id`, `repository_owner_id`, etc.) as defense in depth so trust does not depend on display names alone.\n7. **RBAC on the Azure identity.** Grant only roles required for the pipeline task \u2014 e.g. `AcrPush` on a registry, `Key Vault Secrets User` on one vault, `Contributor` scoped to a resource group. Avoid `Owner` / `User Access Administrator` at subscription scope for CI. Separate identities per environment when blast radius differs.\n8. **Pin actions; protect tokens.** Pin third-party actions by SHA; do not `echo` ID tokens, `AZURE_*` env dumps, or `::debug::` secrets. Disable verbose logging on login steps in shared workflows.\n9. **Fork PR safety.** `pull_request` from forks must not receive `id-token: write` with cloud deploy secrets or environments that grant Azure. Use `pull_request_target` only under org-approved patterns; default to \"OIDC jobs run on `push` / `workflow_dispatch` / internal PRs only\".\n10. **Issuer validation stays on.** Entra FIC issuer must be `https://token.actions.githubusercontent.com` (GitHub's OIDC issuer). Do not disable issuer or audience validation in custom scripts that exchange tokens manually.\n\n## Workflow\n1. Inventory existing workflows under `.github/workflows` for `azure/login`, `AZURE_CLIENT_SECRET`, or `credentials: ${{ secrets.*}}` patterns.\n2. Choose identity type: app registration service principal vs user-assigned managed identity (UAMI) \u2014 match what platform team supports for FIC.\n3. Design FIC subjects per environment/job; document {{ORG}}, {{REPO}}, environment names, and branch refs in runbooks (not secrets).\n4. Author workflow: job-level `permissions`, pinned `azure/login`, subsequent `az`/IaC steps using OIDC session only.\n5. Assign Azure RBAC on the identity; remove unused secret-based login paths.\n6. If migrating immutable `sub`: dual-FIC \u2192 validate \u2192 retire name-based FIC.\n7. PR notes: subject strategy, roles granted, fork policy, and verification evidence.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/gha-oidc-azure.instructions.md` with `applyTo` for workflow YAML.\n- Always-on line: Azure jobs use OIDC + FIC; never add client secrets to git.\n- Extend existing deploy workflows; do not duplicate a secret-based login path.\n\n### Claude Code\n- Procedure in `.claude/skills/gha-oidc-azure-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Azure deploy from Actions uses OIDC (`id-token: write` on the deploy job only) and least-privilege FIC subjects.\"\n- Before claiming done, walk through subject match checklist and fork PR denial reasoning.\n\n### Codex\n- `AGENTS.md` CI/OIDC section: permissions model, FIC subject patterns, immutable sub migration, no secrets in YAML.\n- Link to this skill if root AGENTS.md would bloat.\n\n## Anti-patterns\n- Storing `AZURE_CLIENT_SECRET` alongside OIDC \"for rollback\"\n- FIC subject `repo:ORG/REPO:*` or environment `*` shared by prod and dev\n- Same Entra app + FIC for every environment and every repo in the org\n- Granting subscription `Owner` to a CI service principal\n- `permissions: write-all` or top-level `id-token: write` on every job including fork PR builds\n- Logging OIDC ID tokens or `ACTIONS_ID_TOKEN_REQUEST_TOKEN` output\n- Disabling issuer validation in custom token-exchange scripts\n- Relying solely on name-based `sub` after repo transfer without re-auditing FIC trust\n- Unpinned `azure/login@main` or other floating action refs\n\n## Verification checklist\n- [ ] Only deploy/login jobs have `id-token: write`; default permissions are read-mostly\n- [ ] FIC issuer is GitHub Actions OIDC; audience matches token exchange expectations\n- [ ] FIC `subject` equals the `sub` for the intended ref/environment/workflow job (document the expected string)\n- [ ] `azure/login` succeeds on allowed branch/environment; **fails** on wrong ref or unapproved environment\n- [ ] No `AZURE_CLIENT_SECRET` in GitHub secrets for this path (or tracked deprecation issue)\n- [ ] Fork `pull_request` workflows cannot reach OIDC + protected environment deploy\n- [ ] Action SHAs pinned; login steps do not echo tokens\n- [ ] Azure roles scoped to required resources only (list role + scope in PR)\n- [ ] If immutable sub migration: dual FIC tested before removing legacy FIC\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: gha-oidc-azure-guardrails\ndescription: Use when wiring GitHub Actions OIDC login to Azure/Entra \u2014 FIC subjects, id-token permissions, immutable sub migration, RBAC, fork PR safety. Prefer OIDC over client secrets.\n---\n\nFollow GitHub Actions OIDC Azure Login Guardrails: job-scoped id-token, least-privilege FIC subjects, pinned azure/login, no secrets in git, verify wrong-ref failures.\n```\n" }, { "id": "spring-data-jpa-query-guardrails", "title": "Spring Data JPA Query Guardrails", - "whenToUse": "Designing, reviewing, or refactoring Spring Data JPA repositories, entity mappings, and service-layer query usage — especially list/detail endpoints, reports, or any path where N+1, over-fetch, or unsafe @Query patterns may appear.", + "whenToUse": "Designing, reviewing, or refactoring Spring Data JPA repositories, entity mappings, and service-layer query usage \u2014 especially list/detail endpoints, reports, or any path where N+1, over-fetch, or unsafe @Query patterns may appear.", "tools": [ "copilot", "claude-code", @@ -388,12 +388,12 @@ "hibernate" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-data-jpa-query.instructions.md` with applyTo for `**/repository/**/*.java`, `**/entity/**/*.java`, `**/*Repository.java`, and persistence YAML. Claude Code: `.claude/skills/spring-data-jpa-query-guardrails/SKILL.md` plus a one-line CLAUDE.md fact on lazy-by-default and no collection fetch+Pageable. Codex: `AGENTS.md` persistence section or linked `docs/agents/spring-data-jpa.md`.", - "body": "# Skill: Spring Data JPA Query Guardrails\n\n## Goal\nShip Spring Data JPA access that is correct, lean, and predictable under production data volumes — no accidental N+1, no in-memory pagination traps, no entity leakage at API boundaries, and query plans that match indexes and use cases.\n\n## When to apply\n- New or changed `JpaRepository` / `@Query` / Specifications / Criteria\n- Entity mapping changes (`@OneToMany`, `@ManyToOne`, embeddables, soft-delete filters)\n- List/detail REST or batch jobs that traverse associations\n- Reviews mentioning slow endpoints, high DB CPU, `HHH90003004`, LazyInitializationException, or cartesian explosions\n- Migrations that add columns/indexes used by hot queries (pair with Flyway guardrails when schema changes)\n\n## Baseline rules\n1. **Associations lazy by default.** Map `@ManyToOne` / `@OneToOne` / collections as `FetchType.LAZY`. Override EAGER defaults explicitly. Opt into loading per use case with fetch joins, `@EntityGraph`, or batch fetch — never by leaving EAGER on the mapping.\n2. **Kill N+1 deliberately.** Prefer `@EntityGraph(attributePaths = …)` or JPQL `JOIN FETCH` for associations you always need on that path. For list views with collections, prefer `@BatchSize` / `hibernate.default_batch_fetch_size` or a two-step ID query over silent per-row selects. Assert a query budget in tests (statement count or datasource proxy) for hot paths.\n3. **Never combine collection `JOIN FETCH` with `Pageable`.** Hibernate warns (`HHH90003004`) and paginates in memory. Use: (a) page entity IDs first, then `JOIN FETCH` / entity graph for those IDs; or (b) `@EntityGraph` / batch fetch without collection fetch join on the paged query; or (c) DTO projection that does not inflate rows.\n4. **Projections for reads.** Closed interface or class-based DTO projections (constructor expressions / `@SqlResultSetMapping` when needed) for list and report endpoints. Do not return managed entities (or open SpEL projections that force full entity load) from public APIs.\n5. **`@Query` safety.** Prefer parameterized JPQL/SQL (`:name` / `?1`) — never string-concatenated user input. For modifying queries use `@Modifying(clearAutomatically = true, flushAutomatically = true)` and call from a transactional service. Document native SQL dialect assumptions. Avoid `SELECT *` entity natives that skip the persistence context contract unless reviewed.\n6. **Transactional boundaries.** Read paths: `@Transactional(readOnly = true)` on the service method that owns the session through mapping. Do not touch lazy collections in controllers after the session closes — map to DTOs inside the transaction or use Open-in-view only if the project already standardizes it (prefer off + explicit fetch). Write paths: one clear transactional service method; no repository calls from controllers that start implicit transactions inconsistently.\n7. **Pagination contracts.** Always pass `Pageable` (or keyset/`Slice` when appropriate) for unbounded lists. Cap `size` at the API layer. Prefer `Slice` when total count is expensive and not required. Sort only on whitelisted properties.\n8. **Indexing and explain awareness.** For every new filter/sort/join used in production paths, confirm a supporting index exists or is added in the same change set. Mentally (or via `EXPLAIN`) check selectivity; avoid leading-wildcard `LIKE` and functions on indexed columns in hot queries.\n9. **Soft-delete and filters.** If using `@SQLRestriction` / `@Where` / `@SoftDelete`, ensure count queries, unique constraints, and admin “include deleted” paths are intentional. Soft-delete + unique natural keys need partial unique indexes or equivalent.\n10. **Batching writes.** For bulk inserts/updates, enable JDBC batching (`hibernate.jdbc.batch_size`, order inserts/updates) and avoid flush-per-entity loops. Prefer set-based `@Modifying` queries for mass updates when entity lifecycle listeners are not required.\n11. **One collection fetch at a time.** Fetching two bag collections in one query causes cartesian products. Split queries or use batch fetch for the second collection.\n12. **Equals/hashCode discipline.** Do not use mutable fields or lazy associations in `equals`/`hashCode` for entities; prefer business keys carefully or ID-after-persist patterns already used in-repo.\n\n## Workflow\n1. Inventory repositories, entity graphs, and call sites for the feature (list vs detail vs write).\n2. Decide fetch strategy per use case: projection vs entity graph vs fetch join vs batch size.\n3. Author or adjust repository methods; keep derived query names honest; add `@EntityGraph` / `@Query` only when needed.\n4. Ensure service transaction + DTO mapping; no entity JSON serialization of lazy graphs.\n5. Add/adjust indexes with schema migration if filters changed.\n6. Add characterization or slice tests: correct results + query-count ceiling on the hot path.\n7. PR notes: fetch strategy, pagination approach, index changes, residual N+1 risk.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-data-jpa-query.instructions.md` with `applyTo` for repositories, entities, and persistence config.\n- Always-on: lazy associations; no collection JOIN FETCH + Pageable; DTOs at API boundary.\n- Extend existing repository patterns; do not introduce a second persistence style without cause.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-data-jpa-query-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"JPA associations are LAZY; list endpoints use projections or two-step ID fetch — never collection fetch join with Pageable.\"\n- Before claiming done, show SQL (log or test) and confirm query count for the list path.\n\n### Codex\n- `AGENTS.md` persistence section: N+1 rules, pagination trap, projection preference, `@Query` parameterization.\n- Link to this skill when root AGENTS.md would bloat.\n\n## Anti-patterns\n- `FetchType.EAGER` on `@ManyToOne` “for convenience”\n- Collection `JOIN FETCH` + `Pageable` on the same repository method\n- Returning JPA entities from REST controllers (especially with open-in-view papering over LazyInitializationException)\n- Open SpEL interface projections that load full entities\n- String-concatenated native SQL or JPQL from request parameters\n- `findAll()` without pagination on user-facing APIs\n- Touching lazy collections in `@Async` / event listeners after the session ended\n- Dual bag `JOIN FETCH` in one query (cartesian blow-up)\n- Relying on `spring.jpa.open-in-view=true` as the fetch strategy\n- Missing indexes for new WHERE/ORDER BY on hot paths\n- Soft-delete filters that break unique constraints or admin undelete without a plan\n\n## Verification checklist\n- [ ] Associations are LAZY unless a documented exception exists\n- [ ] Hot list path has no N+1 (query budget test or logged SQL review)\n- [ ] No collection fetch join combined with Pageable\n- [ ] API responses use DTOs/projections, not raw entities\n- [ ] All `@Query` / native SQL uses bind parameters\n- [ ] Read service methods are `readOnly` transactional where appropriate\n- [ ] Page/Slice size capped; sorts whitelisted\n- [ ] Indexes cover new filter/sort columns (migration linked)\n- [ ] Soft-delete behavior verified for counts and uniqueness\n- [ ] Bulk paths use batching or set-based updates when applicable\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-data-jpa-query-guardrails\ndescription: Use when designing or reviewing Spring Data JPA repositories and entity fetch plans — N+1, entity graphs vs fetch joins, pagination traps, DTO projections, @Query safety, transactions, indexing.\n---\n\nFollow Spring Data JPA Query Guardrails: LAZY associations, deliberate fetch plans, no collection JOIN FETCH with Pageable, DTOs at the API boundary, parameterized queries, verify SQL and query counts on hot paths.\n```\n" + "body": "# Skill: Spring Data JPA Query Guardrails\n\n## Goal\nShip Spring Data JPA access that is correct, lean, and predictable under production data volumes \u2014 no accidental N+1, no in-memory pagination traps, no entity leakage at API boundaries, and query plans that match indexes and use cases.\n\n## When to apply\n- New or changed `JpaRepository` / `@Query` / Specifications / Criteria\n- Entity mapping changes (`@OneToMany`, `@ManyToOne`, embeddables, soft-delete filters)\n- List/detail REST or batch jobs that traverse associations\n- Reviews mentioning slow endpoints, high DB CPU, `HHH90003004`, LazyInitializationException, or cartesian explosions\n- Migrations that add columns/indexes used by hot queries (pair with Flyway guardrails when schema changes)\n\n## Baseline rules\n1. **Associations lazy by default.** Map `@ManyToOne` / `@OneToOne` / collections as `FetchType.LAZY`. Override EAGER defaults explicitly. Opt into loading per use case with fetch joins, `@EntityGraph`, or batch fetch \u2014 never by leaving EAGER on the mapping.\n2. **Kill N+1 deliberately.** Prefer `@EntityGraph(attributePaths = \u2026)` or JPQL `JOIN FETCH` for associations you always need on that path. For list views with collections, prefer `@BatchSize` / `hibernate.default_batch_fetch_size` or a two-step ID query over silent per-row selects. Assert a query budget in tests (statement count or datasource proxy) for hot paths.\n3. **Never combine collection `JOIN FETCH` with `Pageable`.** Hibernate warns (`HHH90003004`) and paginates in memory. Use: (a) page entity IDs first, then `JOIN FETCH` / entity graph for those IDs; or (b) `@EntityGraph` / batch fetch without collection fetch join on the paged query; or (c) DTO projection that does not inflate rows.\n4. **Projections for reads.** Closed interface or class-based DTO projections (constructor expressions / `@SqlResultSetMapping` when needed) for list and report endpoints. Do not return managed entities (or open SpEL projections that force full entity load) from public APIs.\n5. **`@Query` safety.** Prefer parameterized JPQL/SQL (`:name` / `?1`) \u2014 never string-concatenated user input. For modifying queries use `@Modifying(clearAutomatically = true, flushAutomatically = true)` and call from a transactional service. Document native SQL dialect assumptions. Avoid `SELECT *` entity natives that skip the persistence context contract unless reviewed.\n6. **Transactional boundaries.** Read paths: `@Transactional(readOnly = true)` on the service method that owns the session through mapping. Do not touch lazy collections in controllers after the session closes \u2014 map to DTOs inside the transaction or use Open-in-view only if the project already standardizes it (prefer off + explicit fetch). Write paths: one clear transactional service method; no repository calls from controllers that start implicit transactions inconsistently.\n7. **Pagination contracts.** Always pass `Pageable` (or keyset/`Slice` when appropriate) for unbounded lists. Cap `size` at the API layer. Prefer `Slice` when total count is expensive and not required. Sort only on whitelisted properties.\n8. **Indexing and explain awareness.** For every new filter/sort/join used in production paths, confirm a supporting index exists or is added in the same change set. Mentally (or via `EXPLAIN`) check selectivity; avoid leading-wildcard `LIKE` and functions on indexed columns in hot queries.\n9. **Soft-delete and filters.** If using `@SQLRestriction` / `@Where` / `@SoftDelete`, ensure count queries, unique constraints, and admin \u201cinclude deleted\u201d paths are intentional. Soft-delete + unique natural keys need partial unique indexes or equivalent.\n10. **Batching writes.** For bulk inserts/updates, enable JDBC batching (`hibernate.jdbc.batch_size`, order inserts/updates) and avoid flush-per-entity loops. Prefer set-based `@Modifying` queries for mass updates when entity lifecycle listeners are not required.\n11. **One collection fetch at a time.** Fetching two bag collections in one query causes cartesian products. Split queries or use batch fetch for the second collection.\n12. **Equals/hashCode discipline.** Do not use mutable fields or lazy associations in `equals`/`hashCode` for entities; prefer business keys carefully or ID-after-persist patterns already used in-repo.\n\n## Workflow\n1. Inventory repositories, entity graphs, and call sites for the feature (list vs detail vs write).\n2. Decide fetch strategy per use case: projection vs entity graph vs fetch join vs batch size.\n3. Author or adjust repository methods; keep derived query names honest; add `@EntityGraph` / `@Query` only when needed.\n4. Ensure service transaction + DTO mapping; no entity JSON serialization of lazy graphs.\n5. Add/adjust indexes with schema migration if filters changed.\n6. Add characterization or slice tests: correct results + query-count ceiling on the hot path.\n7. PR notes: fetch strategy, pagination approach, index changes, residual N+1 risk.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-data-jpa-query.instructions.md` with `applyTo` for repositories, entities, and persistence config.\n- Always-on: lazy associations; no collection JOIN FETCH + Pageable; DTOs at API boundary.\n- Extend existing repository patterns; do not introduce a second persistence style without cause.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-data-jpa-query-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"JPA associations are LAZY; list endpoints use projections or two-step ID fetch \u2014 never collection fetch join with Pageable.\"\n- Before claiming done, show SQL (log or test) and confirm query count for the list path.\n\n### Codex\n- `AGENTS.md` persistence section: N+1 rules, pagination trap, projection preference, `@Query` parameterization.\n- Link to this skill when root AGENTS.md would bloat.\n\n## Anti-patterns\n- `FetchType.EAGER` on `@ManyToOne` \u201cfor convenience\u201d\n- Collection `JOIN FETCH` + `Pageable` on the same repository method\n- Returning JPA entities from REST controllers (especially with open-in-view papering over LazyInitializationException)\n- Open SpEL interface projections that load full entities\n- String-concatenated native SQL or JPQL from request parameters\n- `findAll()` without pagination on user-facing APIs\n- Touching lazy collections in `@Async` / event listeners after the session ended\n- Dual bag `JOIN FETCH` in one query (cartesian blow-up)\n- Relying on `spring.jpa.open-in-view=true` as the fetch strategy\n- Missing indexes for new WHERE/ORDER BY on hot paths\n- Soft-delete filters that break unique constraints or admin undelete without a plan\n\n## Verification checklist\n- [ ] Associations are LAZY unless a documented exception exists\n- [ ] Hot list path has no N+1 (query budget test or logged SQL review)\n- [ ] No collection fetch join combined with Pageable\n- [ ] API responses use DTOs/projections, not raw entities\n- [ ] All `@Query` / native SQL uses bind parameters\n- [ ] Read service methods are `readOnly` transactional where appropriate\n- [ ] Page/Slice size capped; sorts whitelisted\n- [ ] Indexes cover new filter/sort columns (migration linked)\n- [ ] Soft-delete behavior verified for counts and uniqueness\n- [ ] Bulk paths use batching or set-based updates when applicable\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-data-jpa-query-guardrails\ndescription: Use when designing or reviewing Spring Data JPA repositories and entity fetch plans \u2014 N+1, entity graphs vs fetch joins, pagination traps, DTO projections, @Query safety, transactions, indexing.\n---\n\nFollow Spring Data JPA Query Guardrails: LAZY associations, deliberate fetch plans, no collection JOIN FETCH with Pageable, DTOs at the API boundary, parameterized queries, verify SQL and query counts on hot paths.\n```\n" }, { "id": "spring-boot-cache-redis-guardrails", "title": "Spring Boot Cache Redis Guardrails", - "whenToUse": "Designing, reviewing, or hardening Spring Cache with Redis (or Azure Cache for Redis) — TTL, serializers, key prefixes, eviction, stampede, multi-instance correctness.", + "whenToUse": "Designing, reviewing, or hardening Spring Cache with Redis (or Azure Cache for Redis) \u2014 TTL, serializers, key prefixes, eviction, stampede, multi-instance correctness.", "tools": [ "copilot", "claude-code", @@ -408,12 +408,12 @@ "azure" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-boot-cache-redis.instructions.md` with applyTo for cache `@Configuration`, `application*.{yml,yaml,properties}`, and types that use `@Cacheable`, `@CacheEvict`, or `@CachePut`. Claude Code: `.claude/skills/spring-boot-cache-redis-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that Redis cache entries always have a TTL and `@EnableCaching` stays off the application class. Codex: a cache section in root `AGENTS.md` or linked `docs/agents/spring-boot-cache-redis.md`.", - "body": "# Skill: Spring Boot Cache Redis Guardrails\n\n## Goal\nShip Spring Cache on Redis (including Azure Cache for Redis) that expires on purpose, serializes safely, isolates keys per app and environment, and stays correct when more than one pod is running.\n\n## When to apply\n- Enabling `spring-boot-starter-cache` with Redis, or reviewing an existing `CacheManager`\n- Adding or changing `@Cacheable`, `@CacheEvict`, or `@CachePut`\n- Incidents with stale data, unbounded Redis memory, stampedes, or cross-pod inconsistency\n- Moving a local or container Redis onto Azure Cache for Redis\n- Hardening serializers, key names, or bulk eviction before production\n\n## Baseline rules\n1. **Select Redis explicitly and keep caching off slice tests.** Depend on `spring-boot-starter-cache` and `spring-boot-starter-data-redis` (Lettuce unless the build already chose Jedis). Set `spring.cache.type=redis`. Do not assume \"Redis on the classpath\" picks the right manager when another provider is present. Put `@EnableCaching` on a dedicated `@Configuration` (for example `RedisCacheConfig`), not on `@SpringBootApplication`. `@WebMvcTest` and `@DataJpaTest` load the application class; they do not component-scan an arbitrary `@Configuration`. Leaving `@EnableCaching` on the application class pulls cache advice and a connection into slices that should stay light.\n2. **Every cache has a TTL.** `RedisCacheConfiguration` defaults to `Duration.ZERO`, which means entries never expire. That grows memory without bound and, on a server policy of `noeviction`, turns a full cache into write errors. Set a global floor with `spring.cache.redis.time-to-live`. Prefer per-cache TTL through a `RedisCacheManagerBuilderCustomizer` that calls `withCacheConfiguration` and `entryTtl`. Start from the auto-configured `RedisCacheConfiguration` bean so prefix, null policy, and serializer stay intact. Do not replace `CacheManager` with a hand-built bean, and do not declare your own `RedisCacheConfiguration` `@Bean`, unless you re-apply `CacheProperties` yourself. Both bypasses drop Boot's `spring.cache.redis.*` binding (`@ConditionalOnMissingBean`).\n3. **JSON values, string keys, explicit types.** Boot's default value serializer is JDK serialization: opaque bytes, brittle across class moves, and awkward to inspect. Prefer a typed `Jackson2JsonRedisSerializer` when a cache stores one concrete DTO. Use `GenericJackson2JsonRedisSerializer` only with an `ObjectMapper` whose polymorphic validator allowlists those DTOs. Permissive default typing (`@class` plus a laissez-faire subtype validator) is a deserialization risk if anything besides this app can write the keyspace. Document the allowlist. Serialize keys with a string serializer so prefixes and ids stay readable. Do not cache JPA entities, credentials, or types outside the allowlist.\n4. **Prefix and namespace every key.** Leave `spring.cache.redis.use-key-prefix=true` (the default). Turning it off lets two cache names share one Redis key. Set `spring.cache.redis.key-prefix` to application name, environment, and a schema version (`orders:prod:v3:`). Shared Azure instances must not mix apps or environments. Use stable SpEL (`key = \"#id\"`) that you repeat on evict and put. The default key generator hashes every argument, so `Pageable`, principals, and `toString()` of entities become huge or sensitive keys. Never put secrets, tokens, passwords, emails, national ids, or other raw PII in keys or values. Keys show up in `SCAN`, slow logs, and Azure diagnostics.\n5. **Evict one key. Do not `KEYS` the instance.** Prefer `@CacheEvict` / `@CachePut` with the same key the read path uses. `allEntries = true` and `Cache.clear()` walk the keyspace. `RedisCacheManager.builder(connectionFactory)` uses a non-locking writer whose batch strategy is `KEYS` in current Spring Data Redis. `KEYS` is blocking and is a poor fit for a large Azure keyspace. For a real bulk drop, either configure `RedisCacheWriter` with `BatchStrategies.scan(batchSize)` (still expensive, non-atomic, per node on cluster) or bump the version segment of the key prefix and let TTL reap the old generation. Do not call `FLUSHDB` or `FLUSHALL` from application code.\n6. **Decide nulls, then decide stampede.** Default `spring.cache.redis.cache-null-values=true` stores nulls for the full TTL (forever, if TTL was left at zero). Pick one policy: `unless = \"#result == null\"` and disable null caching, or a dedicated short-TTL cache for negative lookups. `disableCachingNullValues()` without `unless` throws when a method returns null, because the cache still attempts the put. `condition` runs before invocation (skip lookup and store). `unless` runs after (the method always runs; the result might not be stored), so it does not stop a stampede. `@Cacheable(sync = true)` locks inside one JVM only. Boot's writer is non-locking, so it is not cross-pod single-flight. If you add a Redis lock, document the lock key, the lock TTL, and the outcome when the holder dies (callers fall through to the database, or they fail).\n7. **Write the system of record, then the cache.** Keep the default `beforeInvocation = false` so evict/put runs after a successful method. Evicting first lets a concurrent reader reload the pre-write row and pin it until TTL. `transactionAware()` on the manager builder defers put/evict until after commit. Boot does not enable it. Turn it on only when a rolled-back transaction must not change the cache. Same-transaction reads will not see the deferred write, and a crash after commit but before the sync leaves stale data until TTL. Assume every pod shares one Redis. A process-local cache (Caffeine) is not coherent across pods. Do not add a near cache unless invalidation is designed and tested. `sync = true` does not coordinate pods.\n8. **Choose fail-open or fail-closed on purpose.** Set `spring.data.redis.timeout` below the caller's timeout so a stuck command does not pin the worker pool. Lettuce pooling needs `commons-pool2` and `spring.data.redis.lettuce.pool.*` (including `max-wait`); an unbounded wait hides the outage. The default `SimpleCacheErrorHandler` rethrows, so a Redis miss-path error fails the request even when the database could answer. That is fail-closed. For fail-open reads, a `CacheErrorHandler` that logs `handleCacheGetError` and does not rethrow lets the interceptor run the method. Swallowing put/evict errors hides a failed invalidation until TTL. Read-mostly catalogs can fail open. Authorization and idempotency keys should fail closed. When Actuator is on the classpath, Redis health is available; do not publish health details on the public port. Use a remote cache when pods must observe the same eviction. Use a local cache when per-pod staleness is acceptable and a Redis outage must not matter.\n9. **Test without a live Redis, then test the hot path with one.** Unit and slice tests should not open a socket. With `@EnableCaching` isolated, `@WebMvcTest` does not cache. Where a slice needs the abstraction, use `@AutoConfigureCache` or `spring.cache.type=none` and assert outcomes, not Redis bytes. For integration of hit, miss, eviction, and null policy, use Testcontainers with a pinned image (for example `redis:7-alpine`), `@ServiceConnection` on Boot 3.1+, or dynamic host/port properties. Do not point CI at Azure or a shared dev cache. Include a round-trip that fails if values come back as JDK payload when JSON was required.\n10. **Azure Cache for Redis is still Redis, plus network and identity.** Enable TLS (`spring.data.redis.ssl.enabled=true`) and use the instance hostname and TLS port (commonly 6380 when non-TLS is disabled). Prefer Microsoft Entra authentication where that tier and the client stack already in the repo support short-lived data-plane tokens. Otherwise set `spring.data.redis.password` from the environment or the app's existing Key Vault reference. Never commit access keys, connection strings, or primary/secondary secrets, and do not invent secret names or resource ids. Restrict the network with the firewall or a private endpoint and private DNS; laptops use local Redis or an approved tunnel, not the production key on a public endpoint. Application TTLs still matter if the server policy is `noeviction`. Use cluster configuration only when the instance is clustered, and do not assume a multi-key command spans prefixes.\n\n## Tool placement\n- **GitHub Copilot:** path-scoped `.github/instructions/spring-boot-cache-redis.instructions.md` with `applyTo` covering the cache configuration class, `application*.{yml,yaml,properties}`, and files that declare `@Cacheable`, `@CacheEvict`, or `@CachePut`. Keep one always-on line in `.github/copilot-instructions.md`: Redis caches have a TTL, JSON values, a namespaced prefix, and no `allEntries=true` on large keyspaces.\n- **Claude Code:** procedure in `.claude/skills/spring-boot-cache-redis-guardrails/SKILL.md`. One CLAUDE.md fact: \"Spring Cache on Redis always sets a TTL via RedisCacheManagerBuilderCustomizer; @EnableCaching lives on an isolated @Configuration, not the application class.\"\n- **Codex:** a short cache section in root `AGENTS.md`, or `docs/agents/spring-boot-cache-redis.md` linked from it when the root file would grow. State TTL, serializer, prefix, eviction, and fail-open versus fail-closed.\n\n## Anti-patterns\n- `@EnableCaching` on `@SpringBootApplication`, so every slice test opens Redis\n- Leaving TTL unset and treating \"it works on my laptop\" as production-safe\n- A custom `CacheManager` or `RedisCacheConfiguration` bean that silently ignores `spring.cache.redis.*`\n- JDK-serialized values, or JSON with permissive `@class` typing on a shared cache\n- `use-key-prefix=false`, or one prefix shared by dev and prod\n- SpEL built from `toString()`, tokens, or PII\n- `@CacheEvict(allEntries = true)` as a routine invalidation on Azure-sized keyspaces\n- `disableCachingNullValues()` without `unless`, so legitimate null returns throw\n- Believing `sync = true` is a cluster-wide single-flight\n- Evicting before the database write, or assuming transaction-aware cache is on by default\n- A Caffeine near cache with no invalidation story in a multi-pod deployment\n- Fail-open put/evict on data that must not stay stale past the method return\n- CI tests aimed at a shared Redis or at Azure\n- Access keys, connection strings, or firewall exceptions committed \"just for local\"\n\n## Verification\n- [ ] `spring.cache.type=redis` and both starters are present; `@EnableCaching` is not on the application class\n- [ ] Global TTL is set, and each hot cache has an explicit TTL from `RedisCacheManagerBuilderCustomizer` derived from Boot's configuration\n- [ ] No replacement `CacheManager` / `RedisCacheConfiguration` bean drops Boot properties\n- [ ] Values are JSON with a documented type allowlist; keys are strings; prefix includes app, environment, and schema version\n- [ ] Read and evict SpEL keys match; keys and values contain no secrets or PII\n- [ ] Bulk clear is scan-based or version-bumped; `allEntries=true` is absent on large caches\n- [ ] Null policy is explicit (`unless` / `condition` / short null TTL) and does not throw on ordinary nulls\n- [ ] Cross-pod single-flight, if any, documents lock TTL and the failure mode; `sync=true` is not described as cluster-wide\n- [ ] Write-then-evict order is intact; `transactionAware` is set only if the PR explains it\n- [ ] Command timeout, pool wait, and `CacheErrorHandler` match the chosen fail-open or fail-closed mode\n- [ ] Slice tests do not need Redis; hot-path integration uses a pinned Testcontainers image\n- [ ] Azure notes name TLS, auth source (Entra or access key via env/Key Vault), and private network, with no secrets in the diff\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-cache-redis-guardrails\ndescription: Use when designing or reviewing Spring Cache on Redis or Azure Cache for Redis — TTL via RedisCacheManagerBuilderCustomizer, JSON serializers, key prefixes, eviction, stampede, and multi-pod correctness.\n---\n\nFollow Spring Boot Cache Redis Guardrails: explicit redis cache type, @EnableCaching on an isolated configuration, TTL on every cache, JSON values, namespaced prefixes, targeted eviction, and a documented fail-open or fail-closed policy.\n```\n" + "body": "# Skill: Spring Boot Cache Redis Guardrails\n\n## Goal\nShip Spring Cache on Redis (including Azure Cache for Redis) that expires on purpose, serializes safely, isolates keys per app and environment, and stays correct when more than one pod is running.\n\n## When to apply\n- Enabling `spring-boot-starter-cache` with Redis, or reviewing an existing `CacheManager`\n- Adding or changing `@Cacheable`, `@CacheEvict`, or `@CachePut`\n- Incidents with stale data, unbounded Redis memory, stampedes, or cross-pod inconsistency\n- Moving a local or container Redis onto Azure Cache for Redis\n- Hardening serializers, key names, or bulk eviction before production\n\n## Baseline rules\n1. **Select Redis explicitly and keep caching off slice tests.** Depend on `spring-boot-starter-cache` and `spring-boot-starter-data-redis` (Lettuce unless the build already chose Jedis). Set `spring.cache.type=redis`. Do not assume \"Redis on the classpath\" picks the right manager when another provider is present. Put `@EnableCaching` on a dedicated `@Configuration` (for example `RedisCacheConfig`), not on `@SpringBootApplication`. `@WebMvcTest` and `@DataJpaTest` load the application class; they do not component-scan an arbitrary `@Configuration`. Leaving `@EnableCaching` on the application class pulls cache advice and a connection into slices that should stay light.\n2. **Every cache has a TTL.** `RedisCacheConfiguration` defaults to `Duration.ZERO`, which means entries never expire. That grows memory without bound and, on a server policy of `noeviction`, turns a full cache into write errors. Set a global floor with `spring.cache.redis.time-to-live`. Prefer per-cache TTL through a `RedisCacheManagerBuilderCustomizer` that calls `withCacheConfiguration` and `entryTtl`. Start from the auto-configured `RedisCacheConfiguration` bean so prefix, null policy, and serializer stay intact. Do not replace `CacheManager` with a hand-built bean, and do not declare your own `RedisCacheConfiguration` `@Bean`, unless you re-apply `CacheProperties` yourself. Both bypasses drop Boot's `spring.cache.redis.*` binding (`@ConditionalOnMissingBean`).\n3. **JSON values, string keys, explicit types.** Boot's default value serializer is JDK serialization: opaque bytes, brittle across class moves, and awkward to inspect. Prefer a typed `Jackson2JsonRedisSerializer` when a cache stores one concrete DTO. Use `GenericJackson2JsonRedisSerializer` only with an `ObjectMapper` whose polymorphic validator allowlists those DTOs. Permissive default typing (`@class` plus a laissez-faire subtype validator) is a deserialization risk if anything besides this app can write the keyspace. Document the allowlist. Serialize keys with a string serializer so prefixes and ids stay readable. Do not cache JPA entities, credentials, or types outside the allowlist.\n4. **Prefix and namespace every key.** Leave `spring.cache.redis.use-key-prefix=true` (the default). Turning it off lets two cache names share one Redis key. Set `spring.cache.redis.key-prefix` to application name, environment, and a schema version (`orders:prod:v3:`). Shared Azure instances must not mix apps or environments. Use stable SpEL (`key = \"#id\"`) that you repeat on evict and put. The default key generator hashes every argument, so `Pageable`, principals, and `toString()` of entities become huge or sensitive keys. Never put secrets, tokens, passwords, emails, national ids, or other raw PII in keys or values. Keys show up in `SCAN`, slow logs, and Azure diagnostics.\n5. **Evict one key. Do not `KEYS` the instance.** Prefer `@CacheEvict` / `@CachePut` with the same key the read path uses. `allEntries = true` and `Cache.clear()` walk the keyspace. `RedisCacheManager.builder(connectionFactory)` uses a non-locking writer whose batch strategy is `KEYS` in current Spring Data Redis. `KEYS` is blocking and is a poor fit for a large Azure keyspace. For a real bulk drop, either configure `RedisCacheWriter` with `BatchStrategies.scan(batchSize)` (still expensive, non-atomic, per node on cluster) or bump the version segment of the key prefix and let TTL reap the old generation. Do not call `FLUSHDB` or `FLUSHALL` from application code.\n6. **Decide nulls, then decide stampede.** Default `spring.cache.redis.cache-null-values=true` stores nulls for the full TTL (forever, if TTL was left at zero). Pick one policy: `unless = \"#result == null\"` and disable null caching, or a dedicated short-TTL cache for negative lookups. `disableCachingNullValues()` without `unless` throws when a method returns null, because the cache still attempts the put. `condition` runs before invocation (skip lookup and store). `unless` runs after (the method always runs; the result might not be stored), so it does not stop a stampede. `@Cacheable(sync = true)` locks inside one JVM only. Boot's writer is non-locking, so it is not cross-pod single-flight. If you add a Redis lock, document the lock key, the lock TTL, and the outcome when the holder dies (callers fall through to the database, or they fail).\n7. **Write the system of record, then the cache.** Keep the default `beforeInvocation = false` so evict/put runs after a successful method. Evicting first lets a concurrent reader reload the pre-write row and pin it until TTL. `transactionAware()` on the manager builder defers put/evict until after commit. Boot does not enable it. Turn it on only when a rolled-back transaction must not change the cache. Same-transaction reads will not see the deferred write, and a crash after commit but before the sync leaves stale data until TTL. Assume every pod shares one Redis. A process-local cache (Caffeine) is not coherent across pods. Do not add a near cache unless invalidation is designed and tested. `sync = true` does not coordinate pods.\n8. **Choose fail-open or fail-closed on purpose.** Set `spring.data.redis.timeout` below the caller's timeout so a stuck command does not pin the worker pool. Lettuce pooling needs `commons-pool2` and `spring.data.redis.lettuce.pool.*` (including `max-wait`); an unbounded wait hides the outage. The default `SimpleCacheErrorHandler` rethrows, so a Redis miss-path error fails the request even when the database could answer. That is fail-closed. For fail-open reads, a `CacheErrorHandler` that logs `handleCacheGetError` and does not rethrow lets the interceptor run the method. Swallowing put/evict errors hides a failed invalidation until TTL. Read-mostly catalogs can fail open. Authorization and idempotency keys should fail closed. When Actuator is on the classpath, Redis health is available; do not publish health details on the public port. Use a remote cache when pods must observe the same eviction. Use a local cache when per-pod staleness is acceptable and a Redis outage must not matter.\n9. **Test without a live Redis, then test the hot path with one.** Unit and slice tests should not open a socket. With `@EnableCaching` isolated, `@WebMvcTest` does not cache. Where a slice needs the abstraction, use `@AutoConfigureCache` or `spring.cache.type=none` and assert outcomes, not Redis bytes. For integration of hit, miss, eviction, and null policy, use Testcontainers with a pinned image (for example `redis:7-alpine`), `@ServiceConnection` on Boot 3.1+, or dynamic host/port properties. Do not point CI at Azure or a shared dev cache. Include a round-trip that fails if values come back as JDK payload when JSON was required.\n10. **Azure Cache for Redis is still Redis, plus network and identity.** Enable TLS (`spring.data.redis.ssl.enabled=true`) and use the instance hostname and TLS port (commonly 6380 when non-TLS is disabled). Prefer Microsoft Entra authentication where that tier and the client stack already in the repo support short-lived data-plane tokens. Otherwise set `spring.data.redis.password` from the environment or the app's existing Key Vault reference. Never commit access keys, connection strings, or primary/secondary secrets, and do not invent secret names or resource ids. Restrict the network with the firewall or a private endpoint and private DNS; laptops use local Redis or an approved tunnel, not the production key on a public endpoint. Application TTLs still matter if the server policy is `noeviction`. Use cluster configuration only when the instance is clustered, and do not assume a multi-key command spans prefixes.\n\n## Tool placement\n- **GitHub Copilot:** path-scoped `.github/instructions/spring-boot-cache-redis.instructions.md` with `applyTo` covering the cache configuration class, `application*.{yml,yaml,properties}`, and files that declare `@Cacheable`, `@CacheEvict`, or `@CachePut`. Keep one always-on line in `.github/copilot-instructions.md`: Redis caches have a TTL, JSON values, a namespaced prefix, and no `allEntries=true` on large keyspaces.\n- **Claude Code:** procedure in `.claude/skills/spring-boot-cache-redis-guardrails/SKILL.md`. One CLAUDE.md fact: \"Spring Cache on Redis always sets a TTL via RedisCacheManagerBuilderCustomizer; @EnableCaching lives on an isolated @Configuration, not the application class.\"\n- **Codex:** a short cache section in root `AGENTS.md`, or `docs/agents/spring-boot-cache-redis.md` linked from it when the root file would grow. State TTL, serializer, prefix, eviction, and fail-open versus fail-closed.\n\n## Anti-patterns\n- `@EnableCaching` on `@SpringBootApplication`, so every slice test opens Redis\n- Leaving TTL unset and treating \"it works on my laptop\" as production-safe\n- A custom `CacheManager` or `RedisCacheConfiguration` bean that silently ignores `spring.cache.redis.*`\n- JDK-serialized values, or JSON with permissive `@class` typing on a shared cache\n- `use-key-prefix=false`, or one prefix shared by dev and prod\n- SpEL built from `toString()`, tokens, or PII\n- `@CacheEvict(allEntries = true)` as a routine invalidation on Azure-sized keyspaces\n- `disableCachingNullValues()` without `unless`, so legitimate null returns throw\n- Believing `sync = true` is a cluster-wide single-flight\n- Evicting before the database write, or assuming transaction-aware cache is on by default\n- A Caffeine near cache with no invalidation story in a multi-pod deployment\n- Fail-open put/evict on data that must not stay stale past the method return\n- CI tests aimed at a shared Redis or at Azure\n- Access keys, connection strings, or firewall exceptions committed \"just for local\"\n\n## Verification\n- [ ] `spring.cache.type=redis` and both starters are present; `@EnableCaching` is not on the application class\n- [ ] Global TTL is set, and each hot cache has an explicit TTL from `RedisCacheManagerBuilderCustomizer` derived from Boot's configuration\n- [ ] No replacement `CacheManager` / `RedisCacheConfiguration` bean drops Boot properties\n- [ ] Values are JSON with a documented type allowlist; keys are strings; prefix includes app, environment, and schema version\n- [ ] Read and evict SpEL keys match; keys and values contain no secrets or PII\n- [ ] Bulk clear is scan-based or version-bumped; `allEntries=true` is absent on large caches\n- [ ] Null policy is explicit (`unless` / `condition` / short null TTL) and does not throw on ordinary nulls\n- [ ] Cross-pod single-flight, if any, documents lock TTL and the failure mode; `sync=true` is not described as cluster-wide\n- [ ] Write-then-evict order is intact; `transactionAware` is set only if the PR explains it\n- [ ] Command timeout, pool wait, and `CacheErrorHandler` match the chosen fail-open or fail-closed mode\n- [ ] Slice tests do not need Redis; hot-path integration uses a pinned Testcontainers image\n- [ ] Azure notes name TLS, auth source (Entra or access key via env/Key Vault), and private network, with no secrets in the diff\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-cache-redis-guardrails\ndescription: Use when designing or reviewing Spring Cache on Redis or Azure Cache for Redis \u2014 TTL via RedisCacheManagerBuilderCustomizer, JSON serializers, key prefixes, eviction, stampede, and multi-pod correctness.\n---\n\nFollow Spring Boot Cache Redis Guardrails: explicit redis cache type, @EnableCaching on an isolated configuration, TTL on every cache, JSON values, namespaced prefixes, targeted eviction, and a documented fail-open or fail-closed policy.\n```\n" }, { "id": "maven-multimodule-ci-cache-guardrails", "title": "Maven Multi-Module CI Cache Guardrails", - "whenToUse": "Speeding up or reviewing GitHub Actions builds for a Maven multi-module Java reactor — dependency cache keys, setup-java cache, reactor flags, and what never to cache.", + "whenToUse": "Speeding up or reviewing GitHub Actions builds for a Maven multi-module Java reactor \u2014 dependency cache keys, setup-java cache, reactor flags, and what never to cache.", "tools": [ "copilot", "claude-code", @@ -428,7 +428,28 @@ "multi-module" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/maven-ci-cache.instructions.md` with applyTo for `**/pom.xml`, `.github/workflows/**/*.{yml,yaml}`, and `**/.mvn/**`. Claude Code: `.claude/skills/maven-multimodule-ci-cache-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that CI caches `~/.m2/repository` by hashed poms, never `**/target`. Codex: a Maven CI section in root `AGENTS.md` or linked `docs/agents/maven-ci-cache.md`.", - "body": "# Skill: Maven Multi-Module CI Cache Guardrails\n\n## Goal\nMake GitHub Actions builds for a Maven multi-module reactor fast and correct: cache the local repository by pom hashes, keep the reactor deterministic, and never poison the cache with `target/` output or secrets.\n\n## When to apply\n- Adding or reviewing `setup-java` / `actions/cache` for a Maven monorepo\n- Slow CI after new modules, BOM bumps, or snapshot churn\n- Flaky builds that pass locally but fail after a cache hit\n- Introducing `-T` parallel reactor builds or selective module builds (`-pl` / `-am` / `-amd`)\n- Hardening cache keys, restore-keys, and path lists before production pipelines\n\n## Baseline rules\n1. **Prefer `setup-java` Maven cache over a hand-rolled `actions/cache`.** On GitHub-hosted runners, `actions/setup-java` with `cache: maven` hashes the dependency tree from the poms and restores `~/.m2/repository`. Use it unless the workflow already has a documented custom cache (for example a shared self-hosted cache layout). If you must use `actions/cache` directly, pin the action major, set `path` to `~/.m2/repository` only, and key on OS plus a hash of every `pom.xml` (and the Maven wrapper props if the wrapper pins the distribution).\n2. **Key on every pom that can change the classpath.** In a multi-module reactor the parent BOM, dependencyManagement, and pluginManagement all affect resolution. Hash `**/pom.xml` (or the concrete list the root reactor includes). Include `.mvn/wrapper/maven-wrapper.properties` when the wrapper is the source of truth for the Maven version. Do not key only on the root pom — a leaf module bump must bust the cache.\n3. **Never cache `**/target` or compiled classes.** Module `target/` directories are build outputs. Caching them across jobs mixes stale class files with new sources and causes ghost test failures. Cache the local repository (resolved jars) and rebuild modules each run. If you need artifact reuse between jobs in one workflow, use `actions/upload-artifact` / `download-artifact` for specific jars, not a persistent `target/` cache key.\n4. **Keep restore-keys as a fallback prefix, not a second full key.** A typical pattern is `key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}` with `restore-keys: ${{ runner.os }}-m2-`. A partial restore is fine (extra jars stay; missing ones download). Do not use an overly broad key that never changes — that freezes an old dependency set after a BOM bump until manual eviction.\n5. **Use the Maven Wrapper in CI.** Commit `.mvn/wrapper` and invoke `./mvnw` (or `mvnw.cmd` on Windows) so the Maven version matches developers. Pin `distributionUrl` to a release, not a moving `latest`. Do not install a different Maven via apt and ignore the wrapper when the repo has one.\n6. **CI-friendly Maven flags are mandatory.** Always pass `-B` (batch) and prefer `-ntp` (no transfer progress). Fail the job on dependency warnings that hide resolution problems when the team already treats them as errors (`-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn` is optional noise control, not a substitute for `-B`). Do not hide test failures with blanket `-DskipTests` on the main verify job; use a dedicated job or profile only when the pipeline already separates compile from test.\n7. **Reactor flags for multi-module: be explicit.** Default CI should run from the reactor root: `./mvnw -B -ntp verify` (or the project's standard lifecycle). Selective builds with `-pl module-a,module-b -am` are for PR paths when the workflow already computes the affected modules; document how the module list is derived. `-amd` builds dependents; use it when an API module change must re-test consumers. Do not combine ad-hoc `-pl` with a stale local repo assumption — the cache must still contain the parent BOM artifacts.\n8. **Parallel builds need thread-safe plugins.** `-T 1C` (one thread per core) or `-T 2` can cut wall time on large reactors. Confirm surefire/failsafe fork settings and any custom plugins are safe under concurrent module builds. If a module is known unsafe, exclude it from parallelism or keep CI serial until fixed. Document the chosen `-T` value in the workflow comment or AGENTS.md.\n9. **Snapshots and mirror config belong in checked-in settings — carefully.** If CI uses a `settings.xml` (company mirror, authenticated registry), mount it via `actions/setup-java` `server-id` / env-backed passwords or a short-lived token. Never commit passwords, tokens, or base64-encoded credentials. Prefer OIDC or short-lived cloud tokens already used elsewhere in the repo over long-lived `settings.xml` secrets. Snapshot updates (`-U`) belong on a scheduled or main-branch job when snapshot deps exist; do not force `-U` on every PR unless the team depends on floating snapshots (prefer pinning).\n10. **Separate dependency resolution from tests when it helps.** A common pattern: job 1 resolves and optionally runs `./mvnw -B -ntp -DskipTests package` with cache save; job 2 restores the same cache key and runs tests. With `setup-java` cache, a single job that runs `verify` is enough for most repos — only split when wall time or runners justify it. Post-job cache save failures must not hide a red test step; keep test exit code authoritative.\n11. **Windows vs Ubuntu runners.** Cache keys must include `runner.os` (or an explicit OS label). Path separators and the wrapper script differ; use `./mvnw` on Unix and `mvnw.cmd` on Windows, or `bash mvnw` when bash is available. Do not assume a Linux-only `~/.m2` path on Windows runners (`~/.m2/repository` still works under the user home, but document it).\n12. **Validate locally before trusting CI cache lore.** Reproduce with `./mvnw -B -ntp -o verify` (offline) after a populated local repo to confirm the reactor does not need unexpected remote hits. In CI logs, confirm cache restore HIT/MISS and that dependency downloads after a pom-only change are expected. Watch for cache thrash: keys that change every run (embedding `github.sha` into the m2 key) defeat the purpose.\n\n## Tool placement\n- **GitHub Copilot:** path-scoped `.github/instructions/maven-ci-cache.instructions.md` with `applyTo` for `**/pom.xml`, `.github/workflows/**/*.{yml,yaml}`, and `**/.mvn/**`. One always-on line in `.github/copilot-instructions.md`: CI caches `~/.m2/repository` keyed by hashed poms; never cache `**/target`.\n- **Claude Code:** procedure in `.claude/skills/maven-multimodule-ci-cache-guardrails/SKILL.md`. One CLAUDE.md fact: \"Maven CI uses setup-java cache or actions/cache on ~/.m2/repository keyed by **/pom.xml; never cache target/.\"\n- **Codex:** short Maven CI section in root `AGENTS.md`, or `docs/agents/maven-ci-cache.md` linked from it. State cache path, key inputs, wrapper, and reactor command.\n\n## Anti-patterns\n- Caching `**/target` or the whole workspace as a \"speedup\"\n- Keying the m2 cache only on the root pom in a multi-module tree\n- Embedding `github.sha` or a timestamp into the dependency cache key\n- Ignoring the Maven Wrapper and installing a different Maven in CI\n- Blanket `-DskipTests` on the only verify job to \"make cache warmer\"\n- Committing `settings.xml` with passwords or tokens\n- Assuming `-T` is safe without checking surefire forks / custom plugins\n- Partial `-pl` builds without `-am` when the module needs reactor siblings\n- restore-keys so broad they keep serving a pre-CVE dependency set with no pom hash change path\n- Documenting Azure/GitHub secrets or mirror URLs that are not already in the repo\n\n## Verification\n- [ ] Workflow uses `setup-java` `cache: maven` or an equivalent `actions/cache` on `~/.m2/repository` only\n- [ ] Cache key hashes all relevant `pom.xml` files (and wrapper props if used)\n- [ ] No path entry caches `**/target` or compiled outputs across runs\n- [ ] CI invokes `./mvnw` (or documented Windows equivalent) with `-B` and preferably `-ntp`\n- [ ] Default job runs a full reactor verify (or a documented selective `-pl/-am` strategy)\n- [ ] Parallel `-T` is documented and known-safe for this repo, or omitted\n- [ ] No credentials in committed settings; tokens via env / OIDC already used in-repo\n- [ ] After a leaf pom dependency bump, CI shows cache miss or partial restore then downloads the new artifact\n- [ ] Offline local `./mvnw -B -ntp -o verify` works on a warm machine for the same revision\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: maven-multimodule-ci-cache-guardrails\ndescription: Use when speeding up or reviewing GitHub Actions Maven multi-module builds — setup-java/m2 cache keys, reactor flags, wrapper, and never caching target/.\n---\n\nFollow Maven Multi-Module CI Cache Guardrails: cache ~/.m2/repository keyed by hashed poms, use the Maven Wrapper with -B -ntp, never cache **/target, and document any -pl/-am or -T usage.\n```\n" + "body": "# Skill: Maven Multi-Module CI Cache Guardrails\n\n## Goal\nMake GitHub Actions builds for a Maven multi-module reactor fast and correct: cache the local repository by pom hashes, keep the reactor deterministic, and never poison the cache with `target/` output or secrets.\n\n## When to apply\n- Adding or reviewing `setup-java` / `actions/cache` for a Maven monorepo\n- Slow CI after new modules, BOM bumps, or snapshot churn\n- Flaky builds that pass locally but fail after a cache hit\n- Introducing `-T` parallel reactor builds or selective module builds (`-pl` / `-am` / `-amd`)\n- Hardening cache keys, restore-keys, and path lists before production pipelines\n\n## Baseline rules\n1. **Prefer `setup-java` Maven cache over a hand-rolled `actions/cache`.** On GitHub-hosted runners, `actions/setup-java` with `cache: maven` hashes the dependency tree from the poms and restores `~/.m2/repository`. Use it unless the workflow already has a documented custom cache (for example a shared self-hosted cache layout). If you must use `actions/cache` directly, pin the action major, set `path` to `~/.m2/repository` only, and key on OS plus a hash of every `pom.xml` (and the Maven wrapper props if the wrapper pins the distribution).\n2. **Key on every pom that can change the classpath.** In a multi-module reactor the parent BOM, dependencyManagement, and pluginManagement all affect resolution. Hash `**/pom.xml` (or the concrete list the root reactor includes). Include `.mvn/wrapper/maven-wrapper.properties` when the wrapper is the source of truth for the Maven version. Do not key only on the root pom \u2014 a leaf module bump must bust the cache.\n3. **Never cache `**/target` or compiled classes.** Module `target/` directories are build outputs. Caching them across jobs mixes stale class files with new sources and causes ghost test failures. Cache the local repository (resolved jars) and rebuild modules each run. If you need artifact reuse between jobs in one workflow, use `actions/upload-artifact` / `download-artifact` for specific jars, not a persistent `target/` cache key.\n4. **Keep restore-keys as a fallback prefix, not a second full key.** A typical pattern is `key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}` with `restore-keys: ${{ runner.os }}-m2-`. A partial restore is fine (extra jars stay; missing ones download). Do not use an overly broad key that never changes \u2014 that freezes an old dependency set after a BOM bump until manual eviction.\n5. **Use the Maven Wrapper in CI.** Commit `.mvn/wrapper` and invoke `./mvnw` (or `mvnw.cmd` on Windows) so the Maven version matches developers. Pin `distributionUrl` to a release, not a moving `latest`. Do not install a different Maven via apt and ignore the wrapper when the repo has one.\n6. **CI-friendly Maven flags are mandatory.** Always pass `-B` (batch) and prefer `-ntp` (no transfer progress). Fail the job on dependency warnings that hide resolution problems when the team already treats them as errors (`-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn` is optional noise control, not a substitute for `-B`). Do not hide test failures with blanket `-DskipTests` on the main verify job; use a dedicated job or profile only when the pipeline already separates compile from test.\n7. **Reactor flags for multi-module: be explicit.** Default CI should run from the reactor root: `./mvnw -B -ntp verify` (or the project's standard lifecycle). Selective builds with `-pl module-a,module-b -am` are for PR paths when the workflow already computes the affected modules; document how the module list is derived. `-amd` builds dependents; use it when an API module change must re-test consumers. Do not combine ad-hoc `-pl` with a stale local repo assumption \u2014 the cache must still contain the parent BOM artifacts.\n8. **Parallel builds need thread-safe plugins.** `-T 1C` (one thread per core) or `-T 2` can cut wall time on large reactors. Confirm surefire/failsafe fork settings and any custom plugins are safe under concurrent module builds. If a module is known unsafe, exclude it from parallelism or keep CI serial until fixed. Document the chosen `-T` value in the workflow comment or AGENTS.md.\n9. **Snapshots and mirror config belong in checked-in settings \u2014 carefully.** If CI uses a `settings.xml` (company mirror, authenticated registry), mount it via `actions/setup-java` `server-id` / env-backed passwords or a short-lived token. Never commit passwords, tokens, or base64-encoded credentials. Prefer OIDC or short-lived cloud tokens already used elsewhere in the repo over long-lived `settings.xml` secrets. Snapshot updates (`-U`) belong on a scheduled or main-branch job when snapshot deps exist; do not force `-U` on every PR unless the team depends on floating snapshots (prefer pinning).\n10. **Separate dependency resolution from tests when it helps.** A common pattern: job 1 resolves and optionally runs `./mvnw -B -ntp -DskipTests package` with cache save; job 2 restores the same cache key and runs tests. With `setup-java` cache, a single job that runs `verify` is enough for most repos \u2014 only split when wall time or runners justify it. Post-job cache save failures must not hide a red test step; keep test exit code authoritative.\n11. **Windows vs Ubuntu runners.** Cache keys must include `runner.os` (or an explicit OS label). Path separators and the wrapper script differ; use `./mvnw` on Unix and `mvnw.cmd` on Windows, or `bash mvnw` when bash is available. Do not assume a Linux-only `~/.m2` path on Windows runners (`~/.m2/repository` still works under the user home, but document it).\n12. **Validate locally before trusting CI cache lore.** Reproduce with `./mvnw -B -ntp -o verify` (offline) after a populated local repo to confirm the reactor does not need unexpected remote hits. In CI logs, confirm cache restore HIT/MISS and that dependency downloads after a pom-only change are expected. Watch for cache thrash: keys that change every run (embedding `github.sha` into the m2 key) defeat the purpose.\n\n## Tool placement\n- **GitHub Copilot:** path-scoped `.github/instructions/maven-ci-cache.instructions.md` with `applyTo` for `**/pom.xml`, `.github/workflows/**/*.{yml,yaml}`, and `**/.mvn/**`. One always-on line in `.github/copilot-instructions.md`: CI caches `~/.m2/repository` keyed by hashed poms; never cache `**/target`.\n- **Claude Code:** procedure in `.claude/skills/maven-multimodule-ci-cache-guardrails/SKILL.md`. One CLAUDE.md fact: \"Maven CI uses setup-java cache or actions/cache on ~/.m2/repository keyed by **/pom.xml; never cache target/.\"\n- **Codex:** short Maven CI section in root `AGENTS.md`, or `docs/agents/maven-ci-cache.md` linked from it. State cache path, key inputs, wrapper, and reactor command.\n\n## Anti-patterns\n- Caching `**/target` or the whole workspace as a \"speedup\"\n- Keying the m2 cache only on the root pom in a multi-module tree\n- Embedding `github.sha` or a timestamp into the dependency cache key\n- Ignoring the Maven Wrapper and installing a different Maven in CI\n- Blanket `-DskipTests` on the only verify job to \"make cache warmer\"\n- Committing `settings.xml` with passwords or tokens\n- Assuming `-T` is safe without checking surefire forks / custom plugins\n- Partial `-pl` builds without `-am` when the module needs reactor siblings\n- restore-keys so broad they keep serving a pre-CVE dependency set with no pom hash change path\n- Documenting Azure/GitHub secrets or mirror URLs that are not already in the repo\n\n## Verification\n- [ ] Workflow uses `setup-java` `cache: maven` or an equivalent `actions/cache` on `~/.m2/repository` only\n- [ ] Cache key hashes all relevant `pom.xml` files (and wrapper props if used)\n- [ ] No path entry caches `**/target` or compiled outputs across runs\n- [ ] CI invokes `./mvnw` (or documented Windows equivalent) with `-B` and preferably `-ntp`\n- [ ] Default job runs a full reactor verify (or a documented selective `-pl/-am` strategy)\n- [ ] Parallel `-T` is documented and known-safe for this repo, or omitted\n- [ ] No credentials in committed settings; tokens via env / OIDC already used in-repo\n- [ ] After a leaf pom dependency bump, CI shows cache miss or partial restore then downloads the new artifact\n- [ ] Offline local `./mvnw -B -ntp -o verify` works on a warm machine for the same revision\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: maven-multimodule-ci-cache-guardrails\ndescription: Use when speeding up or reviewing GitHub Actions Maven multi-module builds \u2014 setup-java/m2 cache keys, reactor flags, wrapper, and never caching target/.\n---\n\nFollow Maven Multi-Module CI Cache Guardrails: cache ~/.m2/repository keyed by hashed poms, use the Maven Wrapper with -B -ntp, never cache **/target, and document any -pl/-am or -T usage.\n```\n" + }, + { + "id": "k8s-probes-graceful-shutdown-guardrails", + "title": "Kubernetes Probes & Graceful Shutdown Guardrails", + "whenToUse": "Wiring or reviewing readiness, liveness, and startup probes plus graceful SIGTERM handling for Spring Boot (or generic HTTP) apps on AKS/Kubernetes so rollouts drain cleanly without cascading restarts.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "kubernetes", + "aks", + "spring-boot", + "probes", + "graceful-shutdown", + "actuator", + "reliability" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/k8s-probes-shutdown.instructions.md` with applyTo for `**/deployment*.{yml,yaml}`, `**/values*.yaml`, `**/templates/**/*.yaml`, and `**/application*.{yml,yaml,properties}`. Claude Code: `.claude/skills/k8s-probes-graceful-shutdown-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that liveness stays dependency-free, readiness gates traffic, and preStop sleep plus graceful shutdown must fit inside terminationGracePeriodSeconds. Codex: a Probes & Shutdown section in root `AGENTS.md` or linked `docs/agents/k8s-probes-shutdown.md`. Pair with spring-boot-actuator-hardening for endpoint exposure; this skill owns probe timing and drain behavior.", + "body": "# Skill: Kubernetes Probes & Graceful Shutdown Guardrails\n\n## Goal\nMake Kubernetes rollouts safe for HTTP services (Spring Boot first-class, generic apps welcome): correct startup/liveness/readiness probes, coordinated graceful shutdown, and no cascading restarts from dependency blips.\n\n## When to apply\n- New Deployments/Helm charts for Spring Boot or other HTTP services on AKS/Kubernetes\n- Rolling updates that drop in-flight requests (502/connection resets) or restart under load\n- Reviews of probe paths, thresholds, `preStop`, and `terminationGracePeriodSeconds`\n- Apps enabling Actuator health groups or moving probes to a management port\n- Slow-starting JVMs killed before they become ready\n\n## Baseline rules\n1. **Three probes, three jobs.** `startupProbe` protects slow boot; until it succeeds, liveness/readiness are not evaluated. `livenessProbe` answers \u201cshould Kubernetes restart this process?\u201d \u2014 keep it cheap and local. `readinessProbe` answers \u201cshould this Pod receive traffic?\u201d \u2014 dependencies and warm-up belong here. Do not collapse all three onto `/actuator/health` without groups.\n2. **Prefer dedicated health groups for Spring Boot.** Enable probes (`management.endpoint.health.probes.enabled=true` on supported Boot versions) and point HTTP probes at `/actuator/health/liveness` and `/actuator/health/readiness` (adjust for `management.endpoints.web.base-path`). Keep the liveness group free of DB/Redis/broker checks; put those on readiness (or custom indicators used only by readiness). For non-Spring apps, expose a lightweight `/livez` (process up) and `/readyz` (deps + accept traffic).\n3. **Probe the port that serves the app path you care about.** If Actuator runs on a separate `management.server.port`, probes must use that `containerPort` (and the Deployment must declare it). Avoid a probe that succeeds on the management port while the main listener is down \u2014 document the chosen layout. Endpoint *exposure* and auth belong in the actuator hardening skill; here the rule is: probes must hit a stable, privately reachable path that reflects the AvailabilityState you intend.\n4. **Always add a startupProbe for JVM services with non-trivial boot.** Example shape: HTTP GET to the liveness (or readiness) path, `periodSeconds: 5`, `failureThreshold` sized so `period \u00d7 failureThreshold` covers p99 cold start (often 60\u2013180s). Prefer startupProbe over large `initialDelaySeconds` on liveness. After startup succeeds, keep liveness/readiness `initialDelaySeconds` small or zero.\n5. **Tune failureThreshold and periodSeconds deliberately.** Defaults (`periodSeconds: 10`, `timeoutSeconds: 1`) are often too tight under GC or brief CPU throttle. Typical production bands: readiness `periodSeconds: 5\u201310`, `failureThreshold: 2\u20133`, `timeoutSeconds: 1\u20133`; liveness slightly slower (`periodSeconds: 10\u201315`, `failureThreshold: 3+`) so a single slow request does not restart the Pod. Document the math in a chart comment when thresholds are non-default.\n6. **Enable graceful shutdown in the app.** For Spring Boot: `server.shutdown=graceful` and a bounded `spring.lifecycle.timeout-per-shutdown-phase` (for example `30s`) so in-flight requests finish and readiness flips to refusing traffic. Ensure the process receives SIGTERM (PID 1 or a signal-forwarding entrypoint \u2014 no shell wrapper that swallows signals). Non-Spring: drain the HTTP server on SIGTERM with an explicit timeout.\n7. **Close the endpoint-propagation race with `preStop`.** Kubernetes can send SIGTERM while kube-proxy/EndpointSlice updates are still catching up. Add a `lifecycle.preStop` sleep (commonly `sleep 10`\u2013`15`, or an exec that waits briefly) *before* the app starts draining, so new traffic stops arriving. Keep the sleep boring and deterministic; do not run complex scripts that can hang.\n8. **Fit the whole drain inside `terminationGracePeriodSeconds`.** Budget: `preStop sleep + app shutdown timeout + small buffer` \u2264 `terminationGracePeriodSeconds` (often 45\u201390s for HTTP APIs). If the grace period is shorter than the sleep + lifecycle timeout, Kubernetes sends SIGKILL and you lose the graceful path. Align Deployment, PodDisruptionBudget expectations, and HPA scale-in with the same budget.\n9. **Rollout and mesh awareness.** During RollingUpdate, `maxUnavailable`/`maxSurge` plus readiness must keep enough Ready Pods. If you use a service mesh or ingress with long idle timeouts, ensure readiness failure removes the Pod from backends before preStop finishes. Do not rely on liveness to \u201cfix\u201d overload \u2014 fix capacity or readiness instead.\n10. **Observe probe failures as first-class signals.** Watch `kube_pod_container_status_restarts`, Ready condition flaps, and application readiness state transitions. A spike in liveness failures is an incident; a readiness flap during a dependency outage can be correct behavior. Alert on restart loops, not on every readiness failure.\n\n## Checklist\n- [ ] Distinct startup / liveness / readiness (or documented reason for omitting startup)\n- [ ] Liveness path has no remote dependency checks\n- [ ] Readiness reflects \u201caccept traffic\u201d (deps, warm-up, migrations finished)\n- [ ] Probe port/path match Actuator or custom livez/readyz layout\n- [ ] startupProbe failure budget covers cold start; liveness not used as a fake startup delay\n- [ ] `server.shutdown=graceful` (or equivalent) + bounded shutdown phase timeout\n- [ ] `preStop` sleep present; SIGTERM reaches the JVM/process\n- [ ] `terminationGracePeriodSeconds` \u2265 preStop + shutdown timeout + buffer\n- [ ] RollingUpdate / PDB still leave enough Ready Pods\n- [ ] Actuator exposure reviewed separately (no public management LoadBalancer)\n\n## Anti-patterns\n- Liveness pointing at `/actuator/health` with DB/disk/mail indicators \u2014 DB blip restarts the fleet\n- No startupProbe and a huge `initialDelaySeconds` that delays failure detection forever after the first start\n- Aggressive liveness (`timeoutSeconds: 1`, `failureThreshold: 1`) under load or GC\n- Graceful shutdown enabled but `terminationGracePeriodSeconds` left at 30s with a 30s app timeout and a 15s preStop (SIGKILL)\n- `preStop` that calls the app\u2019s own `/shutdown` without coordinating readiness, or a hook that can block past the grace period\n- Probes against a public Ingress URL instead of the container port\n- Shell entrypoint (`java ... & wait`) that never forwards SIGTERM\n\n## Verification\n1. `kubectl describe pod` / events: startup succeeds; no unexpected liveness kills during boot.\n2. Exec or port-forward: liveness returns UP while artificially breaking a dependency; readiness goes DOWN.\n3. Trigger a rollout: confirm in-flight requests complete (no surge of 502s) and Pods leave Ready before process exit.\n4. Confirm process exit within grace period (no `Kill` after exceeded grace in events).\n5. Chaos: brief DB outage \u2192 readiness flaps, restart count stays flat.\n\n## Copilot / Claude Code / Codex notes\n- Copilot: keep applyTo narrow to manifests and `application*.{yml,yaml,properties}`; paste the checklist into the PR description.\n- Claude Code: SKILL.md holds this procedure; CLAUDE.md only stores the one-liner on probe roles + grace budget.\n- Codex: put the budget formula and anti-patterns in AGENTS.md; ask for a small Deployment/values + application config diff only.\n" } ] }