---
name: jenkins2gitlab-translate
description: Translate Jenkins pipelines (declarative/scripted Jenkinsfile, Job DSL, freestyle config.xml, shared libraries) into GitLab CI/CD (.gitlab-ci.yml, CI/CD components). Use when the user mentions Jenkins to GitLab migration, Jenkinsfile, Groovy pipeline, Job DSL, config.xml, Gerrit Trigger, shared library, or asks to convert/translate/port CI jobs to GitLab. Also covers fetching job definitions from a Jenkins controller, validating generated YAML against GitLab lint API and real runner tags, and authenticating via MCP, environment variables or ~/.netrc.
version: 1.0
source_article: jenkins2gitlab.md
---

# SKILL: jenkins2gitlab-translate

## 0. ROLE AND OUTPUT CONTRACT

ROLE: Pipeline translator. Input = Jenkins job definitions + controller context. Output = working GitLab CI YAML + migration notes.

GOAL: Same logic, same purpose. NOT a line-by-line copy. Prefer GitLab-native features over emulating Jenkins.

DELIVERABLES per translated job/repo:
1. `.gitlab-ci.yml` (or CI/CD component under `templates/<name>.yml` if source is a shared library).
2. `MIGRATION_NOTES.md` with sections: `## Mapped`, `## Changed behaviour`, `## TODO (human decision)`, `## Secrets to create`, `## Runner tags required`, `## Schedules to create`, `## Inbound callers to repoint`.
3. Validation report: lint result, tag check result, secret scan result.

NEVER:
- Copy encrypted Jenkins secrets (`{AQAAABAAAAAQ...}`, `{...}` blobs from `config.xml`/`credentials.xml`). They are bound to the old controller key. Useless and leaking.
- Put any secret value (plain or encrypted) in YAML, notes, commit messages, logs or chat output.
- Print, echo, log or commit tokens read from env vars or `~/.netrc`.
- Translate `label 'a || b'` into `tags: [a, b]` (GitLab tags = AND).
- Invent runner tags. Every tag must exist on a real runner (verify, section 7.2).
- Emit a pipeline without `workflow:rules` when the project has MRs + branches (duplicate pipelines).
- Delete Jenkins jobs. Only disable (human step, cutover phase).

ALWAYS:
- Ask for / fetch controller context, not only job files (section 3).
- Keep credential IDs only, as a list of secrets to recreate from their real source.
- Add `expire_in` to every `artifacts:`.
- Add `when: always` to artifacts carrying test reports.
- Set `GIT_DEPTH: 0` on jobs using `git describe`, `git log` counts, changelog generation, version-from-history.
- Mark every non-mappable construct as `# TODO(migration): <reason>` in YAML and in `MIGRATION_NOTES.md`.

## 1. AUTHENTICATION (ORDER OF PRECEDENCE)

Try in order. Stop at first that works. Never mix credentials of different users silently; report which method was used (method name only, never the value).

### 1.1 MCP servers
- If a GitLab MCP / Jenkins MCP server is configured and authenticated, use its tools first.
- If MCP returns auth error, needsAuth, 401/403, or is not configured -> fall through to 1.2.

### 1.2 Environment variables
GitLab (first non-empty wins):
- URL: `GITLAB_URL`, `GITLAB_HOST`, `CI_SERVER_URL`, `GL_HOST`
- Token: `GITLAB_TOKEN`, `GITLAB_PRIVATE_TOKEN`, `GL_TOKEN`, `PRIVATE_TOKEN`
- In CI only: `CI_JOB_TOKEN` (limited API scope; header `JOB-TOKEN`)
Jenkins:
- URL: `JENKINS_URL`
- User: `JENKINS_USER`, `JENKINS_USERNAME`
- Token: `JENKINS_API_TOKEN`, `JENKINS_TOKEN`
If missing or rejected (401/403) -> fall through to 1.3.

### 1.3 Local ~/.netrc (fallback)
Use when MCP cannot log in AND env vars are missing/invalid.
- Path: `$NETRC` if set, else `~/.netrc` (Windows: `%USERPROFILE%\_netrc`).
- Format: `machine <host> login <user> password <token>`.
- Match `machine` against the hostname (no scheme, no path) of GitLab / Jenkins URL. If URL unknown, list `machine` names only (NOT passwords) and ask the user which host is GitLab and which is Jenkins.
- Check file mode: if not `600`, warn the user; continue only read-only.
- Jenkins: HTTP Basic is supported -> `curl --netrc` (or `--netrc-file "$NETRC"`). Token never appears in argv.
- GitLab API: Basic auth is NOT accepted for REST API; read password field as PAT and send header `PRIVATE-TOKEN`. Do it inside a process (Python), not via shell interpolation, so the token stays out of argv and shell history.
- git over HTTPS reads `~/.netrc` automatically; no extra config needed.

Netrc helper (Python, stdlib only, token never printed):
```python
import json, netrc, os, sys, urllib.parse, urllib.request

def _netrc_auth(host):
    path = os.environ.get("NETRC") or os.path.expanduser("~/.netrc")
    a = netrc.netrc(path).authenticators(host)
    if not a:
        raise SystemExit(f"no netrc entry for {host}")
    login, _, password = a
    return login, password

def gitlab_api(base_url, path, method="GET", data=None):
    host = urllib.parse.urlparse(base_url).hostname
    token = (os.environ.get("GITLAB_TOKEN") or os.environ.get("GITLAB_PRIVATE_TOKEN")
             or _netrc_auth(host)[1])
    body = json.dumps(data).encode() if data is not None else None
    req = urllib.request.Request(f"{base_url.rstrip('/')}/api/v4{path}", data=body, method=method,
                                 headers={"PRIVATE-TOKEN": token, "Content-Type": "application/json"})
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read() or b"null")

def jenkins_get(base_url, path, raw=False):
    import base64
    host = urllib.parse.urlparse(base_url).hostname
    user = os.environ.get("JENKINS_USER"); tok = os.environ.get("JENKINS_API_TOKEN")
    if not (user and tok):
        user, tok = _netrc_auth(host)
    auth = base64.b64encode(f"{user}:{tok}".encode()).decode()
    req = urllib.request.Request(f"{base_url.rstrip('/')}{path}", headers={"Authorization": f"Basic {auth}"})
    with urllib.request.urlopen(req) as r:
        data = r.read()
        return data.decode() if raw else json.loads(data)
```

Shell equivalents (Jenkins only, netrc):
```bash
curl -fsS --netrc "$JENKINS_URL/api/json?tree=jobs[fullName,url,_class]"
curl -fsS --netrc "$JENKINS_URL/job/<folder>/job/<name>/config.xml" -o config.xml
```

If all three methods fail: stop network actions, continue offline with files the user provides, and list exactly which host lacks credentials.

## 2. WORKFLOW

```
[1 discover] -> [2 export context] -> [3 classify job] -> [4 translate] -> [5 harden] -> [6 validate] -> [7 report]
```

1. DISCOVER: locate sources in this order: `Jenkinsfile*` in repo, Job DSL `*.groovy` (seed jobs), shared library repo (`vars/*.groovy`, `src/**`, `resources/**`), exported `config.xml`, controller API (section 3).
2. EXPORT CONTEXT: plugins, nodes+labels, credential IDs, global env vars, global tool installations, shared library config, Vault config, last-run date per job.
3. CLASSIFY each job: `declarative` | `scripted` | `freestyle` | `matrix` | `multibranch` | `job-dsl` | `pipeline-from-scm` | `inline-pipeline-in-config.xml`. Also flag `dead` (no run in 90 days or no owner) -> recommend prune, do not translate unless told.
4. TRANSLATE using mapping tables (section 4-6) and skeleton (section 8). Merge all Jenkins jobs serving the same repo (check, post-merge, nightly, deploy) into ONE `.gitlab-ci.yml` with `rules:`.
5. HARDEN: checklist section 7.1.
6. VALIDATE: section 7.2 (lint, tags, secrets, YAML parse).
7. REPORT: deliverables from section 0.

Scale mode (many jobs): first write ONE golden reference pipeline by hand / with user approval, then use it as the style template for all others. Process jobs in batches per repo. Keep a progress table in `MIGRATION_NOTES.md`.

## 3. JENKINS CONTROLLER EXTRACTION (API)

| What | Endpoint |
|---|---|
| Job tree | `/api/json?tree=jobs[fullName,url,_class,jobs[fullName,url,_class,jobs[fullName,url,_class]]]` |
| Job config | `<job_url>config.xml` |
| Last build | `<job_url>lastBuild/api/json?tree=number,result,timestamp,duration` |
| Build params of last build | `<job_url>lastBuild/api/json?tree=actions[parameters[name,value]]` |
| Plugins | `/pluginManager/api/json?depth=1&tree=plugins[shortName,version,active]` |
| Nodes + labels | `/computer/api/json?tree=computer[displayName,offline,assignedLabels[name]]` |
| Credential IDs (no values) | `/credentials/store/system/domain/_/api/json?tree=credentials[id,typeName,description]` |
| Folder credentials | `<folder_url>credentials/store/folder/domain/_/api/json?tree=credentials[id,typeName]` |
| Global config (admin) | `/manage/configure` is UI-only; ask for JCasC export (`/manage/configuration-as-code/export`) if plugin installed |

`_class` hints:
- `org.jenkinsci.plugins.workflow.job.WorkflowJob` -> pipeline (inline script or SCM Jenkinsfile; check `<definition class=...CpsScmFlowDefinition>` vs `CpsFlowDefinition`).
- `hudson.model.FreeStyleProject` -> freestyle (builders under `<builders>`, publishers under `<publishers>`).
- `hudson.matrix.MatrixProject` -> matrix -> `parallel:matrix`.
- `org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject` -> multibranch -> one project with branch/MR rules.
- `com.cloudbees.hudson.plugins.folder.Folder` -> recurse.

From `config.xml` extract: `<triggers>` (cron, pollSCM, GerritTrigger, upstream), `<assignedNode>` (label expr), `<parameterDefinitions>`, `<builders>` shell/batch commands, `<publishers>` (junit, archiveArtifacts, email), `<buildWrappers>` (credentials binding, timestamps, timeout), `<logRotator>`/`buildDiscarder`, `<disabled>`, `<concurrentBuild>`.
IGNORE any `<secret>`, `<password>`, `{AQAAA...}` content.

If config.xml is stored in Git and mutated by Groovy init hooks: export the EFFECTIVE config.xml from the live controller and treat repo copy as non-authoritative.

## 4. KEYWORD MAPPING: DECLARATIVE -> GITLAB

| Jenkins | GitLab | Notes |
|---|---|---|
| `pipeline {}` | top-level `.gitlab-ci.yml` | |
| `agent any` | omit `tags:` only if some runner has "Run untagged jobs" enabled; else default tag | verify |
| `agent { label "${AXIS}" }` inside `matrix` | `tags: ["$AXIS"]` with `parallel:matrix` | matrix vars allowed in `tags:`/`image:` |
| `agent { label 'x' }` | `tags: [x]` | |
| `agent { label 'a && b' }` | `tags: [a, b]` | AND ok |
| `agent { label 'a \|\| b' }` | `tags: [<shared-capability-tag>]` | add shared tag on runners; TODO for runner admins |
| `agent { docker { image 'i' } }` | `image: i` | |
| `agent { dockerfile true }` | separate build-image job pushing to registry, then `image: $CI_REGISTRY_IMAGE/ci:$CI_COMMIT_SHA` | |
| `agent { kubernetes { yaml ... } }` | kubernetes executor runner + `image:` + `services:`; pod spec overrides need runner config | TODO |
| `agent none` + per-stage agent | per-job `image:`/`tags:` | |
| `environment { K = 'v' }` | `variables: K: v` | |
| `environment { K = credentials('id') }` | CI/CD variable `K` (masked, protected) or `secrets:` | list in notes |
| `parameters { string(name:'P', defaultValue:'d') }` | `spec: inputs: p: { default: d }` (17.11+) or `variables: P: { value: d, description: .. }` | |
| `booleanParam` | `spec: inputs: x: { type: boolean, default: false }` | |
| `choice(choices: [...])` | `spec: inputs: x: { options: [...], default: first }` | |
| `password(...)` param | never as input; CI/CD variable | |
| Active Choices / dynamic params | NO EQUIVALENT | TODO; propose static options or script-generated child pipeline |
| `options { timeout(time: N, unit: 'MINUTES') }` | job `timeout: Nm` (`default: timeout` needs GitLab 19.6 with its feature flag on) | job timeout <= runner timeout |
| `options { retry(N) }` | `retry: { max: min(N,2), when: [...] }` | GitLab max 2 |
| `options { disableConcurrentBuilds() }` | `resource_group:` on sensitive jobs; or `interruptible: true` + auto-cancel | |
| `options { disableConcurrentBuilds(abortPrevious: true) }` | `interruptible: true` + project setting auto-cancel redundant pipelines | |
| `options { buildDiscarder(logRotator(...)) }` | `artifacts: expire_in`; project CI/CD pipeline retention setting | notes |
| `options { skipDefaultCheckout() }` | `variables: GIT_STRATEGY: none` | |
| `options { timestamps() }` / `ansiColor` | drop (native) | |
| `options { checkoutToSubdirectory('d') }` | `GIT_CLONE_PATH: $CI_BUILDS_DIR/...` (runner `custom_build_dir` enabled) or `cd` | |
| `options { quietPeriod(n) }` | drop | |
| `options { preserveStashes() }` | drop | |
| `tools { maven 'M3'; jdk 'j17' }` | `image:` containing those versions | pin tag |
| `stages { stage('X') {...} }` | `stages: [x]` + jobs with `stage: x` | or DAG with `needs:` |
| nested `stages` in stage | flatten; use `needs:` | |
| `steps { sh 'cmd' }` | `script: [cmd]` | |
| `sh(returnStdout: true, script: 'c').trim()` | `VAR=$(c)` in script | |
| `sh(returnStatus: true, ...)` | `cmd \|\| rc=$?` | |
| `bat`/`powershell` | Windows runner, `script:` with powershell | tags windows |
| `echo 'x'` | `echo x` | |
| `dir('d') { ... }` | `cd d && ...` or `(cd d; ...)` | |
| `withEnv(['K=v']) {...}` | job `variables:` or `export K=v` | |
| `script { groovy }` | extract to `scripts/*.sh`/`*.py` in repo or tools image | |
| `error 'msg'` | `echo msg >&2; exit 1` | |
| `catchError(buildResult:'SUCCESS', stageResult:'FAILURE')` | `allow_failure: true` on that job | |
| `unstable('msg')` / `currentBuild.result = 'UNSTABLE'` | dedicated exit code + `allow_failure: { exit_codes: [N] }` | no unstable state in GitLab |
| `input message:'..'` | separate job `when: manual` (+ protected environment approvals, Premium) | Jenkins `input` holds an executor; GitLab manual job uses none until played |
| "Build Now" (manual run) | "New pipeline" (`$CI_PIPELINE_SOURCE == "web"`) or `when: manual` job | |
| `input` with parameters | manual job + variables entered at run, or `spec:inputs` | TODO |
| `milestone()` | `interruptible: true` | |
| `lock('res')` | `resource_group: res` | |
| `parallel { stage A; stage B }` | jobs A and B in same stage (or both with same `needs:`) | |
| `failFast true` | no direct equivalent | TODO; note |
| `matrix { axes {...} }` | `parallel: matrix: [{AX1: [..], AX2: [..]}]` | max 200 jobs; `excludes` -> rules on matrix vars |
| `stash name:'n', includes:'p'` | producer job `artifacts: { paths: [p], expire_in: 1 day }` | |
| `unstash 'n'` | consumer `needs: [producer]` (DAG, starts early) or `dependencies: [producer]` (keeps stage order, only selects artifacts) | choose consciously; note in `## Changed behaviour` if `needs` changes timing |
| `archiveArtifacts artifacts:'p', fingerprint:true` | `artifacts: paths: [p]` | fingerprinting: no equivalent, drop |
| keep build forever | `artifacts: expire_in: never` (release jobs only) or UI "Keep" | |
| discard old builds | `artifacts: expire_in: <duration>` + project pipeline retention | |
| `junit 'r/*.xml'` | `artifacts: { when: always, reports: { junit: r/*.xml } }` | |
| `publishHTML` | `artifacts: paths:` + `expose_as:` (or Pages) | |
| `jacoco`/`cobertura`/`recordCoverage` | `coverage: '/regex/'` + `artifacts: reports: coverage_report: { coverage_format: cobertura, path: .. }` | |
| `recordIssues` (warnings-ng) | `artifacts: reports: codequality:` (Code Climate JSON) | converter may be needed |
| `cleanWs()` / `deleteDir()` | drop (clean containers); shell runner: `GIT_CLEAN_FLAGS` | |
| `checkout scm` | implicit | |
| `git url:'other', credentialsId:..` | `git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@$CI_SERVER_HOST/group/other.git` | target project must allowlist this project (job token) |
| `build job: 'x', parameters: [...]` | `trigger: { project: group/x, branch: main, strategy: mirror }` (`depend` before 18.2) + `variables:` / or `trigger: include:` (child) | |
| `build job:` with `wait: false` | `trigger:` without `strategy:` | |
| `copyArtifacts(projectName:'x')` | `needs: [{ project: group/x, job: j, ref: main, artifacts: true }]` (Premium) or API `jobs/artifacts/:ref/download?job=` | |
| `post { always }` | `after_script:` (does not change status) or job `when: always` in later stage | |
| `post { success }` | job in later stage, default `when: on_success` | |
| `post { failure }` | job in later stage `when: on_failure` | |
| `post { unstable }` | n/a; use exit_code pattern | |
| `post { cleanup }` | `after_script:` | |
| `post { changed/fixed/regression }` | no equivalent; notification via GitLab integrations | TODO |
| `emailext`/`mail` | GitLab pipeline notifications / integration, or script with SMTP | |
| `slackSend` | Slack integration or `curl` webhook with masked var | |
| `sshagent(['id'])` | file-type variable `SSH_PRIVATE_KEY`; `eval $(ssh-agent -s); ssh-add "$SSH_PRIVATE_KEY"` | chmod 600 |
| `withCredentials([usernamePassword(...)])` | two masked variables `X_USER`,`X_PASS` | |
| `withCredentials([file(...)])` | file-type variable | |
| `withCredentials([string(...)])` | masked variable | |
| `withVault` / HashiCorp Vault plugin | `id_tokens` + `secrets: vault:` (Premium) or Vault CLI JWT login (Free) | section 6 |
| `withAWS(role:..)` | `id_tokens` + `aws sts assume-role-with-web-identity` | OIDC |
| `withKubeConfig` | file-type var `KUBECONFIG` or GitLab agent for Kubernetes | |
| `withSonarQubeEnv` | `image: sonarsource/sonar-scanner-cli`, vars `SONAR_HOST_URL`, `SONAR_TOKEN` | |
| `docker.build/push` | `docker:dind` service or kaniko/buildah; `$CI_REGISTRY*` vars | dind needs privileged runner |
| `docker.image('i').inside {}` | job with `image: i` | |
| `readJSON/readYaml/writeFile` | `jq`/`yq`/shell in tools image | |
| `currentBuild.displayName/description` | no direct; job name / `release` / MR note via API | drop |

## 5. TRIGGERS AND CONDITIONS

| Jenkins | GitLab |
|---|---|
| `triggers { cron('H 2 * * *') }` | pipeline schedule (UI/API, NOT YAML); job `rules: - if: $CI_PIPELINE_SOURCE == "schedule"`. Replace `H` with fixed minute. Add to notes `## Schedules to create` |
| `triggers { pollSCM(...) }` | drop (push events native) |
| `triggers { upstream('x') }` | in project x: `trigger:` job to this project; or pipeline subscriptions (Premium) |
| Remote trigger URL `/job/x/build?token=` | trigger token + `POST /projects/:id/trigger/pipeline`; `$CI_PIPELINE_SOURCE == "trigger"`. List caller in notes |
| Generic webhook trigger plugin | trigger token webhook URL `.../trigger/pipeline?token=..&ref=..`; payload in `$TRIGGER_PAYLOAD` (file) |
| Parameterized trigger (downstream with params) | `trigger:` job + job `variables:` (forwarded downstream) |
| `when { branch 'main' }` | `rules: - if: $CI_COMMIT_BRANCH == "main"` (prefer `$CI_DEFAULT_BRANCH`) |
| `when { branch pattern: 'release/*', comparator: 'GLOB' }` | `- if: $CI_COMMIT_BRANCH =~ /^release\//` |
| `when { tag 'v*' }` / `buildingTag()` | `- if: $CI_COMMIT_TAG =~ /^v/` |
| `when { changeRequest() }` | `- if: $CI_PIPELINE_SOURCE == "merge_request_event"` |
| `when { changeRequest target: 'main' }` | `... && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main"` |
| `when { changeset 'src/**' }` | `rules: - changes: [src/**/*]` (see caveat) |
| `when { environment name:'X', value:'v' }` | `- if: $X == "v"` |
| `when { expression { params.RUN_E2E } }` | `- if: $RUN_E2E == "true"` |
| `when { not {...} }` / `anyOf` / `allOf` | `!=`, `!~`, `\|\|`, `&&`, parentheses in `if:` |
| `allOf { branch 'x'; tag 'y' }` | IMPOSSIBLE in GitLab: tag pipelines have empty `CI_COMMIT_BRANCH`. Flag as TODO, ask intent (usually "tag on main" -> tag protection + `$CI_COMMIT_TAG` rule) |
| `when { environment name:'production' }` misread as GitLab env | NO: Jenkins `environment` condition checks a variable; never map to `$CI_ENVIRONMENT_NAME` |
| `when { triggeredBy 'TimerTrigger' }` | `$CI_PIPELINE_SOURCE == "schedule"` |
| `when { triggeredBy cause: 'UserIdCause' }` | `$CI_PIPELINE_SOURCE == "web"` |
| `beforeAgent true` | drop |

`changes:` caveat: on branch pipelines compares to the previous commit; always TRUE for new branches, tags, schedules, manual and API/trigger pipelines -> may run more often than Jenkins. In MR pipelines compares to target branch. Use `changes: { paths: [...], compare_to: refs/heads/main }` only with stable base. Note in `## Changed behaviour`.

### 5.1 Gerrit Trigger events
| Gerrit event | GitLab |
|---|---|
| `patchset-created` | `$CI_PIPELINE_SOURCE == "merge_request_event"` |
| `draft-published` / WIP removed | MR pipeline; optional `- if: $CI_MERGE_REQUEST_TITLE =~ /^Draft:/` -> `when: never` |
| `change-merged` | `- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"` |
| `ref-updated` | push pipeline on branch/tag rules |
| `comment-added` (e.g. "recheck") | retry pipeline from UI/API; no comment trigger -> TODO |
| Verified +1/-1 vote | "Pipelines must succeed" MR setting |
| Gerrit project/branch/file-path filters | `rules: if:` on branch + `changes:` |
| Gerrit topic (multi-repo change) | NO EQUIVALENT; TODO (multi-project pipeline or coordinated MRs) |
| `GERRIT_*` vars | section 5.2 |

### 5.2 Built-in variables
| Jenkins | GitLab |
|---|---|
| `BUILD_NUMBER` | `CI_PIPELINE_IID` (per project) or `CI_JOB_ID` |
| `BUILD_ID` | `CI_JOB_ID` |
| `BUILD_URL` | `CI_PIPELINE_URL` / `CI_JOB_URL` |
| `JOB_NAME` | `CI_PROJECT_PATH` + `CI_JOB_NAME` |
| `JOB_BASE_NAME` | `CI_JOB_NAME` |
| `WORKSPACE` | `CI_PROJECT_DIR` |
| `NODE_NAME` | `CI_RUNNER_DESCRIPTION` |
| `NODE_LABELS` | `CI_RUNNER_TAGS` |
| `EXECUTOR_NUMBER` | none |
| `JENKINS_URL` | `CI_SERVER_URL` |
| `GIT_COMMIT` | `CI_COMMIT_SHA` |
| `GIT_PREVIOUS_COMMIT` | `CI_COMMIT_BEFORE_SHA` (push only) |
| `GIT_BRANCH` / `BRANCH_NAME` | `CI_COMMIT_BRANCH` (empty in MR pipelines -> `CI_MERGE_REQUEST_SOURCE_BRANCH_NAME`); `CI_COMMIT_REF_NAME` covers tags |
| `TAG_NAME` | `CI_COMMIT_TAG` |
| `CHANGE_ID` | `CI_MERGE_REQUEST_IID` |
| `CHANGE_TARGET` | `CI_MERGE_REQUEST_TARGET_BRANCH_NAME` |
| `CHANGE_AUTHOR` | `CI_COMMIT_AUTHOR` / `GITLAB_USER_LOGIN` |
| `GERRIT_CHANGE_NUMBER` | `CI_MERGE_REQUEST_IID` |
| `GERRIT_PATCHSET_NUMBER` | none (use `CI_COMMIT_SHA`) |
| `GERRIT_BRANCH` | `CI_MERGE_REQUEST_TARGET_BRANCH_NAME` |
| `GERRIT_REFSPEC` | none; code is already checked out |
| `GERRIT_PROJECT` | `CI_PROJECT_PATH` |
| `env.X` / `params.X` in Groovy | `$X` in shell |
| `"${env.X}"` Groovy interpolation inside `sh` | plain shell `"$X"` |

## 6. SECRETS TRANSLATION

Decision order (simplest -> best):
1. CI/CD variable (masked + protected, optional `environment_scope`). Protected => only on protected branches/tags; ensure target branch protected.
2. Vault via OIDC: `id_tokens` + `secrets:` (Premium) or Vault CLI (Free).
3. Direct OIDC federation to target (cloud, k8s, internal API) -> no stored secret.

Per Jenkins credential ID produce one line in `## Secrets to create`:
`<credential_id> | <type: string|usernamePassword|file|sshKey|cert> | <proposed GitLab var name or vault path> | <scope: project|group> | <protected: yes/no> | <env scope> | owner: TODO`

Premium Vault:
```yaml
deploy:
  variables:
    VAULT_SERVER_URL: https://vault.example.com
    VAULT_AUTH_ROLE: <role>
  id_tokens:
    VAULT_ID_TOKEN:
      aud: https://vault.example.com
  secrets:
    DB_PASSWORD:
      vault: <path>/<field>@<mount>
      token: $VAULT_ID_TOKEN
      file: false
```
Free Vault:
```bash
export VAULT_ADDR=https://vault.example.com
export VAULT_TOKEN="$(vault write -field=token auth/jwt/login role=<role> jwt="$VAULT_ID_TOKEN")"
DB_PASSWORD="$(vault kv get -field=<field> <mount>/<path>)"
```
Create variable via API (value from stdin, never argv):
```bash
tr -d '\n' < secret.txt | curl -fsS --request POST --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
  "$GITLAB_URL/api/v4/projects/<url-encoded-path>/variables" \
  --form "key=NAME" --form "value=<-" --form "masked=true" --form "protected=true" --form "environment_scope=*"
```
Agent must NOT create variables with real values unless user explicitly provides the source and asks. Default: only list them.

## 7. HARDENING AND VALIDATION

### 7.1 Checklist (apply to every generated file)
- [ ] `workflow:rules` present; covers MR, tag, schedule/web/api/trigger/pipeline, branch; avoids duplicate branch+MR pipelines.
- [ ] Every `tags:` list matches >=1 real online runner (7.2).
- [ ] No OR-semantics hidden in tag lists.
- [ ] No secret values; no `{AQAAA`; no `password:`/`token:` literals.
- [ ] Every `artifacts:` has `expire_in`.
- [ ] Test report artifacts have `when: always`.
- [ ] `GIT_DEPTH: 0` where history needed.
- [ ] Deploy jobs: `environment:` + `resource_group:`; prod deploy restricted to default branch/tags AND to `$CI_PIPELINE_SOURCE == "push"` (a branch rule alone also matches schedule/web/api pipelines).
- [ ] Jobs needing infra access run on protected runner tags only and only from protected refs.
- [ ] `rules:` reproduce original trigger + branch + path filters (compare with source).
- [ ] `retry.max <= 2`.
- [ ] `parallel:matrix` <= 200 jobs.
- [ ] Cross-project clone/artifacts: job token allowlist noted.
- [ ] Large logs: note runner `output_limit` (default 4096 KB) if job prints a lot.
- [ ] Large artifacts: note max artifact size (default 100 MB self-managed).
- [ ] Cron -> schedule listed; remote trigger callers listed.
- [ ] Tier-gated features flagged (7.3).
- [ ] Shared logic as components/includes; no global `default:` inside components.

### 7.2 Validation commands
Lint (dry run simulates pipeline creation on default branch):
```python
res = gitlab_api(GITLAB_URL, f"/projects/{proj_id}/ci/lint", "POST",
                 {"content": open(".gitlab-ci.yml").read(), "dry_run": True, "include_jobs": True})
# check res["valid"], res["errors"], res["warnings"], res["jobs"]
```
Or `glab ci lint .gitlab-ci.yml` if glab authenticated.

Tag check:
- Project runners: `GET /projects/:id/runners?type=project_type` then `GET /runners/:id` -> `tag_list`, `status`.
- Group runners: `GET /groups/:id/runners?tag_list=a,b`.
- Instance (admin only): `GET /runners/all?tag_list=a,b`.
- For each job: set(job.tags) must be subset of some online runner's tag_list. Report missing combos.

Secret scan (local):
```bash
rg -n '\{AQAAA|-----BEGIN [A-Z ]*PRIVATE KEY|glpat-|glrt-|xox[bap]-|AKIA[0-9A-Z]{16}|password\s*[:=]\s*\S' .gitlab-ci.yml templates/ || echo "secret-scan: clean"
```
YAML parse: `python -c 'import yaml,sys; list(yaml.safe_load_all(open(sys.argv[1])))' .gitlab-ci.yml`.

Behaviour check (human-run, parallel phase): same commits built on Jenkins + GitLab; compare pass/fail, test count, duration, artifacts. Treat every difference as finding (e.g. Jenkins `|| true` + UNSTABLE hiding failures).

### 7.3 Tier-gated features (flag in notes, offer Free fallback)
Premium: `secrets:` (Vault), `needs:project`, merge trains, protected environments/deploy approvals, push rules, required approvals/Code Owners, specific users in "Allowed to push", environment-scoped group variables, pipeline subscriptions, LDAP/SAML group sync, SCIM.
Ultimate: custom roles.
Version: pipeline-level `spec:inputs` in `.gitlab-ci.yml` -> GitLab 17.11+. If older: use `variables:` with `description`/`options`.

## 8. TEMPLATES

### 8.1 Project skeleton (golden path baseline)
```yaml
spec:
  inputs:
    target_env:
      options: [staging, production]
      default: staging
---
variables:
  TARGET_ENV: $[[ inputs.target_env ]]

default:
  image: registry.example.com/build/toolchain:1.4
  tags: [linux-docker]
  interruptible: true                 # set timeout: per job

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_TAG
    - if: $CI_PIPELINE_SOURCE =~ /^(web|schedule|api|trigger|pipeline)$/
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH

stages: [verify, build, test, deploy]

lint:
  stage: verify
  script: make lint
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

build:
  stage: build
  script: make build
  artifacts:
    paths: [dist/]
    expire_in: 2 weeks

test:
  stage: test
  script: make test
  artifacts:
    when: always
    expire_in: 2 weeks
    reports:
      junit: reports/*.xml

deploy:
  stage: deploy
  interruptible: false
  environment: $TARGET_ENV
  resource_group: $TARGET_ENV
  script: ./deploy.sh "$TARGET_ENV"
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"
```

### 8.2 Shared library -> CI/CD component
Source:
```groovy
@Library('ci-lib@v2') _
standardBuild(goVersion: '1.22', runnerTag: 'linux-docker')
```
Component `templates/go-build.yml` in `org/platform/ci-components`:
```yaml
spec:
  inputs:
    stage:
      default: build
    go_version:
      default: "1.23"
    runner_tag:
      default: linux-docker
---
go-build:
  stage: $[[ inputs.stage ]]
  image: registry.example.com/mirror/golang:$[[ inputs.go_version ]]
  tags: ["$[[ inputs.runner_tag ]]"]
  script:
    - go build ./...
    - go test ./... -coverprofile=coverage.out
```
Consumer:
```yaml
include:
  - component: $CI_SERVER_FQDN/org/platform/ci-components/go-build@1.2.0
    inputs:
      go_version: "1.22"
```
Rules:
- `vars/<name>.groovy` with `call(Map cfg)` -> component `templates/<name>.yml`; map keys -> inputs.
- `@Library('lib@ref')` -> component `@<semver>`; never `@main` in production.
- `src/**` Groovy classes -> scripts in versioned tools image.
- `resources/**` -> files in component project, fetched via `include:` or baked into image.
- Library-injected global env -> group-level CI/CD variables.
- No `default:` block in components.

### 8.3 Scripted pipeline patterns
| Scripted | GitLab |
|---|---|
| `node('label') { ... }` | job with `tags:` |
| `stage('X') { ... }` inside node | job `stage: x` |
| `for (t in targets) { stage(t) {...} }` | `parallel: matrix: [{TARGET: [..]}]` |
| loop with targets computed at runtime | generator job writes `child.yml` artifact + `trigger: include: [{artifact: child.yml, job: gen}]` with `strategy: mirror` |
| `try { } catch(e) { } finally { }` | `script` + `after_script` + `when: on_failure` job |
| `if (env.BRANCH_NAME == 'main') { stage(...) }` | `rules:` on that job |
| `timeout(10) { }` | job `timeout: 10m` |
| `waitUntil {}` / `sleep` | shell loop with timeout |
| `parallel a: {..}, b: {..}` | jobs in same stage |
| `load 'x.groovy'` | include / script file |
| `properties([parameters(...), pipelineTriggers(...)])` | `spec:inputs` + schedules (notes) |

### 8.4 Freestyle config.xml patterns
| XML | GitLab |
|---|---|
| `<hudson.tasks.Shell><command>` | `script:` lines |
| `<hudson.tasks.BatchFile>` | Windows runner `script:` |
| `<assignedNode>expr</assignedNode>` | tags (OR rule!) |
| `<hudson.triggers.TimerTrigger><spec>` | schedule |
| `<hudson.triggers.SCMTrigger>` | drop |
| `<jenkins.triggers.ReverseBuildTrigger>` | upstream trigger |
| `<com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger>` | section 5.1; read `<gerritProjects>` for project/branch/file filters |
| `<hudson.tasks.junit.JUnitResultArchiver>` | junit report |
| `<hudson.tasks.ArtifactArchiver>` | artifacts |
| `<hudson.plugins.parameterizedtrigger.BuildTrigger>` | `trigger:` downstream |
| `<org.jenkinsci.plugins.credentialsbinding.impl.SecretBuildWrapper>` | variables list (IDs only) |
| `<hudson.plugins.build__timeout.BuildTimeoutWrapper>` | `timeout:` |
| `<concurrentBuild>false</concurrentBuild>` | `resource_group:` |
| `<logRotator>` | `expire_in` + notes |
| `<disabled>true</disabled>` | do not translate; mark dead |

### 8.5 Label OR fix (worked example)
Source: `agent { label 'linux && (build || build-prod)' }`
WRONG: `tags: [linux, build, build-prod]` (pending forever).
RIGHT: `tags: [linux-build]` + notes `## Runner tags required: add tag linux-build to all runners in pools build and build-prod`.

### 8.6 UNSTABLE fix (worked example)
Source: `sh 'make test || true'` + `junit` -> UNSTABLE.
RIGHT:
```yaml
test:
  script:
    - make test || exit 3
  allow_failure:
    exit_codes: [3]
  artifacts:
    when: always
    expire_in: 2 weeks
    reports:
      junit: reports/*.xml
```
Note in `## Changed behaviour`: previously hidden failures now visible; confirm with owner whether to keep `allow_failure`.

### 8.7 Extended example: parallel + matrix + stash + input + downstream (reference translation)
Source Jenkinsfile:
```groovy
pipeline {
  agent none
  triggers { cron('H 2 * * *') }
  stages {
    stage('Build') {
      agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
      steps {
        sh 'mvn -B package -DskipTests'
        stash name: 'jar', includes: 'target/*.jar'
      }
    }
    stage('Checks') {
      parallel {
        stage('Unit tests') {
          agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
          steps { sh 'mvn -B test' }
          post { always { junit 'target/surefire-reports/*.xml' } }
        }
        stage('Lint') {
          agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
          when { changeset '**/*.java' }
          steps { sh 'mvn -B checkstyle:check' }
        }
      }
    }
    stage('Integration') {
      matrix {
        axes {
          axis { name 'PLATFORM'; values 'linux-amd64', 'linux-arm64' }
          axis { name 'JDK'; values '17', '21' }
        }
        agent { label "${PLATFORM}" }
        stages {
          stage('IT') { steps { unstash 'jar'; sh "./it.sh --jdk ${JDK}" } }
        }
      }
    }
    stage('Release') {
      agent { label 'linux-amd64' }
      when { tag 'v*' }
      steps {
        input message: 'Deploy to production?'
        unstash 'jar'
        sh './deploy.sh production'
        archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
      }
    }
    stage('E2E') {
      when { branch 'main' }
      steps {
        build job: 'org/e2e-tests', wait: false,
              parameters: [string(name: 'APP_VERSION', value: env.GIT_COMMIT)]
      }
    }
  }
}
```
Target `.gitlab-ci.yml` (add `workflow:` from 8.1):
```yaml
default:
  image: maven:3.9-eclipse-temurin-21
  tags: [linux-docker]

stages: [build, checks, integration, release, e2e]

build:
  stage: build
  script: mvn -B package -DskipTests
  artifacts:                                  # stash 'jar'
    paths: [target/*.jar]
    expire_in: 1 week                         # must outlast the manual release

unit-tests:
  stage: checks                               # parallel with lint
  script: mvn -B test
  artifacts:
    when: always
    expire_in: 2 weeks
    reports:
      junit: target/surefire-reports/*.xml

lint:
  stage: checks
  script: mvn -B checkstyle:check
  rules:
    - changes: ["**/*.java"]

integration:
  stage: integration
  tags: ["$PLATFORM"]
  parallel:
    matrix:
      - PLATFORM: [linux-amd64, linux-arm64]
        JDK: ["17", "21"]
  needs: [build]                              # unstash; DAG start
  script: ./it.sh --jdk "$JDK"

release:
  stage: release
  tags: [linux-amd64]
  rules:
    - if: $CI_COMMIT_TAG =~ /^v/
      when: manual                            # input
  environment: production
  resource_group: production
  dependencies: [build]                       # unstash; keeps stage order
  script: ./deploy.sh production
  artifacts:
    paths: [target/*.jar]
    expire_in: never

e2e-tests:
  stage: e2e
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"
  variables:
    APP_VERSION: $CI_COMMIT_SHA
  trigger:
    project: org/e2e-tests
    branch: main
```
Notes to emit for this translation:
- `## Schedules to create`: nightly 02:xx on default branch (from `cron('H 2 * * *')`).
- `## Runner tags required`: `linux-docker`, `linux-amd64`, `linux-arm64`.
- `## Changed behaviour`: integration starts after build (not after checks) due to `needs`; `fingerprint` dropped; `lint` `changes:` true on new branches/schedules/tags; manual release holds no runner.
- Cross-project: `org/e2e-tests` must allow trigger from this project (Developer on target for triggering user).

## 9. UNSUPPORTED / ESCALATE TO HUMAN
Emit TODO, do not fake:
- Active Choices / dynamic/cascading parameters.
- Lockable resource pools with N devices (partial: `resource_group` per device + tags).
- Groovy console / controller automation, `Jenkins.instance` access, script approvals.
- `post { fixed/regression/changed }` semantics.
- `failFast` in parallel.
- Gerrit topics / cross-repo atomic submits.
- Comment-triggered rebuilds ("recheck").
- Build promotion plugins (map to environments + manual jobs; confirm).
- Per-job build history views, build monitor/radiator views (GitLab has no per-job history page; suggest API/Grafana).
- Anything relying on persistent workspace state between builds -> `cache:` design needed.
- Host-local scripts on agents (not in repo) -> must be moved into repo/image; ask owner.

## 10. AGENT RESPONSE FORMAT (TO USER)
1. One-line result: `<N> jobs -> <M> .gitlab-ci.yml files; lint: pass/fail; tags: ok/missing <list>; secrets: clean/found`.
2. Files written (paths).
3. TODO list requiring human decision (short).
4. Auth method used: `mcp` | `env` | `netrc` | `offline` (never the credential).
