From 8128518cb86b467a3d790bcc6f3902b4a0a645c7 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:05:49 +0000 Subject: [PATCH 1/2] Add Jenkins declarative pipeline guardrails skill --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index 18d021d..26e72c1 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -592,6 +592,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spark-job-tuning.instructions.md` with applyTo for job code and job configs (`**/jobs/**/*.py`, `**/src/**/*.scala`, `**/*.sql`, `**/notebooks/**/*.py`, `**/databricks.yml`, `**/resources/**/*.yml`) (optional `.github/skills/spark-job-tuning-guardrails/SKILL.md`). Claude Code: `.claude/skills/spark-job-tuning-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that Spark tuning is baseline → plan → one change at a time with AQE on. Codex: a Spark performance section in root `AGENTS.md` or a nested `AGENTS.md` under the jobs directory. Pair with data-platform-pipeline-review for contracts, idempotency, and PII — this skill covers runtime performance only.", "body": "# Skill: Spark Job Performance Tuning Guardrails\n\n## Goal\nMake Spark / PySpark / Spark SQL batch jobs faster and cheaper by fixing what the physical plan and Spark UI actually show — shuffle volume, skew, spill, join strategy, and file layout — instead of guessing at cluster size or pasting config snippets.\n\n## When to apply\n- A job breaches its SLA, runs noticeably slower after a data-volume jump, or costs more than its peers\n- Spark UI shows one or two straggler tasks, heavy spill, huge shuffle read/write, or thousands of tiny tasks\n- Reviews of new joins, aggregations, window functions, UDFs, or `MERGE`/upsert logic on large tables\n- Jobs that write many small files or one giant file per partition\n- Someone proposes \"just double the workers\" or adds `.cache()` / `.repartition()` without evidence\n\n## Baseline rules\n1. **Measure before tuning.** Capture a baseline run: wall time, stage durations, input/shuffle/spill bytes, task-duration distribution (median vs max), and cluster cost. Every change is compared to that baseline on representative data — same volume, skew, and file layout as production.\n2. **Read the plan first.** Use `df.explain(mode=\"formatted\")` (or `EXPLAIN FORMATTED` / `EXPLAIN COST`) and the SQL tab of the Spark UI. Find each `Exchange` (shuffle), the join type chosen (`BroadcastHashJoin`, `SortMergeJoin`, `ShuffledHashJoin`), and whether filters and column pruning reach the scan.\n3. **Keep AQE on.** Adaptive Query Execution (default since Spark 3.2) coalesces small post-shuffle partitions, converts eligible sort-merge joins to broadcast at runtime, and splits skewed join partitions. Do not disable it to \"stabilize\" a job; tune its thresholds instead (`advisoryPartitionSizeInBytes`, skew factor and threshold).\n4. **Shrink data early.** Filter and project before joins and aggregations; read only needed columns from columnar formats; make sure partition filters and predicate pushdown appear in the scan node. Avoid `select *` across big tables and avoid exploding arrays before filtering.\n5. **Pick the join strategy deliberately.** Broadcast only a side that is reliably small after filtering (and within executor/driver memory) — use a `broadcast()` hint when the size is known and stable. Never broadcast a table that grows with business volume. For large–large joins, align keys and types so Spark does not add casts or extra shuffles.\n6. **Treat skew explicitly.** Confirm skew in the stage view (max task time or shuffle read far above the 75th percentile). Let AQE skew-join handling cover sort-merge joins first; for skew it cannot see (aggregations, broadcast joins, sub-threshold hot keys) use pre-aggregation, isolating hot keys, or salting — and document the hot keys.\n7. **Size partitions by bytes, not habit.** Aim for roughly 100–200 MB of input per shuffle partition; let AQE coalesce from a deliberately high initial partition count rather than hard-coding `spark.sql.shuffle.partitions=200` forever. Use `repartition` only when you need a key-based distribution; use `coalesce` to reduce partitions without a full shuffle.\n8. **Spill is a signal.** Large memory or disk spill means partitions are too big or rows too wide. Fix partitioning or row width first; raise executor memory only when the data per task is already sensible.\n9. **Cache only reused results.** `cache()`/`persist()` a DataFrame only when it is reused by more than one action and fits comfortably; `unpersist()` when done. Never cache \"just in case\" and never cache before a filter.\n10. **Prefer built-ins over Python UDFs.** Use Spark SQL functions first; if Python logic is unavoidable use pandas/Arrow UDFs instead of row-at-a-time UDFs. No `collect()`/`toPandas()` on unbounded data, and no driver-side loops that trigger one job per item.\n11. **Write files of healthy size.** Control output layout so files land roughly in the 128 MB–1 GB range: use the `REBALANCE` hint or `repartition` by the write partition columns, avoid high-cardinality partition columns, and schedule compaction (`OPTIMIZE` / auto-compaction or the table format's equivalent) for incrementally written tables.\n12. **Keep statistics fresh.** Run `ANALYZE TABLE … COMPUTE STATISTICS` (or rely on the table format's stats) so the optimizer's size estimates — and therefore join choices — are realistic.\n13. **Config changes live in code, scoped and explained.** Set tuning configs in the job definition (session config, job JSON, or asset bundle) with a comment stating the evidence. No cluster-wide overrides to fix a single job; no copy-pasted config blocks with unknown origin.\n\n## Workflow\n1. Inventory: job entrypoint, input tables and sizes, output table and its partitioning, cluster/pool definition, current Spark configs, last few run durations.\n2. Baseline run on representative data; save the plan and the top three slowest stages with their metrics.\n3. Diagnose each slow stage: shuffle bytes, skew (max vs p75), spill, task count, scan pruning.\n4. Apply one change at a time in priority order: prune/filter → join strategy → skew handling → partition sizing → write layout → caching → cluster size.\n5. Re-run, compare against baseline, and keep only changes that measurably help.\n6. PR notes: before/after metrics table, plan excerpts, configs added with rationale, residual risks (data growth, broadcast size drift).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spark-job-tuning.instructions.md` with `applyTo` for job code and configs (for example `**/jobs/**/*.py`, `**/src/**/*.scala`, `**/*.sql`, `**/notebooks/**/*.py`, `**/databricks.yml`, `**/resources/**/*.yml`).\n- Always-on line in `.github/copilot-instructions.md`: \"Spark changes need a plan excerpt and before/after stage metrics; keep AQE on; no unbounded `collect()`/`toPandas()`.\"\n- Optional `.github/skills/spark-job-tuning-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/spark-job-tuning-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Spark tuning is evidence-based: baseline → plan → one change at a time; AQE stays enabled; configs are set per job with a comment.\"\n- Before claiming done, show the `explain` output for the changed query and the before/after metrics.\n\n### Codex\n- A Spark performance section in root `AGENTS.md`, or nested `AGENTS.md` under the jobs directory (or linked `docs/agents/spark-job-tuning.md`).\n- State: how to run a job locally or on a dev cluster, where plans and run metrics are saved, banned patterns (row UDFs, unbounded collect, blanket cache), and the config-in-code rule.\n\n## Anti-patterns\n- Doubling cluster size before reading the plan\n- Disabling AQE or hard-coding `spark.sql.shuffle.partitions` without measuring\n- Broadcasting a dimension table that quietly grows past memory\n- Salting every join \"for safety\" when there is no skew\n- `.cache()` sprinkled across a pipeline with no `unpersist()`\n- Row-at-a-time Python UDFs where a built-in function exists\n- `collect()`/`toPandas()` on full tables inside production jobs\n- Partitioning output by a high-cardinality column (user id, timestamp) and creating millions of tiny files\n- Benchmarking on a tiny sample whose skew and file layout look nothing like production\n\n## Verification checklist\n- [ ] Baseline and post-change metrics captured on representative data\n- [ ] Plan reviewed: shuffles, join strategies, and scan pruning explained\n- [ ] AQE enabled; any threshold changes justified\n- [ ] Skew confirmed (or ruled out) from stage metrics, with the fix documented\n- [ ] Spill eliminated or explained\n- [ ] No unbounded `collect()`/`toPandas()` and no avoidable Python row UDFs\n- [ ] Output files in a healthy size range; compaction plan in place\n- [ ] Configs live in the job definition with comments\n- [ ] PR includes before/after table and residual risks\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spark-job-tuning-guardrails\ndescription: Use when a Spark, PySpark, or Spark SQL job is slow, spills, has straggler tasks, writes small files, or a review touches large joins and aggregations. Tune from the plan and Spark UI metrics with AQE on, one change at a time.\n---\n\nFollow Spark Job Performance Tuning Guardrails: baseline first, read the physical plan, keep AQE on, prune early, choose joins deliberately, handle skew explicitly, size partitions by bytes, cache only reused data, prefer built-ins over Python UDFs, write healthy file sizes, and keep tuning configs in code with evidence.\n```\n" + }, + { + "id": "jenkins-declarative-pipeline-guardrails", + "title": "Jenkins Declarative Pipeline Guardrails", + "whenToUse": "Writing or reviewing a Jenkinsfile or Jenkins shared library — new stages, credentials, approval gates, agents, or builds that hang, queue forever, or load the controller.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "jenkins", + "ci", + "devsecops", + "groovy", + "security", + "kubernetes" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/jenkins-pipeline.instructions.md` with applyTo for pipeline code (`**/Jenkinsfile`, `**/*.jenkinsfile`, `**/vars/*.groovy`, `**/src/**/*.groovy`, `**/jenkins/**/*.yaml`) (optional `.github/skills/jenkins-declarative-pipeline-guardrails/SKILL.md`). Claude Code: `.claude/skills/jenkins-declarative-pipeline-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that pipeline Groovy runs on the controller, so script blocks stay tiny and credentials are never Groovy-interpolated. Codex: a Jenkins section in root `AGENTS.md` or a nested `AGENTS.md` beside the shared library. Pair with bash-script-hardening-guardrails for the scripts the pipeline calls and gha-devsecops-pipeline if the repo also runs GitHub Actions.", + "body": "# Skill: Jenkins Declarative Pipeline Guardrails\n\n## Goal\nKeep Jenkinsfiles short, predictable, and safe: Declarative syntax as thin glue, real build logic in scripts and build tools, ephemeral agents, bounded runs, secrets that never leak into logs or Groovy strings, and pinned shared libraries — so the controller stays healthy and every build can be reproduced.\n\n## When to apply\n- Writing a new `Jenkinsfile` or converting a freestyle / Scripted job to Declarative\n- Reviews that add stages, `script {}` blocks, credentials, `input` gates, `parallel`/`matrix`, or a new `@Library`\n- Builds that hang, queue forever, fill the controller disk, or slow the whole Jenkins instance\n- Moving builds from static VMs to Kubernetes pod agents (for example on AKS)\n- Someone asks for a script approval or wants to call `Jenkins.instance` from a pipeline\n\n## Baseline rules\n1. **Pipeline as code, Declarative first.** The `Jenkinsfile` lives in the repo next to the code and is reviewed like code. Use Declarative `pipeline {}`; keep `script {}` blocks to a few lines and move anything bigger into a versioned shared library or a shell script.\n2. **Groovy is glue, not the build.** Pipeline Groovy runs on the controller. Put compilation, tests, packaging, and parsing in `sh` steps that call scripts or build tools (`./mvnw -B -ntp verify`, `make`, `./scripts/deploy.sh`). Combine many tiny `sh` calls into one script; avoid `JsonSlurper`/`XmlSlurper`, big loops, and file processing in Groovy — use `readJSON`/`readYaml` (Pipeline Utility Steps) or do it in the script.\n3. **Never build on the controller.** The built-in node has zero executors. Select agents by explicit `label`, or define a pod template / container image per stage. Prefer ephemeral agents (Kubernetes or cloud agents) so every build starts clean and nothing persists between jobs.\n4. **Pin the toolchain.** Use container images pinned by tag or digest, or `tools { jdk 'jdk-21'; maven 'maven-3.9' }` with names that map to fixed versions. Commit the Maven/Gradle wrapper. No \"latest\" images and no reliance on whatever happens to be installed on an agent.\n5. **Bound every run.** Top-level `options {}` sets `timeout(...)`, `buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))`, `timestamps()`, and `disableConcurrentBuilds(abortPrevious: true)` for branch/PR jobs. Remember a stage-level timeout with a stage-level agent includes agent provisioning time — size it accordingly.\n6. **Secrets through bindings only.** Use `withCredentials([...])` or `environment { X = credentials('id') }`, scoped to the narrowest stage. Reference secrets inside single-quoted shell strings (`sh 'curl -u \"$USER:$PASS\" ...'`) so the shell expands them, never Groovy string interpolation (`\"${PASS}\"`). No `echo` of secrets, no `set -x` around them, no writing them into the workspace or artifacts. Store credentials at folder scope, not global.\n7. **Don't punch holes in the sandbox.** No `Jenkins.instance` / internal Jenkins APIs in Jenkinsfiles or libraries, no script approvals that bypass the Groovy sandbox, and no shared-library code that overrides built-in steps like `sh` or `timeout`. If a Jenkins API is truly needed, it belongs in a small reviewed plugin.\n8. **Pin shared libraries.** Load with `@Library('team-lib@v2.3.1') _` (a tag or commit), not a moving branch. Libraries are small, tested (for example with JenkinsPipelineUnit), and versioned like any other dependency.\n9. **Gates don't hold executors.** `input` (approvals) runs with `agent none` on that stage plus its own `timeout`, so nobody's approval holds a build agent. Use `when { branch 'main' }`, `when { changeRequest() }`, or `when { tag ... }` with `beforeAgent true` instead of `if` logic inside steps. Guard deploys with `lock` and `milestone` so older builds cannot overtake newer ones.\n10. **Parallelism with intent.** Use `parallel` or `matrix` for independent work, `failFast true` when one failure makes the rest pointless, and `stash`/`unstash` only for small artifacts — publish big ones to an artifact repository.\n11. **Always report and clean up.** `post { always { junit ...; archiveArtifacts artifacts: '...', fingerprint: true, allowEmptyArchive: true } cleanup { cleanWs() } }`. Test results are published even when the build fails; failure notifications go to the owning team, not everyone.\n12. **Untrusted changes get untrusted treatment.** Multibranch / PR jobs from forks must not run a modified `Jenkinsfile` with access to deploy credentials; use the trust settings so fork PRs use the target branch's Jenkinsfile, and keep deploy credentials off PR builds entirely.\n13. **Lint before merge.** Validate the Jenkinsfile with the Declarative linter (`jenkins-cli declarative-linter` or the pipeline-model-converter validate endpoint) or a Jenkinsfile Runner check in CI. Pipeline fixes go through a PR, not ad-hoc Replay edits that never reach the repo.\n\n## Workflow\n1. Inventory: current `Jenkinsfile`, shared libraries and versions, agent labels or pod templates, credentials IDs used, plugins relied on, and the slowest/most flaky stages from recent builds.\n2. Map stages to responsibilities (checkout, build, test, scan, package, publish, deploy) and move heavy logic into scripts or build-tool goals.\n3. Apply the rules above in order: agents and toolchain → options/bounds → credentials → `when`/gates → parallelism → post/cleanup → library pinning.\n4. Lint the result, run it on a branch (and on a PR from a branch, if multibranch), and compare duration and queue time to previous builds.\n5. PR notes: stage diagram, credentials touched (by ID only), agent/image changes, timeouts chosen, and anything that still needs a Jenkins admin (plugins, credential scope, trust settings).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/jenkins-pipeline.instructions.md` with `applyTo` for pipeline code (for example `**/Jenkinsfile`, `**/*.jenkinsfile`, `**/vars/*.groovy`, `**/src/**/*.groovy`, `**/jenkins/**/*.yaml`).\n- Always-on line in `.github/copilot-instructions.md`: \"Jenkinsfiles are Declarative glue: logic in scripts, agents by label or pod template, timeouts on every run, secrets via withCredentials in single-quoted sh only.\"\n- Optional `.github/skills/jenkins-declarative-pipeline-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/jenkins-declarative-pipeline-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Pipeline Groovy runs on the controller: keep `script {}` tiny, never interpolate credentials in Groovy strings, pin `@Library` versions.\"\n- Before claiming done, show the linter result and the final `options`, `agent`, and credential-binding blocks.\n\n### Codex\n- A Jenkins section in root `AGENTS.md`, or a nested `AGENTS.md` beside the shared library (or linked `docs/agents/jenkins-pipeline.md`).\n- State: how to lint the Jenkinsfile, which agent labels / pod templates exist, the approved credential IDs, banned patterns (Groovy-interpolated secrets, `Jenkins.instance`, unpinned libraries, builds on the controller), and the required `post` block.\n\n## Anti-patterns\n- `agent any` on a controller that still has executors\n- 300-line `script {}` blocks doing JSON parsing and loops on the controller\n- `sh \"curl -H 'Authorization: Bearer ${TOKEN}' ...\"` (Groovy interpolation of a secret)\n- `input` inside a stage that holds an agent for days\n- No `timeout`, no `buildDiscarder`, and a controller disk full of old artifacts\n- `@Library('team-lib@main')` or implicit-load libraries nobody reviews\n- Script approvals granted to make `Jenkins.instance` work\n- Fork PRs running a modified Jenkinsfile with production credentials in scope\n- Fixing pipelines with Replay and never committing the change\n\n## Verification checklist\n- [ ] Declarative syntax; `script {}` blocks small and justified\n- [ ] Heavy logic lives in scripts or build-tool goals\n- [ ] No builds on the controller; agents by label or pinned pod template/image\n- [ ] `timeout`, `buildDiscarder`, `timestamps`, and concurrency policy set\n- [ ] Credentials bound per stage; no Groovy-interpolated secrets; nothing echoed\n- [ ] Shared libraries pinned to a tag or commit; no sandbox bypasses\n- [ ] Approval gates use `agent none` + timeout; deploys guarded by `lock`/`milestone`\n- [ ] `post` publishes tests/artifacts and runs `cleanWs()`\n- [ ] Fork PRs cannot reach deploy credentials\n- [ ] Jenkinsfile passes the Declarative linter\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: jenkins-declarative-pipeline-guardrails\ndescription: Use when writing or reviewing a Jenkinsfile or Jenkins shared library — new stages, credentials, approvals, agents, or slow/hanging builds. Keep Declarative pipelines as thin glue with bounded runs, safe credential bindings, and pinned libraries.\n---\n\nFollow Jenkins Declarative Pipeline Guardrails: Declarative first with tiny script blocks, build logic in scripts and build tools, no builds on the controller, pinned agents and toolchains, timeout and buildDiscarder on every run, credentials via withCredentials in single-quoted sh, no sandbox bypasses, pinned @Library versions, approvals that don't hold agents, post blocks that publish results and clean the workspace, and a lint check before merge.\n```" } ] } From 1722e251f97a91f314d0207740f06bcfce0d0509 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:05:57 +0000 Subject: [PATCH 2/2] Add harden Jenkinsfile prompt --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index f5831af..e450afc 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -594,6 +594,26 @@ ], "formatNotes": "All three. Point the tool at the job entrypoint, the job/cluster config, and any saved `explain` output or Spark UI stage metrics (paste the top slow stages if logs are not in the repo). Copilot: spark-job-tuning path instructions plus those files in agent mode. Claude Code: the spark-job-tuning-guardrails skill plus the job file. Codex: AGENTS.md Spark performance section, then the diff.", "body": "Task: Diagnose and tune the Spark job I specify. Work from the physical plan and run metrics, apply the smallest set of changes that measurably helps, and give me a before/after comparison I can paste into the PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Job entrypoint: {{JOB_PATH}} (PySpark/Scala file, notebook, or SQL file)\n- Platform: {{PLATFORM}} (databricks | synapse | hdinsight | spark-on-k8s | other)\n- Spark version: {{SPARK_VERSION}}\n- Inputs: {{INPUTS}} (tables/paths with approximate size and format)\n- Output: {{OUTPUT}} (table/path, format, partition columns)\n- Symptom: {{SYMPTOM}} (sla-miss | straggler-tasks | spill | small-files | oom | cost)\n- Evidence available: {{EVIDENCE}} (spark-ui | event-logs | explain-output | run-history | none)\n- Cluster definition: {{CLUSTER}} (path to job/cluster config, or \"unknown\")\n- Target: {{TARGET}} (e.g. under 30 min, 40% less cost, no spill)\n\nRequirements:\n\n1. Inventory\n - Read {{JOB_PATH}} end to end: sources, filters, joins, aggregations, window functions, UDFs, `cache`/`persist`, `collect`/`toPandas`, and the final write\n - Current Spark configs set in code, job JSON, or {{CLUSTER}} (AQE flags, shuffle partitions, broadcast thresholds, memory)\n - {{OUTPUT}} layout: partition columns, typical file count and size, compaction schedule if any\n - Whether table statistics exist for {{INPUTS}}\n\n2. Diagnose\n - Produce or request `explain(mode=\"formatted\")` for the heaviest query; list each Exchange, join strategy, and whether pushdown/pruning reached the scan\n - From {{EVIDENCE}}: top three slowest stages with shuffle read/write, spill, task count, and max vs p75 task duration\n - Classify each hotspot: excess data read, wrong join strategy, skew, bad partition sizing, spill, small files, driver bottleneck, or Python UDF overhead\n - If {{EVIDENCE}}=none, say which metrics to capture first and give a ranked hypothesis list instead of tuning blindly\n\n3. Fix (one change per hotspot, in this order)\n - Prune columns and filter before joins/aggregations\n - Choose join strategy: broadcast only a reliably small side; align key types to avoid casts\n - Skew: rely on AQE skew-join first; for aggregations or hot keys AQE cannot split, use pre-aggregation, hot-key isolation, or salting — name the hot keys\n - Partition sizing: keep AQE on; set an initial partition count high enough for coalescing; target roughly 100–200 MB per shuffle partition\n - Writes: `REBALANCE`/`repartition` by output partition columns; no high-cardinality partition columns; add or note compaction\n - Remove unneeded `cache()`, unbounded `collect()`/`toPandas()`, and replace row-at-a-time Python UDFs with built-ins or pandas UDFs\n - Change cluster size only after the above, and only with metrics showing the job is resource-bound\n\n4. Verification\n - Re-run on representative data (same skew and file layout as prod); fill the before/after table\n - Show the new plan excerpt proving the intended join/shuffle change\n - Confirm output row counts and checksums match the baseline run\n - Note behavior under 2× input growth (broadcast size, partition count)\n\nConstraints:\n- Minimal diff; match the repo's existing job structure and config style.\n- Keep AQE enabled; every config added gets a comment with its evidence.\n- Do not invent table names, cluster IDs, workspace URLs, or data sizes — use placeholders if unknown.\n- Do not change business logic or output schema; correctness beats speed.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete code/config diffs and a checklist.\n\nOutput format:\n1. Hotspot table: stage | symptom | root cause | fix | expected impact\n2. Patch (job code + config diff)\n3. Before/after metrics: wall time, shuffle bytes, spill, max task time, output file count/size, cost if known\n4. Risks and follow-ups (data growth, stats refresh, compaction schedule)\n\nStart from {{JOB_PATH}}. Read the plan before changing any config.\n" + }, + { + "id": "harden-jenkinsfile", + "title": "Harden a Jenkinsfile", + "whenToUse": "Review a Jenkins pipeline for leaked-secret risks, controller-heavy Groovy, unbounded runs, and unpinned agents or libraries, and produce a minimal Declarative diff with lint output.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "jenkins", + "ci", + "devsecops", + "groovy", + "security", + "kubernetes" + ], + "formatNotes": "All three. Point the tool at the Jenkinsfile, any shared-library `vars/*.groovy` it loads, and the scripts its `sh` steps call; list credential IDs only, never secret values. Copilot: jenkins-pipeline path instructions plus those files in agent mode. Claude Code: the jenkins-declarative-pipeline-guardrails skill plus the Jenkinsfile. Codex: AGENTS.md Jenkins section, then the diff.", + "body": "Task: Review and harden the Jenkins pipeline I specify. Keep it Declarative, move heavy logic out of Groovy, make every run bounded and reproducible, and make sure no credential can leak — then give me a minimal diff I can open as a PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Pipeline file: {{JENKINSFILE_PATH}} (usually `Jenkinsfile`)\n- Job type: {{JOB_TYPE}} (multibranch | pipeline | organization-folder)\n- Build stack: {{BUILD_STACK}} (maven | gradle | docker | python | other)\n- Agents available: {{AGENTS}} (labels, Kubernetes pod templates, or \"unknown\")\n- Shared libraries: {{LIBRARIES}} (names and versions, or \"none\")\n- Credential IDs in use: {{CREDENTIAL_IDS}} (IDs only — never paste secret values)\n- Deploy targets: {{DEPLOY_TARGETS}} (e.g. aks-dev, aks-prod, artifact-repo, none)\n- Pain points: {{PAIN}} (hangs | slow | flaky | controller-load | secret-exposure | none)\n\nRequirements:\n\n1. Inventory\n - Read {{JENKINSFILE_PATH}} end to end: agent declarations, `options`, `environment`, every stage, `when` conditions, `script {}` blocks, `input` steps, `parallel`/`matrix`, `post`\n - List each credential binding, how the secret is referenced, and which stages can see it\n - List shared libraries and the version each is loaded at, plus any `Jenkins.instance` or other internal API use\n - Note how fork PRs are treated if {{JOB_TYPE}} is multibranch\n\n2. Findings (rank by risk: secret exposure > untrusted code with credentials > controller load > unbounded runs > reproducibility > hygiene)\n - Groovy-interpolated secrets (`\"${TOKEN}\"` inside `sh`), echoed secrets, `set -x` around secrets, secrets written to the workspace\n - Builds that can run on the controller, `agent any` without labels, unpinned images or tools\n - Large `script {}` blocks, Groovy JSON/XML parsing, loops of tiny `sh` calls\n - Missing `timeout`, `buildDiscarder`, `timestamps`, or concurrency policy\n - `input` holding an agent; deploys without `lock`/`milestone`; `if` logic that should be `when { ... beforeAgent true }`\n - Unpinned `@Library` refs, overridden built-in steps, sandbox bypasses\n - Missing `post` publishing (tests, artifacts with fingerprints) and workspace cleanup\n\n3. Fix\n - Declarative structure with `agent none` at the top only if every stage declares its own agent; otherwise one labelled agent or pod template\n - Move heavy logic into scripts (`scripts/ci/*.sh`) or build-tool goals ({{BUILD_STACK}}: e.g. `./mvnw -B -ntp verify`)\n - Top-level `options { timeout(...); buildDiscarder(logRotator(...)); timestamps(); disableConcurrentBuilds(abortPrevious: true) }` — adjust stage timeouts knowing they include agent provisioning when the agent is stage-level\n - Bind credentials per stage with `withCredentials` or `credentials()`; reference them only inside single-quoted `sh` strings\n - Approval stages: `agent none`, `input` with `timeout`, and `lock`/`milestone` on deploys to {{DEPLOY_TARGETS}}\n - Pin `@Library` to a tag or commit; replace `Jenkins.instance` use with a supported step or flag it for a plugin\n - `post { always { junit ...; archiveArtifacts ... fingerprint: true } cleanup { cleanWs() } }`\n - Keep deploy credentials out of PR and fork builds\n\n4. Verification\n - Run the Declarative linter (`jenkins-cli declarative-linter` or the validate endpoint) and include its output\n - Run on a branch build and, for multibranch, a PR build; compare duration and queue time with recent builds\n - Confirm in the console log that secrets show as masked and are never printed by a step\n - List anything that needs a Jenkins admin (plugins, credential scope, fork trust settings, agent templates)\n\nConstraints:\n- Minimal diff; keep stage names and artifacts unless a rename is needed for clarity.\n- Do not invent credential IDs, agent labels, image names, or URLs — use placeholders if unknown.\n- Never print or request secret values; refer to credentials by ID only.\n- Do not change what gets built or deployed; behaviour stays the same except for the safety fixes.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete Jenkinsfile diff and a checklist.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (Jenkinsfile diff plus any new scripts)\n3. Before/after: run duration, queue time, controller-side `script` lines, credentials scope per stage\n4. Admin follow-ups and residual risks\n\nStart from {{JENKINSFILE_PATH}}. Fix secret handling before anything else." } ] }