From ac937270f6b80b01cb6675299af9b5906cc1f506 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:00:32 -0600 Subject: [PATCH 1/5] feat(op): a merge-request note activity, so findingMode "comment" works on GitLab (#2256) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `reconcilePr`'s `comment` mode posted onto a GitHub pull request and nothing else: it shelled to `gh`, read the pull request out of the Actions event payload, and the gitlab and forgejo generators refused the mode by name for want of anywhere to put the finding. The mode now also writes a GitLab merge-request note, by the same recipe and inside the same activity rather than a second one: the hidden marker is the body's first line, the next run finds the note by that prefix and PUTs it, and a merge request pushed to five times carries one note holding the current finding rather than five stale ones. Which forge a run is on is read off the run's own variables, not configured. Only a `merge_request_event` pipeline sets `CI_MERGE_REQUEST_IID`, so a run that has it is unambiguously the GitLab case and a GitHub run never reaches that branch. A merge request opened from a fork runs its pipeline in the fork, so the note goes on `CI_MERGE_REQUEST_PROJECT_ID` in preference to `CI_PROJECT_ID`. Two token headers, because GitLab reads two credentials from two of them: an access token in `PRIVATE-TOKEN`, the pipeline's own `CI_JOB_TOKEN` in `JOB-TOKEN`. The access token is preferred and the job token accepted last — GitLab's job-token allowlist does not reach the notes API on current versions, so a project that has not widened it needs a token with `api` scope, and one that has needs no long-lived credential at all. A run with a merge request and no token says which variable to set. Over `fetch` rather than a CLI: `gh` ships on GitHub's hosted runners and is already this activity's dependency, `glab` ships on no GitLab runner, and a finding step that needed it would fail on the `node:22-slim` image the generator emits. Also: `writeGatedRunSummary` gains a second surface. GitLab has no step summary at all — a job's surfaces are its log and its artifacts — so `CHANT_GATE_SUMMARY` names a path the generated job declares under `artifacts:`. The forge's own variable still wins where both are set. Refs #2231, #2243, #2084. --- packages/core/src/op/activities/index.ts | 9 +- .../core/src/op/activities/reconcile.test.ts | 238 +++++++++++++++ packages/core/src/op/activities/reconcile.ts | 280 +++++++++++++++++- packages/core/src/op/gate-summary.test.ts | 62 ++++ packages/core/src/op/gate-summary.ts | 22 +- 5 files changed, 592 insertions(+), 19 deletions(-) create mode 100644 packages/core/src/op/gate-summary.test.ts diff --git a/packages/core/src/op/activities/index.ts b/packages/core/src/op/activities/index.ts index 894c25d42d..9f70c7fb4e 100644 --- a/packages/core/src/op/activities/index.ts +++ b/packages/core/src/op/activities/index.ts @@ -43,7 +43,14 @@ export type { EnvTeardownArgs, EnvTeardownResult, EnvTeardownDeps } from "./env- // the registry imports this module statically, so a project that installs // nothing but chant still resolves every step below. -export { reconcilePr, commentMarker, pullRequestContextFrom, resolvePullRequestContext } from "./reconcile"; +export { + reconcilePr, + commentMarker, + pullRequestContextFrom, + resolvePullRequestContext, + mergeRequestContextFrom, + gitlabNoteTokenFrom, +} from "./reconcile"; export type { ReconcilePrArgs, ReconcileResult, ReconcileMode, ReconcileEntry, PullRequestContext } from "./reconcile"; export { nativeApply, compensateApply, hasNativeRollback } from "./apply"; diff --git a/packages/core/src/op/activities/reconcile.test.ts b/packages/core/src/op/activities/reconcile.test.ts index b229cb06a8..c2414af8cc 100644 --- a/packages/core/src/op/activities/reconcile.test.ts +++ b/packages/core/src/op/activities/reconcile.test.ts @@ -6,6 +6,8 @@ import { entriesFromPlan, commentMarker, pullRequestContextFrom, + mergeRequestContextFrom, + gitlabNoteTokenFrom, } from "./reconcile"; const entries = [ @@ -159,3 +161,239 @@ describe("reconcilePr comment mode refuses a run with no pull request (#2231)", } }); }); + +// ── The GitLab merge-request note (#2256) ─────────────────────────────────── + +describe("mergeRequestContextFrom (#2256)", () => { + const gitlabEnv = { + CI_API_V4_URL: "https://gitlab.com/api/v4", + CI_PROJECT_ID: "42", + CI_PROJECT_PATH: "acme/infra", + CI_PROJECT_URL: "https://gitlab.com/acme/infra", + CI_MERGE_REQUEST_IID: "7", + }; + + test("reads the merge request off a merge_request_event pipeline", () => { + expect(mergeRequestContextFrom(gitlabEnv)).toEqual({ + api: "https://gitlab.com/api/v4", + project: "42", + iid: 7, + path: "acme/infra", + webUrl: "https://gitlab.com/acme/infra", + }); + }); + + test("prefers the merge request's own project over the pipeline's", () => { + // A merge request from a fork runs its pipeline in the fork's project, + // and the note belongs on the target project's merge request. + expect( + mergeRequestContextFrom({ ...gitlabEnv, CI_MERGE_REQUEST_PROJECT_ID: "9" })?.project, + ).toBe("9"); + }); + + test("derives the API base from CI_SERVER_URL when CI_API_V4_URL is unset", () => { + const { CI_API_V4_URL: _drop, ...rest } = gitlabEnv; + expect(mergeRequestContextFrom({ ...rest, CI_SERVER_URL: "https://gl.example.com" })?.api).toBe( + "https://gl.example.com/api/v4", + ); + }); + + test("a push or scheduled GitLab pipeline has no merge request", () => { + const { CI_MERGE_REQUEST_IID: _drop, ...rest } = gitlabEnv; + expect(mergeRequestContextFrom(rest)).toBeUndefined(); + expect(mergeRequestContextFrom({ ...rest, CI_MERGE_REQUEST_IID: "" })).toBeUndefined(); + expect(mergeRequestContextFrom({ ...rest, CI_MERGE_REQUEST_IID: "not-a-number" })).toBeUndefined(); + }); + + test("a GitHub Actions run is not mistaken for a GitLab one", () => { + expect(mergeRequestContextFrom({ GITHUB_REPOSITORY: "INTENTIUS/chant", GITHUB_REF: "refs/pull/1/merge" })).toBeUndefined(); + }); +}); + +describe("gitlabNoteTokenFrom (#2256)", () => { + test("a project or personal access token is sent as PRIVATE-TOKEN", () => { + expect(gitlabNoteTokenFrom({ GITLAB_TOKEN: "glpat-x" })).toEqual({ + header: "PRIVATE-TOKEN", + value: "glpat-x", + source: "GITLAB_TOKEN", + }); + }); + + test("CHANT_GITLAB_TOKEN wins over GITLAB_TOKEN, which wins over the job token", () => { + expect( + gitlabNoteTokenFrom({ CHANT_GITLAB_TOKEN: "a", GITLAB_TOKEN: "b", CI_JOB_TOKEN: "c" })?.source, + ).toBe("CHANT_GITLAB_TOKEN"); + expect(gitlabNoteTokenFrom({ GITLAB_TOKEN: "b", CI_JOB_TOKEN: "c" })?.source).toBe("GITLAB_TOKEN"); + }); + + test("the job token is sent as JOB-TOKEN, which is a different header", () => { + expect(gitlabNoteTokenFrom({ CI_JOB_TOKEN: "c" })).toEqual({ + header: "JOB-TOKEN", + value: "c", + source: "CI_JOB_TOKEN", + }); + }); + + test("no token at all is undefined rather than an empty header", () => { + expect(gitlabNoteTokenFrom({})).toBeUndefined(); + expect(gitlabNoteTokenFrom({ GITLAB_TOKEN: "", CI_JOB_TOKEN: "" })).toBeUndefined(); + }); +}); + +/** One stubbed GitLab REST response. */ +function gitlabResponse(body: unknown, headers: Record = {}): Response { + return { + ok: true, + status: 200, + headers: { get: (name: string) => headers[name.toLowerCase()] ?? null }, + json: async () => body, + text: async () => JSON.stringify(body), + } as unknown as Response; +} + +describe("reconcilePr comment mode on GitLab posts one merge-request note (#2256)", () => { + const gitlabEnv: Record = { + CI_API_V4_URL: "https://gitlab.com/api/v4", + CI_PROJECT_ID: "42", + CI_PROJECT_PATH: "acme/infra", + CI_PROJECT_URL: "https://gitlab.com/acme/infra", + CI_MERGE_REQUEST_IID: "7", + GITLAB_TOKEN: "glpat-x", + }; + + function stubGitlabEnv(): void { + for (const [k, v] of Object.entries(gitlabEnv)) vi.stubEnv(k, v); + // A GitLab job carries none of GitHub's variables; make that explicit so + // the GitHub path can never be the one under test here. + for (const k of ["GITHUB_REPOSITORY", "GITHUB_REF", "GITHUB_EVENT_PATH"]) vi.stubEnv(k, ""); + } + + test("POSTs a new note carrying the marker as its first line", async () => { + stubGitlabEnv(); + const calls: Array<{ url: string; init?: RequestInit }> = []; + vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => { + calls.push({ url, init }); + if (!init?.method || init.method === "GET") return gitlabResponse([]); + return gitlabResponse({ id: 555 }); + }); + try { + const result = await reconcilePr({ env: "app", mode: "comment", body: "the plan" }); + expect(result.commentUrl).toBe("https://gitlab.com/acme/infra/-/merge_requests/7#note_555"); + expect(result.mergeRequest).toBe("acme/infra!7"); + const post = calls[calls.length - 1]; + expect(post.url).toBe("https://gitlab.com/api/v4/projects/42/merge_requests/7/notes"); + expect(post.init?.method).toBe("POST"); + expect((post.init?.headers as Record)["PRIVATE-TOKEN"]).toBe("glpat-x"); + expect(JSON.parse(String(post.init?.body)).body).toBe( + "\n\nthe plan", + ); + } finally { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + } + }); + + test("PUTs the note it already owns instead of stacking a second one", async () => { + stubGitlabEnv(); + const calls: Array<{ url: string; init?: RequestInit }> = []; + vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => { + calls.push({ url, init }); + if (!init?.method || init.method === "GET") { + return gitlabResponse([ + { id: 1, system: true, body: "changed the description" }, + { id: 2, system: false, body: "unrelated human note" }, + { id: 3, system: false, body: "\n\nan older plan" }, + ]); + } + return gitlabResponse({ id: 3 }); + }); + try { + const result = await reconcilePr({ env: "app", mode: "comment", body: "a newer plan" }); + const write = calls[calls.length - 1]; + expect(write.init?.method).toBe("PUT"); + expect(write.url).toBe("https://gitlab.com/api/v4/projects/42/merge_requests/7/notes/3"); + expect(result.commentUrl).toBe("https://gitlab.com/acme/infra/-/merge_requests/7#note_3"); + } finally { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + } + }); + + test("follows GitLab's own pagination rather than reading page one alone", async () => { + stubGitlabEnv(); + const seen: string[] = []; + vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => { + if (!init?.method || init.method === "GET") { + seen.push(url); + if (url.endsWith("page=1")) return gitlabResponse([{ id: 1, body: "nope" }], { "x-next-page": "2" }); + return gitlabResponse([{ id: 9, body: "\n\nold" }], { "x-next-page": "" }); + } + return gitlabResponse({ id: 9 }); + }); + try { + await reconcilePr({ env: "app", mode: "comment", body: "new" }); + expect(seen).toHaveLength(2); + expect(seen[1]).toContain("page=2"); + } finally { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + } + }); + + test("a rejected write fails the step by name, carrying GitLab's own status", async () => { + stubGitlabEnv(); + vi.stubGlobal("fetch", async (_url: string, init?: RequestInit) => { + if (!init?.method || init.method === "GET") return gitlabResponse([]); + return { + ok: false, + status: 403, + headers: { get: () => null }, + json: async () => ({}), + text: async () => '{"message":"403 Forbidden"}', + } as unknown as Response; + }); + try { + await expect(reconcilePr({ env: "app", mode: "comment", body: "plan" })).rejects.toThrow( + /merge_requests\/7\/notes.*403.*403 Forbidden/s, + ); + } finally { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + } + }); + + test("a merge-request pipeline with no token says which variable to set", async () => { + for (const [k, v] of Object.entries(gitlabEnv)) vi.stubEnv(k, k === "GITLAB_TOKEN" ? "" : v); + vi.stubEnv("CI_JOB_TOKEN", ""); + vi.stubEnv("CHANT_GITLAB_TOKEN", ""); + try { + await expect(reconcilePr({ env: "app", mode: "comment", body: "plan" })).rejects.toThrow( + /GITLAB_TOKEN.*CI_JOB_TOKEN/s, + ); + } finally { + vi.unstubAllEnvs(); + } + }); +}); + +describe("the no-context refusal names both forges' variables (#2256)", () => { + test("a run on neither forge is told what GitLab would have set too", async () => { + for (const k of [ + "GITHUB_REPOSITORY", + "GITHUB_REF", + "GITHUB_EVENT_PATH", + "CI_MERGE_REQUEST_IID", + "CI_PROJECT_ID", + "CI_API_V4_URL", + ]) { + vi.stubEnv(k, ""); + } + try { + await expect(reconcilePr({ env: "app", mode: "comment", body: "plan" })).rejects.toThrow( + /CI_MERGE_REQUEST_IID/, + ); + } finally { + vi.unstubAllEnvs(); + } + }); +}); diff --git a/packages/core/src/op/activities/reconcile.ts b/packages/core/src/op/activities/reconcile.ts index 2c8a73f4a2..9a9f8fa631 100644 --- a/packages/core/src/op/activities/reconcile.ts +++ b/packages/core/src/op/activities/reconcile.ts @@ -12,6 +12,13 @@ const execAsync = promisify(exec); * re-run (chant #2231). It therefore needs a pull-request trigger, and * {@link resolvePullRequestContext} fails the step by name when the run has * none. + * + * On GitLab the same mode writes a merge-request note (chant #2256): the same + * marker, the same edit-in-place, a different API. Which forge a run is on is + * read off the run's own CI variables rather than configured — a + * `merge_request_event` pipeline sets `CI_MERGE_REQUEST_IID`, a GitHub + * `pull_request` event sets `GITHUB_REPOSITORY`, and no run sets both. See + * {@link mergeRequestContextFrom}. */ export type ReconcileMode = "pull-request" | "issue" | "report" | "comment"; @@ -78,10 +85,12 @@ export interface ReconcileResult { prUrl?: string; /** Opened issue URL (issue mode). */ issueUrl?: string; - /** The posted or updated PR comment's URL (comment mode). */ + /** The posted or updated PR comment / MR note URL (comment mode). */ commentUrl?: string; - /** The pull request the comment landed on, `owner/repo#number` (comment mode). */ + /** The pull request the comment landed on, `owner/repo#number` (comment mode, GitHub). */ pullRequest?: string; + /** The merge request the note landed on, `group/project!iid` (comment mode, GitLab — #2256). */ + mergeRequest?: string; /** The markdown summary used as the PR/issue body. */ summary: string; /** The entries that triggered the reconcile. */ @@ -142,14 +151,17 @@ export function commentMarker(env: string): string { return ``; } -/** What a `comment`-mode step says when the run it is in has no pull request. */ +/** What a `comment`-mode step says when the run it is in has no pull request and no merge request. */ export function noPullRequestContextMessage(): string { return ( - 'reconcilePr mode "comment" posts the finding on the pull request that triggered the run, and this run ' + - "has none. It needs GITHUB_REPOSITORY plus a pull request number, read from the event payload at " + - "GITHUB_EVENT_PATH (`.number` / `.pull_request.number`) or from GITHUB_REF (`refs/pull//merge`). " + - "GitHub Actions sets those on a pull_request event and on nothing else. Trigger this Op from a " + - 'pull_request workflow, or give it findingMode "issue" or "report".' + 'reconcilePr mode "comment" posts the finding on the pull request or merge request that triggered the ' + + "run, and this run has none. On GitHub Actions it needs GITHUB_REPOSITORY plus a pull request number, " + + "read from the event payload at GITHUB_EVENT_PATH (`.number` / `.pull_request.number`) or from " + + "GITHUB_REF (`refs/pull//merge`), which a pull_request event sets and nothing else does. On GitLab " + + "CI it needs CI_MERGE_REQUEST_IID plus the project (CI_MERGE_REQUEST_PROJECT_ID or CI_PROJECT_ID) and " + + "the API base (CI_API_V4_URL, or CI_SERVER_URL to derive it), which a merge_request_event pipeline " + + "sets and nothing else does. Trigger this Op from a pull_request or merge_request pipeline, or give " + + 'it findingMode "issue" or "report".' ); } @@ -252,6 +264,226 @@ async function postOrUpdateComment( return stdout.trim(); } +// ── The GitLab merge-request note (#2256) ─────────────────────────────────── + +/** + * The merge request a `comment`-mode run posts its note onto (#2256), as a + * GitLab CI job knows it. The GitLab counterpart of {@link + * PullRequestContext}. + */ +export interface MergeRequestContext { + /** REST v4 base, from `CI_API_V4_URL` or derived from `CI_SERVER_URL`. */ + api: string; + /** The project holding the merge request — its numeric id, or a `group/project` path. */ + project: string; + /** The merge request's `iid` (its per-project number, which is what the API path takes). */ + iid: number; + /** `group/project`, for the human-readable `group/project!iid` on the result. */ + path?: string; + /** The project's web URL, used to build the note's own URL. */ + webUrl?: string; +} + +/** + * Derive the triggering merge request from a GitLab job's CI variables. Pure + * — exported for testing, and the whole forge detection: nothing but a + * `merge_request_event` pipeline sets `CI_MERGE_REQUEST_IID`, so a run that + * has it is on GitLab and has a merge request, and a run that does not is + * neither. + * + * The project is the merge request's own (`CI_MERGE_REQUEST_PROJECT_ID`) in + * preference to the pipeline's (`CI_PROJECT_ID`): a merge request opened from + * a fork runs its pipeline in the fork, and the note belongs on the target + * project's merge request rather than on an iid that means something else in + * the fork. + * + * Returns undefined rather than throwing, so the caller owns the message. + */ +export function mergeRequestContextFrom( + env: Record, +): MergeRequestContext | undefined { + const rawIid = env.CI_MERGE_REQUEST_IID?.trim(); + if (!rawIid) return undefined; + const iid = Number(rawIid); + if (!Number.isInteger(iid) || iid <= 0) return undefined; + + const server = env.CI_SERVER_URL?.trim().replace(/\/+$/, ""); + const api = env.CI_API_V4_URL?.trim().replace(/\/+$/, "") || (server ? `${server}/api/v4` : ""); + if (!api) return undefined; + + const project = + env.CI_MERGE_REQUEST_PROJECT_ID?.trim() || + env.CI_PROJECT_ID?.trim() || + env.CI_MERGE_REQUEST_PROJECT_PATH?.trim() || + env.CI_PROJECT_PATH?.trim() || + ""; + if (!project) return undefined; + + const path = env.CI_MERGE_REQUEST_PROJECT_PATH?.trim() || env.CI_PROJECT_PATH?.trim(); + const webUrl = env.CI_MERGE_REQUEST_PROJECT_URL?.trim() || env.CI_PROJECT_URL?.trim(); + return { + api, + project, + iid, + ...(path ? { path } : {}), + ...(webUrl ? { webUrl } : {}), + }; +} + +/** The credential a merge-request note is written with, and the header GitLab reads it from. */ +export interface GitlabNoteToken { + /** `PRIVATE-TOKEN` for a personal/project/group access token, `JOB-TOKEN` for `CI_JOB_TOKEN`. */ + header: "PRIVATE-TOKEN" | "JOB-TOKEN"; + value: string; + /** The variable it came from, so a refusal or a log line can name it. */ + source: string; +} + +/** + * Resolve the token a merge-request note is written with, most specific + * first. Pure — exported for testing. + * + * Two headers, not one, because GitLab reads two different credentials from + * two different headers: an access token goes in `PRIVATE-TOKEN`, and the + * pipeline's own ephemeral `CI_JOB_TOKEN` goes in `JOB-TOKEN`. Sending one in + * the other's header is a 401, not a fallback. + * + * The access token is preferred because it is the one that reliably works: + * `CI_JOB_TOKEN` reaches only the endpoints GitLab's job-token allowlist + * names, and the notes API is not among them on current GitLab, so a project + * that has not widened that allowlist needs a token with `api` scope. It is + * still accepted last rather than refused, so a project on an instance whose + * allowlist does cover notes needs no long-lived credential at all. + */ +export function gitlabNoteTokenFrom( + env: Record, +): GitlabNoteToken | undefined { + for (const source of ["CHANT_GITLAB_TOKEN", "GITLAB_TOKEN"]) { + const value = env[source]?.trim(); + if (value) return { header: "PRIVATE-TOKEN", value, source }; + } + const jobToken = env.CI_JOB_TOKEN?.trim(); + if (jobToken) return { header: "JOB-TOKEN", value: jobToken, source: "CI_JOB_TOKEN" }; + return undefined; +} + +/** What a `comment`-mode step says on a merge request it has no credential for. */ +export function noGitlabNoteTokenMessage(iid: number): string { + return ( + `reconcilePr mode "comment" has merge request !${iid} to post its finding on and no token to post it ` + + "with. Set a GITLAB_TOKEN CI/CD variable (masked, scope: api) on the project — a project access token " + + "is enough — or, on an instance whose job-token allowlist covers the notes API, make CI_JOB_TOKEN " + + "available to the job. CHANT_GITLAB_TOKEN is read first where the two must differ." + ); +} + +/** One page of merge-request notes, as much of each as this activity reads. */ +interface GitlabNote { + id: number; + body?: string; + /** GitLab's own generated notes ("changed the description"), never ours. */ + system?: boolean; +} + +/** GitLab's REST paths take a URL-encoded project id or `group%2Fproject` path. */ +function notesEndpoint(ctx: MergeRequestContext): string { + return `${ctx.api}/projects/${encodeURIComponent(ctx.project)}/merge_requests/${ctx.iid}/notes`; +} + +/** One GitLab REST call, with the failure spelled out rather than swallowed into a parse error. */ +async function gitlabRequest( + url: string, + token: GitlabNoteToken, + init: RequestInit, + signal?: AbortSignal, +): Promise { + const res = await fetch(url, { + ...init, + ...(signal ? { signal } : {}), + headers: { [token.header]: token.value, "content-type": "application/json" }, + }); + if (!res.ok) { + const detail = (await res.text().catch(() => "")).slice(0, 500); + throw new Error( + `GitLab API ${init.method ?? "GET"} ${url} answered ${res.status}${detail ? `: ${detail}` : ""} ` + + `(token from ${token.source}, sent as ${token.header}).`, + ); + } + return res; +} + +/** + * Find the note this Op already owns on `ctx`'s merge request, by the same + * hidden marker `postOrUpdateComment` looks a GitHub comment up by: the + * marker is the body's first line and the match is a prefix. + * + * Pages the way GitLab pages, following the `x-next-page` response header + * rather than guessing a page count — an active merge request runs past one + * page of notes routinely, and a lookup that read page one alone would post + * a second comment instead of editing the first. + * + * GitLab's own system notes are skipped: they are the activity feed + * ("changed the description"), they are never ours, and they are the bulk of + * what fills those pages. + */ +async function findOwnedNote( + ctx: MergeRequestContext, + token: GitlabNoteToken, + marker: string, + signal?: AbortSignal, +): Promise { + const endpoint = notesEndpoint(ctx); + // A merge request with more notes than this has something other than a + // stale plan comment wrong with it; the bound is what stops a broken + // `x-next-page` header from looping forever. + const MAX_PAGES = 50; + for (let page = 1; page <= MAX_PAGES; page++) { + const res = await gitlabRequest(`${endpoint}?per_page=100&page=${page}`, token, { method: "GET" }, signal); + const notes = (await res.json()) as GitlabNote[]; + const owned = notes.find((note) => !note.system && (note.body ?? "").startsWith(marker)); + if (owned) return owned.id; + const next = res.headers.get("x-next-page")?.trim(); + if (!next) return undefined; + } + return undefined; +} + +/** + * Post `body` as one note on `ctx`'s merge request, or edit the note this Op + * already owns there — {@link postOrUpdateComment}'s GitLab half, and the + * same recipe: find by marker, PUT when there is one, POST when there is not, + * so a merge request pushed to five times carries one note holding the + * current finding rather than five stale ones. + * + * Over `fetch` rather than a CLI. `gh` is on GitHub's hosted runners and is + * already this activity's dependency for the issue and pull-request modes; + * `glab` is on no GitLab runner by default, and a job whose finding step + * depended on it would fail on the ordinary `node:22-slim` image the + * generator emits. + */ +async function postOrUpdateNote( + ctx: MergeRequestContext, + token: GitlabNoteToken, + marker: string, + body: string, + signal?: AbortSignal, +): Promise { + const endpoint = notesEndpoint(ctx); + const existing = await findOwnedNote(ctx, token, marker, signal); + const payload = JSON.stringify({ body: `${marker}\n\n${body}` }); + const res = existing + ? await gitlabRequest(`${endpoint}/${existing}`, token, { method: "PUT", body: payload }, signal) + : await gitlabRequest(endpoint, token, { method: "POST", body: payload }, signal); + const note = (await res.json()) as GitlabNote; + // GitLab's note payload carries no web URL, unlike GitHub's comment. The + // anchor is how the UI itself addresses a note, so it is built rather than + // read; with no project web URL to build it from, the API path is at least + // a resolvable address for the thing that was written. + return ctx.webUrl + ? `${ctx.webUrl}/-/merge_requests/${ctx.iid}#note_${note.id}` + : `${endpoint}/${note.id}`; +} + /** * Map a `chant lifecycle plan --json` ChangeSet to reconcile entries, dropping * `noop` entries (nothing to reconcile). Pure — exported for testing. @@ -286,10 +518,13 @@ async function derivePlanEntries( * - `issue` — open a GitHub issue describing the drift (no code change). * - `comment` — post the body as one comment on the pull request that * triggered the run, editing that same comment on every re-run rather than - * stacking a new one (#2231). Needs a pull-request-triggered run; fails by - * name when there is none. No code change, and the `pull-requests: write` - * the generated workflow already grants on that trigger is the whole scope - * it spends. + * stacking a new one (#2231), or, on a GitLab `merge_request_event` + * pipeline, as one note on that merge request by the same recipe (#2256). + * Needs a pull-request- or merge-request-triggered run; fails by name when + * there is none. No code change, and the `pull-requests: write` the + * generated workflow already grants on that trigger is the whole scope it + * spends on GitHub; on GitLab the scope is whatever the token it is given + * carries. * - `pull-request` — create a branch, regenerate source via * `chant import --from `, commit, push, and open a PR whose diff is the * regenerated TypeScript. Never commits to the main branch. @@ -325,8 +560,27 @@ export async function reconcilePr(args: ReconcilePrArgs, signal?: AbortSignal): // The trigger context is read here rather than passed in: a step's args // are serialized at build time, and the pull request is not known until // the run. Missing context is fatal — see `noPullRequestContextMessage`. - const ctx = await resolvePullRequestContext(); const marker = args.marker ?? commentMarker(args.env); + + // GitLab first, because its check is the narrow one: only a + // `merge_request_event` pipeline sets `CI_MERGE_REQUEST_IID` (#2256), so + // a run that has it is unambiguously the GitLab case, and a GitHub run + // never reaches this branch. + const mr = mergeRequestContextFrom(process.env); + if (mr) { + const token = gitlabNoteTokenFrom(process.env); + if (!token) throw new Error(noGitlabNoteTokenMessage(mr.iid)); + const commentUrl = await postOrUpdateNote(mr, token, marker, summary, signal); + return { + mode, + summary, + entries, + commentUrl, + mergeRequest: `${mr.path ?? mr.project}!${mr.iid}`, + }; + } + + const ctx = await resolvePullRequestContext(); const commentUrl = await postOrUpdateComment(ctx, marker, summary, signal); return { mode, summary, entries, commentUrl, pullRequest: `${ctx.repo}#${ctx.number}` }; } diff --git a/packages/core/src/op/gate-summary.test.ts b/packages/core/src/op/gate-summary.test.ts new file mode 100644 index 0000000000..3c0a13dd71 --- /dev/null +++ b/packages/core/src/op/gate-summary.test.ts @@ -0,0 +1,62 @@ +/** + * The pending-gate block a CI run leaves where people actually look (#2243), + * and the second surface GitLab needs for it (#2256). + * + * GitHub Actions, Forgejo Actions and Gitea all hand a step a markdown + * scratchpad through `GITHUB_STEP_SUMMARY`. GitLab CI has no equivalent at + * all — a job's surfaces are its log and its artifacts — so `CHANT_GATE_SUMMARY` + * names a path the generated GitLab job also declares under `artifacts:`. One + * more environment variable, the same block, still no API call and no token. + */ + +import { mkdtempSync, readFileSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, test, expect } from "vitest"; +import { gatedRunSummaryMarkdown, writeGatedRunSummary } from "./gate-summary"; + +const summary = { op: "app-apply", gate: "approve-app-apply", expiresAt: "2026-09-08T00:00:00Z" }; + +function tempPath(name: string): string { + return join(mkdtempSync(join(tmpdir(), "chant-gate-")), name); +} + +describe("gatedRunSummaryMarkdown (#2243)", () => { + test("names the gate, the exact approve command and the ledger path", () => { + const md = gatedRunSummaryMarkdown(summary); + expect(md).toContain("Waiting on gate `approve-app-apply`"); + expect(md).toContain("chant approve app-apply approve-app-apply --approver "); + expect(md).toContain("_gates/app-apply.jsonl"); + }); +}); + +describe("writeGatedRunSummary surfaces (#2243, #2256)", () => { + test("writes to GITHUB_STEP_SUMMARY where the forge sets one", () => { + const path = tempPath("step-summary.md"); + expect(writeGatedRunSummary(summary, { GITHUB_STEP_SUMMARY: path })).toBe(path); + expect(readFileSync(path, "utf8")).toContain("approve-app-apply"); + }); + + test("writes to CHANT_GATE_SUMMARY where the forge sets none — GitLab's artifact path", () => { + const path = tempPath("chant-gate-app-apply.md"); + expect(writeGatedRunSummary(summary, { CHANT_GATE_SUMMARY: path })).toBe(path); + expect(readFileSync(path, "utf8")).toContain("chant approve app-apply approve-app-apply"); + }); + + test("the forge's own variable wins when both are set", () => { + const forge = tempPath("step-summary.md"); + const artifact = tempPath("chant-gate-app-apply.md"); + expect( + writeGatedRunSummary(summary, { GITHUB_STEP_SUMMARY: forge, CHANT_GATE_SUMMARY: artifact }), + ).toBe(forge); + expect(existsSync(artifact)).toBe(false); + }); + + test("a run with neither variable writes nothing and reports nothing", () => { + expect(writeGatedRunSummary(summary, {})).toBeUndefined(); + }); + + test("an unwritable path is swallowed: a decided run does not change outcome over a scratchpad", () => { + expect(writeGatedRunSummary(summary, { CHANT_GATE_SUMMARY: "/no/such/dir/gate.md" })).toBeUndefined(); + }); +}); diff --git a/packages/core/src/op/gate-summary.ts b/packages/core/src/op/gate-summary.ts index c7d4aa2830..498f99be63 100644 --- a/packages/core/src/op/gate-summary.ts +++ b/packages/core/src/op/gate-summary.ts @@ -8,9 +8,14 @@ * markdown scratchpad through `GITHUB_STEP_SUMMARY`, rendered at the top of * the run page; anything else that sets the variable gets the same block. * - * That is the whole forge coupling: one environment variable, appended to - * when it is set, and nothing at all when it is not. No API call, no token, - * no flag to turn it on. + * GitLab CI sets no such variable and has no step summary at all: a job's + * surfaces are its log and its artifacts (#2256). So `CHANT_GATE_SUMMARY` + * names a second path, which the generated GitLab job sets to a file it also + * declares under `artifacts:`. Same block, same rule, one more variable. + * + * That is the whole forge coupling: two environment variables, appended to + * whichever is set, and nothing at all when neither is. No API call, no + * token, no flag to turn it on. */ import { appendFileSync } from "node:fs"; @@ -63,7 +68,14 @@ export function gatedRunSummaryMarkdown(summary: GatedRunSummary): string { /** * Append {@link gatedRunSummaryMarkdown} to the file `GITHUB_STEP_SUMMARY` - * names, when the variable is set and the file can be written. + * names, or, where the forge sets no such variable, the one + * `CHANT_GATE_SUMMARY` names (#2256) — when it is set and the file can be + * written. + * + * The forge's own variable wins where both are set: a step summary is + * rendered on the run page, an artifact has to be downloaded, and writing + * both would put the same block in two places on a forge that already shows + * one of them. * * Returns the path written, or `undefined` when there was nothing to write to. * A write that fails is swallowed: a run that already decided its outcome must @@ -73,7 +85,7 @@ export function writeGatedRunSummary( summary: GatedRunSummary, env: NodeJS.ProcessEnv = process.env, ): string | undefined { - const path = env.GITHUB_STEP_SUMMARY; + const path = env.GITHUB_STEP_SUMMARY || env.CHANT_GATE_SUMMARY; if (!path) return undefined; try { appendFileSync(path, gatedRunSummaryMarkdown(summary)); From cbbcf9378cf5d156d530d18d11d0b432792113ee Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:06:22 -0600 Subject: [PATCH 2/5] feat(gitlab): the merge_request and push triggers on the op-pipeline generator (#2256) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The generator was cron-only and refused four things by name. Two of those refusals were wrong about GitLab rather than about chant. `GitLab has no pull_request/push event model` was the claim; `$CI_PIPELINE_SOURCE` distinguishes `merge_request_event` from `push` on every pipeline and `rules:` selects a job on either. So a `pull_request` trigger becomes a `merge_request_event` rule with the branch filter mapped to `$CI_MERGE_REQUEST_TARGET_BRANCH_NAME` — the branch the merge request would merge into, which is what github's `on.pull_request.branches` filters on too — and a `push` trigger becomes `$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == ""`, defaulting to the same `main` github's generator assumes. Two branches are two rule entries, because `rules:` is an OR over its list. A branch name carrying a quote, a `$` or a backslash is refused rather than interpolated, since either character silently changes which pipelines match. `findingMode "comment"` is no longer refused outright: there is a merge-request note activity to spend it now. What survives is the constraint github already has — the mode posts onto the merge request that triggered the run, so a cron or push job carrying it is refused by name at build time rather than emitted to fail at its Report step. What remains genuinely absent is in-file cron, so the cron path is unchanged and the header still says which Pipeline Schedules to create — only for the Ops that need one, rather than as a blanket instruction on a file that may carry none. Every job now carries a `resource_group`, GitLab's stand-in for github's per-Op concurrency group: one run at a time, queued rather than cancelled, which on an apply job is also what stops two runs racing for the same state lock. All jobs stay in one file: a GitHub trigger is workflow-scoped, a GitLab one is job-scoped. becomes the `id_tokens:` declaration the old refusal already named as the shape to reach for, audience `$CI_SERVER_URL`. `id-token: read` and every other scope are still refused, because GitLab has no per-job token-scope mapping and a dropped scope emits a job that reads as granted and runs with nothing. A `uses` setup step is still refused for want of any shape to translate it into. `--gated-exit 0`, so a pending approval is a green run; the human render is already in the job log, and `CHANT_GATE_SUMMARY` points core at a path the job also declares under `artifacts:`. No follow-up notice job: that would need a forge API call and a token a report-mode Op should not have to carry. Refs #2084, #2231, #2242, #2243. --- .../src/components/generate-op-pipeline.ts | 6 +- .../components/generate-op-pipeline.test.ts | 234 ++++++++- .../src/components/generate-op-pipeline.ts | 472 +++++++++++++----- lexicons/gitlab/src/plugin.ts | 3 +- packages/core/src/lexicon.ts | 13 +- 5 files changed, 561 insertions(+), 167 deletions(-) diff --git a/lexicons/github/src/components/generate-op-pipeline.ts b/lexicons/github/src/components/generate-op-pipeline.ts index c7550321c5..c3f25657c3 100644 --- a/lexicons/github/src/components/generate-op-pipeline.ts +++ b/lexicons/github/src/components/generate-op-pipeline.ts @@ -114,8 +114,10 @@ export interface GithubOpPipelineDoc { * Kept out of {@link jobsDoc} so a dialect that cannot run it drops it by * simply not copying it: the job shells to `gh` against the GitHub API and * needs `gh` on the runner, which is the same reason the `comment` finding - * mode is refused on forgejo and gitlab (#2231). {@link emitOpPipelineYAML} - * merges it into `jobs:` for the forges that can. + * mode is refused on forgejo (#2231). {@link emitOpPipelineYAML} merges it + * into `jobs:` for the forges that can. GitLab reaches the same outcome + * without this job at all: its push job writes the pending block to an + * artifact instead (#2256). */ gatedNoticeDoc?: Record; } diff --git a/lexicons/gitlab/src/components/generate-op-pipeline.test.ts b/lexicons/gitlab/src/components/generate-op-pipeline.test.ts index 70e4be2100..b653039852 100644 --- a/lexicons/gitlab/src/components/generate-op-pipeline.test.ts +++ b/lexicons/gitlab/src/components/generate-op-pipeline.test.ts @@ -70,33 +70,190 @@ describe("generateGitlabOpPipeline: one file, one job per scheduled Op", () => { }); }); -describe("generateGitlabOpPipeline: no pull_request/push event model (#2084)", () => { - test("a pull_request trigger throws a clear error instead of silently ignoring it", () => { - const specs: ScheduledOpSpec[] = [{ name: "tf-plan", trigger: { kind: "pull_request" } }]; - expect(() => generateGitlabOpPipeline(specs)).toThrow(/pull_request.*GitLab has no pull_request\/push event model/s); +/** + * #2084's trigger pair, now that GitLab has both events after all (#2256). + * + * The two refusals this replaces ("GitLab has no pull_request/push event + * model" on either trigger) were wrong about GitLab rather than about chant: + * `$CI_PIPELINE_SOURCE` distinguishes `merge_request_event` from `push` on + * every pipeline, and `rules:` selects a job on either. What is genuinely + * absent is in-file cron, which is why the cron path still runs off a + * project-level Pipeline Schedule and is unchanged below. + */ +describe("generateGitlabOpPipeline: the merge_request and push triggers (#2084, #2256)", () => { + test("a pull_request trigger becomes a merge_request_event rule filtered to the target branch", () => { + const result = generateGitlabOpPipeline([ + { name: "tf-plan", trigger: { kind: "pull_request", branches: ["main"] } }, + ]); + const job = parseYAML(result.files[0].yaml)["tf-plan"] as Record; + expect(job.rules).toEqual([ + { + if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main"', + }, + ]); }); - test("a push trigger throws a clear error instead of silently ignoring it", () => { - const specs: ScheduledOpSpec[] = [{ name: "tf-apply", trigger: { kind: "push" } }]; - expect(() => generateGitlabOpPipeline(specs)).toThrow(/push.*GitLab has no pull_request\/push event model/s); + test("an unfiltered pull_request trigger fires on every merge request", () => { + const result = generateGitlabOpPipeline([{ name: "tf-plan", trigger: { kind: "pull_request" } }]); + const job = parseYAML(result.files[0].yaml)["tf-plan"] as Record; + expect(job.rules).toEqual([{ if: '$CI_PIPELINE_SOURCE == "merge_request_event"' }]); + }); + + test("two target branches are two rules, which is how GitLab spells an OR", () => { + const result = generateGitlabOpPipeline([ + { name: "tf-plan", trigger: { kind: "pull_request", branches: ["main", "release"] } }, + ]); + const job = parseYAML(result.files[0].yaml)["tf-plan"] as { rules: Array<{ if: string }> }; + expect(job.rules.map((r) => r.if)).toEqual([ + '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main"', + '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "release"', + ]); + }); + + test("a push trigger becomes a push rule on the named branch", () => { + const result = generateGitlabOpPipeline([ + { name: "tf-apply", trigger: { kind: "push", branches: ["release"] } }, + ]); + const job = parseYAML(result.files[0].yaml)["tf-apply"] as Record; + expect(job.rules).toEqual([ + { if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "release"' }, + ]); + }); + + test("an unfiltered push trigger defaults to main, the same branch github's generator assumes", () => { + const result = generateGitlabOpPipeline([{ name: "tf-apply", trigger: { kind: "push" } }]); + const job = parseYAML(result.files[0].yaml)["tf-apply"] as { rules: Array<{ if: string }> }; + expect(job.rules[0].if).toBe('$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"'); + }); + + test("every job carries a resource_group, GitLab's own per-Op concurrency", () => { + // github's `concurrency: { group, cancel-in-progress: false }` queues a + // second run rather than cancelling the first, which is exactly what a + // resource_group does — and on an apply job it is also the thing that + // stops two runs racing for the same state lock. + const result = generateGitlabOpPipeline([ + { name: "tf-plan", trigger: { kind: "pull_request" } }, + { name: "tf-apply", trigger: { kind: "push" } }, + { name: "nightly", schedule: "0 6 * * *" }, + ]); + const parsed = parseYAML(result.files[0].yaml); + for (const name of ["tf-plan", "tf-apply", "nightly"]) { + expect((parsed[name] as Record).resource_group).toBe(name); + } + }); + + test("mixed triggers still land in one file, because a GitLab trigger is job-scoped", () => { + const result = generateGitlabOpPipeline([ + { name: "tf-plan", trigger: { kind: "pull_request", branches: ["main"] } }, + { name: "tf-apply", trigger: { kind: "push", branches: ["main"] } }, + { name: "nightly", schedule: "0 6 * * *" }, + ]); + expect(result.files).toHaveLength(1); + expect(result.jobs.map((j) => j.trigger.kind)).toEqual(["pull_request", "push", "cron"]); + }); + + test("the header sets up a Pipeline Schedule only for the Ops that need one", () => { + const yaml = generateGitlabOpPipeline([ + { name: "tf-plan", trigger: { kind: "pull_request", branches: ["main"] } }, + { name: "tf-apply", trigger: { kind: "push", branches: ["main"] } }, + ]).files[0].yaml; + // No cron Op here, so nothing has to be created in Settings > CI/CD. + expect(yaml).not.toContain("Pipeline Schedule"); + expect(yaml).toContain("merge_request_event onto main"); + expect(yaml).toContain("push to main"); + }); + + test("a branch name that would break out of the rule expression is refused by name", () => { + // A `rules:` if-expression is a string GitLab parses; a quote in a branch + // name would end it early and silently change which pipelines match. + expect(() => + generateGitlabOpPipeline([ + { name: "tf-plan", trigger: { kind: "pull_request", branches: ['main" || $CI_PIPELINE_SOURCE == "push'] } }, + ]), + ).toThrow(/branch/i); }); }); -describe("generateGitlabOpPipeline: no comment finding mode (#2231)", () => { - test("findingMode comment is refused by name, even on a cron trigger GitLab does support", () => { - const specs: ScheduledOpSpec[] = [ - { name: "app-plan", schedule: "0 6 * * *", findingMode: "comment" }, - ]; - expect(() => generateGitlabOpPipeline(specs)).toThrow( - /Scheduled Op "app-plan".*findingMode "comment".*GitLab has no pull_request event/s, - ); +/** + * #2231's finding mode, now that there is a GitLab merge-request note + * activity to spend it (#2256). The blanket refusal this replaces was about + * chant having no way to post the note; what remains is the same constraint + * github already has — the mode posts onto the merge request that triggered + * the run, so it needs a trigger that has one. + */ +describe("generateGitlabOpPipeline: the comment finding mode on a merge request (#2231, #2256)", () => { + test("findingMode comment is accepted on a pull_request trigger", () => { + const result = generateGitlabOpPipeline([ + { name: "app-plan", trigger: { kind: "pull_request", branches: ["main"] }, findingMode: "comment" }, + ]); + expect(result.jobs[0].findingMode).toBe("comment"); + const job = parseYAML(result.files[0].yaml)["app-plan"] as { rules: Array<{ if: string }> }; + expect(job.rules[0].if).toContain("merge_request_event"); + }); + + test("the header names the token the note is written with", () => { + const yaml = generateGitlabOpPipeline([ + { name: "app-plan", trigger: { kind: "pull_request" }, findingMode: "comment" }, + ]).files[0].yaml; + expect(yaml).toContain("GITLAB_TOKEN"); }); - test("the refusal names the modes GitLab does have", () => { - const specs: ScheduledOpSpec[] = [{ name: "app-plan", schedule: "0 6 * * *", findingMode: "comment" }]; - expect(() => generateGitlabOpPipeline(specs)).toThrow( - /findingMode "issue" or "merge-request"/, + test("findingMode comment on a cron trigger is refused, because a schedule has no merge request", () => { + expect(() => + generateGitlabOpPipeline([{ name: "app-plan", schedule: "0 6 * * *", findingMode: "comment" }]), + ).toThrow(/findingMode "comment".*trigger is "cron"/s); + }); + + test("findingMode comment on a push trigger is refused, naming the trigger", () => { + expect(() => + generateGitlabOpPipeline([ + { name: "app-plan", trigger: { kind: "push" }, findingMode: "comment" }, + ]), + ).toThrow(/findingMode "comment".*trigger is "push"/s); + }); +}); + +/** + * #2243's green-gated apply, in the two surfaces GitLab has: the job's own + * log, and an artifact. There is no step summary to write to and no + * cross-job output to publish, so there is also no follow-up job. + */ +describe("generateGitlabOpPipeline: a gated apply is a green run (#2243, #2256)", () => { + function applyJob(): Record { + const result = generateGitlabOpPipeline([ + { name: "app-apply", trigger: { kind: "push", branches: ["main"] } }, + ]); + return parseYAML(result.files[0].yaml)["app-apply"] as Record; + } + + test("the push job maps the gated exit code and nothing else", () => { + expect((applyJob().script as string[]).at(-1)).toBe("chant run app-apply --gated-exit 0"); + }); + + test("the pending gate is written to a path the job also publishes as an artifact", () => { + const job = applyJob(); + expect((job.variables as Record).CHANT_GATE_SUMMARY).toBe( + "chant-gate-app-apply.md", ); + expect(job.artifacts).toEqual({ + when: "always", + paths: ["chant-gate-app-apply.md"], + expire_in: "30 days", + }); + }); + + test("no other trigger is gated: a plan or a watch that stops is a signal, not noise", () => { + const result = generateGitlabOpPipeline([ + { name: "app-plan", trigger: { kind: "pull_request" } }, + { name: "nightly", schedule: "0 6 * * *" }, + ]); + const parsed = parseYAML(result.files[0].yaml); + for (const name of ["app-plan", "nightly"]) { + const job = parsed[name] as Record; + expect((job.script as string[]).at(-1)).toBe(`chant run ${name}`); + expect(job.artifacts).toBeUndefined(); + expect(job.variables).toBeUndefined(); + } }); }); @@ -161,12 +318,45 @@ describe("generateGitlabOpPipeline: setup steps and additive permissions (#2242) ]); }); - test("refuses additive permissions by name, and points at GitLab's own OIDC surface", () => { + /** + * `id-token: write` is the one additive scope that has a GitLab meaning + * (#2256): the refusal it replaces already named `id_tokens:` as the shape + * to reach for, and this reaches for it rather than describing it. Every + * other scope is still refused, because GitLab has no per-job token-scope + * mapping to put it in. + */ + test("id-token: write becomes an id_tokens declaration, GitLab's own OIDC surface", () => { + const result = generateGitlabOpPipeline([ + { + name: "app-apply", + trigger: { kind: "push", branches: ["main"] }, + permissions: { "id-token": "write" }, + }, + ]); + const job = parseYAML(result.files[0].yaml)["app-apply"] as Record; + expect(job.id_tokens).toEqual({ CHANT_ID_TOKEN: { aud: "$CI_SERVER_URL" } }); + }); + + test("an Op that adds no permissions declares no id_tokens", () => { + const result = generateGitlabOpPipeline([{ name: "actions-audit", schedule: "0 6 * * *" }]); + const job = parseYAML(result.files[0].yaml)["actions-audit"] as Record; + expect(job.id_tokens).toBeUndefined(); + }); + + test("id-token: read is refused: GitLab either mints the token or does not", () => { + expect(() => + generateGitlabOpPipeline([ + { name: "actions-audit", schedule: "0 6 * * *", permissions: { "id-token": "read" } }, + ]), + ).toThrow(/id-token: read/); + }); + + test("any other additive scope is still refused by name", () => { expect(() => generateGitlabOpPipeline([ - { name: "actions-audit", schedule: "0 6 * * *", permissions: { "id-token": "write" } }, + { name: "actions-audit", schedule: "0 6 * * *", permissions: { "pull-requests": "write" } }, ]), - ).toThrow(/adds permissions \{ id-token: write \}.*id_tokens:/s); + ).toThrow(/adds permission "pull-requests: write".*no per-job token-scope/s); }); }); diff --git a/lexicons/gitlab/src/components/generate-op-pipeline.ts b/lexicons/gitlab/src/components/generate-op-pipeline.ts index 85b4dd2fc4..5549324b0a 100644 --- a/lexicons/gitlab/src/components/generate-op-pipeline.ts +++ b/lexicons/gitlab/src/components/generate-op-pipeline.ts @@ -1,53 +1,77 @@ /** - * Generate mode — scheduled Op → GitLab CI YAML (#927). + * Generate mode — Op → GitLab CI YAML (#927, #2084, #2256). * * The Op counterpart to `./generate-pipeline.ts` (#563): that module * synthesizes a deploy-time component graph as one `.gitlab-ci.yml`; this one - * synthesizes a cron-triggered job per stateless Op. An Op's cadence is an - * `OpSchedule` on the Op itself (`packages/core/src/op/types.ts`), - * runtime-neutral data each reader interprets; this module is the reader that - * turns it into a GitLab pipeline schedule (`WorkflowAuditOp`/ - * `PipelineAuditOp`/`ReconcileOp` all accept an optional `schedule` precisely - * for this). + * synthesizes one job per Op, selected by its own `rules:`. + * + * What GitLab genuinely lacks is in-file cron. A schedule is a project-level + * object (Settings → CI/CD → Schedules) that runs the project's *existing* + * `.gitlab-ci.yml` with a chosen cron and CI/CD variables, so a cron-triggered + * Op becomes a job gated on `$CI_PIPELINE_SOURCE == "schedule"` plus a per-Op + * selector variable, and the generated file's header says what to set up. What + * GitLab does not lack, and what this generator wrongly refused until #2256, + * is the other two triggers (#2084): `$CI_PIPELINE_SOURCE` distinguishes + * `merge_request_event` from `push` on every pipeline, and `rules:` selects a + * job on either. So: + * + * - `cron` → `$CI_PIPELINE_SOURCE == "schedule" && $CHANT_SCHEDULED_OP == + * ""`, unchanged; + * - `pull_request` → `$CI_PIPELINE_SOURCE == "merge_request_event"`, with the + * branch filter mapped to `$CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, which is + * the branch the merge request would merge INTO — the same thing github's + * `on.pull_request.branches` filters on; + * - `push` → `$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == + * ""`, defaulting to the same `main` github's generator assumes. + * + * Two or more branches are two or more rule entries, because `rules:` is an + * OR over its entries and a regex alternation would need every branch name + * escaped into a pattern. + * + * Every job carries a `resource_group`, GitLab's stand-in for github's per-Op + * `concurrency` group: one run at a time per Op, the next one queued rather + * than cancelled. On an apply job that is also what stops two runs racing for + * the same state lock. + * + * Unlike github, all of this lands in ONE file. A GitHub trigger is + * workflow-scoped, so an Op there needs its own workflow; a GitLab trigger is + * job-scoped, so the whole set is one document with one job apiece. * - * Unlike GitHub Actions' per-workflow `on.schedule`, GitLab has no in-file - * cron at all — a schedule is a project-level object (Settings → CI/CD → - * Schedules) that runs the project's *existing* `.gitlab-ci.yml` with a - * chosen cron and CI/CD variables. So every scheduled Op here becomes one - * job in a single generated file, gated to run only under its own Pipeline - * Schedule (`$CI_PIPELINE_SOURCE == "schedule"` plus a per-op selector - * variable) — the cron itself is configured on the Pipeline Schedule, not in - * this YAML, and the generated file's header comment states what to set up. * Each job runs exactly one invocation, `chant run ` by default — never - * inlined audit/reconcile logic. The finding-mode itself is already baked - * into the Op's own activity args at build time by the composite that - * created it; GitLab has no per-job `permissions:` concept (unlike GitHub - * Actions), and `findingMode: "comment"` is refused by name here because it - * posts onto a GitHub pull-request event GitLab does not have (#2231), so a - * non-`report` mode's write access comes from whatever - * `GITLAB_TOKEN`/CI-CD-variable configuration the project already has — - * this generator documents the requirement rather than fabricating a - * variable nothing reads. + * inlined audit/reconcile logic. The finding-mode is already baked into the + * Op's own activity args at build time by the composite that created it; this + * generator only wires what the mode needs to act. * - * Neither of #2242's two per-Op options survives the crossing, and both are - * refused by name rather than dropped. A `setup` entry spelled `{ uses }` is - * a GitHub Actions marketplace action; GitLab CI has `script` and nothing - * else, so there is no shape to translate it into and no way to approximate - * `aws-actions/configure-aws-credentials` in a shell line. A `{ run }` entry - * translates exactly, and is emitted ahead of the `beforeScript` lines, the - * same position the github generator gives it. An additive `permissions` map - * is refused for the same reason `permissions:` is absent here at all: GitLab - * has no per-job token-scope mapping, and its OIDC surface is a different - * declaration (`id_tokens:` with an `aud`, exchanged for cloud credentials by - * the job itself) that chant does not generate. Ignoring the map would emit a - * job that reads as having OIDC and runs with no credentials. + * `findingMode: "comment"` works here since #2256: `reconcilePr` writes a + * merge-request note when the run is a `merge_request_event` pipeline, by the + * same hidden-marker edit-in-place recipe it uses on a GitHub pull request. + * What survives of the old blanket refusal is the constraint github already + * has — the mode posts onto the merge request that triggered the run, so a + * cron or push job carrying it is refused by name at build time rather than + * emitted to fail at its Report step ({@link assertTriggerSupportsMode}). + * GitLab has no per-job `permissions:` concept, so the note's write access + * comes from a `GITLAB_TOKEN` CI/CD variable, which the header names. + * + * #2242's two per-Op options cross over one and a half times. A `setup` entry + * spelled `{ uses }` is a GitHub Actions marketplace action; GitLab CI has + * `script` and nothing else, so there is no shape to translate it into and it + * is refused by name. A `{ run }` entry translates exactly, and is emitted + * ahead of the `beforeScript` lines — in `script:` rather than + * `before_script:`, which is where `./generate-pipeline.ts` puts the same + * option's lines in this same lexicon, and which concatenates identically at + * run time. An additive `permissions` map has exactly one entry with a GitLab + * meaning: `id-token: write` becomes an `id_tokens:` declaration ({@link + * idTokensFor}), the OIDC surface the old refusal already named as the shape + * to reach for. Every other scope is still refused, because there is no + * per-job token-scope mapping to put it in and a silently dropped scope emits + * a job that reads as granted and runs with nothing. * * A spec's `environment` (#2257) does cross, because GitLab has the concept * under the same key and with the same two fields: `environment: { name, url * }` on the job, an environment object in the project, and — on a protected * environment — an approval rule that holds the deployment job until an * approver releases it. So the reviewer gate the option exists for is - * expressible here, unlike the two #2242 options above, and it is emitted + * expressible here, unlike the `uses` setup step above, and it is emitted * rather than refused. What GitLab does not have is any way for this file to * declare the protection: an environment's approval rules are project * settings (Settings > CI/CD > Protected environments), exactly as GitHub's @@ -55,16 +79,17 @@ * the environment to protect the way it already names the schedule to create. * chant's own gate (#2119) runs inside the job either way. * - * The gated-apply mapping (#2243) has nothing to attach to here. It exists - * because a push-to-main apply that stops at its gate exits 3 and paints the - * branch red on every merge; this generator has no push pipeline at all, - * refusing a `push` trigger by name (#2084) because a GitLab schedule is a - * project-level cron object rather than an event. GitLab does have its own - * equivalent of the mapping should one ever be wanted — `allow_failure: - * { exit_codes: [3] }` turns one exit code into a warning rather than a - * failure, without a flag on the invocation — so the day this generator - * grows a push trigger, that is the shape to reach for rather than - * `--gated-exit`. + * The gated apply (#2243) lands in the two surfaces GitLab has. `chant run` + * returns 3 when a run stops at an unapproved gate, so a push-to-default apply + * would paint the branch red on every merge until someone approves; the push + * job runs with `--gated-exit 0`, mapping that one outcome and nothing else. + * Where GitHub Actions gets the pending block on its run page through + * `GITHUB_STEP_SUMMARY`, GitLab has no step summary at all, so the job sets + * `CHANT_GATE_SUMMARY` to a path it also declares under `artifacts:` and the + * block is downloadable from the pipeline. The human render is already in the + * job log, since the invocation carries no `--json`. There is no follow-up + * notice job: it would need a forge API call and a token this generator does + * not require of a `report`-mode Op. */ import { emitYAML } from "@intentius/chant/yaml"; @@ -75,9 +100,190 @@ import type { OpFindingMode, OpPipelineJob, OpPipelineResult as GenerateGitlabOpResult, + OpTrigger, ScheduledOpSpec, } from "@intentius/chant/lexicon"; +export type { GenerateGitlabOpOptions, GenerateGitlabOpResult }; + +/** GitLab CI job names must be safe YAML keys; Op names are already kebab-case in every fixture, but normalize defensively (mirrors `./generate-pipeline.ts`'s `toJobName`). */ +function toJobName(opName: string): string { + return opName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(); +} + +const DEFAULT_IMAGE = "node:22-slim"; +const STAGE = "scheduled-ops"; + +/** The CI/CD variable a Pipeline Schedule sets to select which job it runs. */ +const SELECTOR_VAR = "CHANT_SCHEDULED_OP"; + +/** + * Default branch assumed for a `push` trigger with no `branches` override. + * The same value github's generator documents, for the same reason: this + * operates on a `ScheduledOpSpec` rather than a git checkout, so it cannot + * read a downstream project's actual default branch. Set `trigger.branches` + * explicitly on a project whose default branch is something else. + */ +const DEFAULT_PUSH_BRANCH = "main"; + +/** The pipeline source GitLab reports for a merge-request pipeline. */ +const MERGE_REQUEST_SOURCE = '$CI_PIPELINE_SOURCE == "merge_request_event"'; + +/** + * The `id_tokens:` entry an `id-token: write` spec gets. The name is the + * environment variable the JWT lands in, which the job's own setup line reads + * (`aws sts assume-role-with-web-identity --web-identity-token + * "$CHANT_ID_TOKEN"`, or the provider's equivalent). + * + * `$CI_SERVER_URL` as the audience is GitLab's own documented default: an + * identity provider federated to a GitLab instance is registered with that + * instance's URL as its audience, and the variable expands to exactly that on + * gitlab.com and on a self-managed instance alike. A project whose provider + * was registered with some other audience edits the generated declaration. + */ +const ID_TOKEN_NAME = "CHANT_ID_TOKEN"; +const ID_TOKEN_AUDIENCE = "$CI_SERVER_URL"; + +/** + * `chant run` returns 3 when a run stops at an unapproved gate; `--gated-exit + * 0` maps that one outcome to success (#2243). `push` only — a cron watch or + * a merge-request plan that stops at a gate is a signal, not noise on a merge. + */ +const GATED_EXIT_FLAG = ["--gated-exit", "0"]; + +/** The variable core's `writeGatedRunSummary` writes the pending-gate block to when the forge sets no step summary (#2256). */ +const GATE_SUMMARY_VAR = "CHANT_GATE_SUMMARY"; + +/** How long a pending-gate artifact is worth keeping: long enough to outlive the approval it is waiting for. */ +const GATE_ARTIFACT_EXPIRY = "30 days"; + +/** + * Refuse a branch name that cannot be interpolated into a `rules:` + * if-expression. The expression is a string GitLab parses, so a `"` would end + * it early and a `$` would expand as a variable — either one silently changes + * which pipelines match the job, which is worse than not generating it. + */ +function assertBranchName(specName: string, branch: string): void { + if (branch.trim() === "") { + throw new Error( + `Scheduled Op "${specName}" has an empty branch filter. Name a branch, or drop the filter.`, + ); + } + if (/["$\\]/.test(branch)) { + throw new Error( + `Scheduled Op "${specName}" filters on branch "${branch}", which carries a character this generator ` + + `cannot put in a GitLab \`rules:\` expression: a quote would end the expression early and a "$" ` + + `would expand as a CI/CD variable, either of which silently changes which pipelines run the job. ` + + `Name a branch without \`"\`, \`$\` or \`\\\`.`, + ); + } +} + +/** + * This trigger's `rules:` entries. Two or more branches are two or more + * entries: `rules:` is an OR over its list, which is how GitLab spells the + * alternation github expresses as a `branches:` array. + */ +function rulesFor(spec: ScheduledOpSpec, trigger: OpTrigger): Array<{ if: string }> { + switch (trigger.kind) { + case "cron": + return [{ if: `$CI_PIPELINE_SOURCE == "schedule" && $${SELECTOR_VAR} == "${spec.name}"` }]; + case "pull_request": { + const branches = trigger.branches ?? []; + if (branches.length === 0) return [{ if: MERGE_REQUEST_SOURCE }]; + return branches.map((branch) => { + assertBranchName(spec.name, branch); + return { if: `${MERGE_REQUEST_SOURCE} && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "${branch}"` }; + }); + } + case "push": { + const branches = trigger.branches?.length ? trigger.branches : [DEFAULT_PUSH_BRANCH]; + return branches.map((branch) => { + assertBranchName(spec.name, branch); + return { if: `$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "${branch}"` }; + }); + } + } +} + +/** + * Refuse `findingMode: "comment"` on a trigger that has no merge request + * (#2231, #2256). The mode's activity reads the merge request out of the + * pipeline's own variables at run time, so a cron- or push-triggered job + * carrying it would generate fine and then fail on every run. Refusing here + * names the Op, the mode and the trigger at build time instead — the same + * refusal github's generator makes, on the same terms. + */ +function assertTriggerSupportsMode(name: string, mode: OpFindingMode, trigger: OpTrigger): void { + if (mode !== "comment" || trigger.kind === "pull_request") return; + throw new Error( + `Scheduled Op "${name}" has findingMode "comment", which posts its finding as a note on the merge ` + + `request that triggered the run, but its trigger is "${trigger.kind}". A ${trigger.kind} pipeline has ` + + `no merge request to post on. Give it a { kind: "pull_request" } trigger, or use findingMode "issue" ` + + `or "merge-request".`, + ); +} + +/** + * Turn a spec's additive `permissions` (#2242) into the one GitLab + * declaration that carries the same meaning, refusing everything else by name. + * + * `id-token: write` is that one: GitLab's OIDC surface is `id_tokens:`, a + * per-job declaration of a JWT the job exchanges for cloud credentials + * itself. `id-token: read` is refused rather than mapped, because GitLab + * either mints the token into the job or does not — there is no read-only + * half of it, and emitting the declaration for a spec that asked for read + * would hand the job more than it asked for. + * + * Every other scope is refused, unchanged from the pre-#2256 behaviour: + * GitLab has no per-job token-scope mapping at all, and a scope quietly + * dropped would emit a job that reads as granted and runs with nothing. + */ +function idTokensFor(spec: ScheduledOpSpec): Record | undefined { + let wantsIdToken = false; + for (const [rawScope, value] of Object.entries(spec.permissions ?? {})) { + const scope = rawScope.trim(); + if (scope === "id-token") { + if (value !== "write") { + throw new Error( + `Scheduled Op "${spec.name}" adds permission "id-token: ${value}", but GitLab either mints an ` + + `OIDC token into a job or does not — there is no read-only half of an \`id_tokens:\` ` + + `declaration. Ask for { "id-token": "write" }, or drop the option.`, + ); + } + wantsIdToken = true; + continue; + } + throw new Error( + `Scheduled Op "${spec.name}" adds permission "${scope}: ${value}", but GitLab CI has no per-job ` + + `token-scope mapping — there is no \`permissions:\` key to add it to (#2242). The one scope that ` + + `does cross over is "id-token": "write", which becomes an \`id_tokens:\` declaration. Drop the ` + + `option here, or generate this Op for github.`, + ); + } + return wantsIdToken ? { [ID_TOKEN_NAME]: { aud: ID_TOKEN_AUDIENCE } } : undefined; +} + +/** + * Refuse a `uses` setup step by name and return the `run` lines that do + * translate. See the module doc for why a marketplace action is a refusal + * rather than a silent drop. + */ +function gitlabSetupScript(spec: ScheduledOpSpec): string[] { + const lines: string[] = []; + (spec.setup ?? []).forEach((step, index) => { + if ("uses" in step) { + throw new Error( + `Scheduled Op "${spec.name}" setup step ${index + 1} is \`uses: "${step.uses}"\`, a GitHub Actions ` + + `marketplace action. GitLab CI jobs run \`script\` lines only, so there is nothing to translate it ` + + `into (#2242). Express the setup as a \`{ run }\` entry, or generate this Op for github/forgejo.`, + ); + } + lines.push(step.run); + }); + return lines; +} + /** * Validate a spec's `environment` (#2257) on GitLab's own terms. A GitLab job * naming an environment that does not exist creates an unprotected one on @@ -112,60 +318,11 @@ function assertGitlabEnvironment(name: string, environment: OpEnvironment): void } /** - * Refuse the two #2242 options GitLab cannot honour, by name and before any - * YAML exists, and return the `run` setup lines that do translate. See the - * module doc for why each one is a refusal rather than a silent drop. - */ -function gitlabSetupScript(spec: ScheduledOpSpec): string[] { - if (spec.permissions && Object.keys(spec.permissions).length > 0) { - const scopes = Object.entries(spec.permissions) - .map(([scope, value]) => `${scope}: ${value}`) - .join(", "); - throw new Error( - `Scheduled Op "${spec.name}" adds permissions { ${scopes} }, but GitLab CI has no per-job token-scope ` + - `mapping — there is no \`permissions:\` key to add them to (#2242). Its OIDC surface is a separate ` + - `\`id_tokens:\` declaration the job exchanges for cloud credentials itself, which chant does not ` + - `generate. Drop the option here, or generate this Op for github.`, - ); - } - const lines: string[] = []; - (spec.setup ?? []).forEach((step, index) => { - if ("uses" in step) { - throw new Error( - `Scheduled Op "${spec.name}" setup step ${index + 1} is \`uses: "${step.uses}"\`, a GitHub Actions ` + - `marketplace action. GitLab CI jobs run \`script\` lines only, so there is nothing to translate it ` + - `into (#2242). Express the setup as a \`{ run }\` entry, or generate this Op for github/forgejo.`, - ); - } - lines.push(step.run); - }); - return lines; -} - -export type { GenerateGitlabOpOptions, GenerateGitlabOpResult }; - -/** GitLab CI job names must be safe YAML keys; Op names are already kebab-case in every fixture, but normalize defensively (mirrors `./generate-pipeline.ts`'s `toJobName`). */ -function toJobName(opName: string): string { - return opName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(); -} - -const DEFAULT_IMAGE = "node:22-slim"; -const STAGE = "scheduled-ops"; - -/** The CI/CD variable a Pipeline Schedule sets to select which job it runs. */ -const SELECTOR_VAR = "CHANT_SCHEDULED_OP"; - -/** One setup line per Op in the generated file's header comment. */ -function setupLine(spec: ScheduledOpSpec, cron: string, jobName: string, mode: OpFindingMode): string { - const tokenNote = mode === "report" ? "" : " — needs a GITLAB_TOKEN CI/CD variable (masked, scope: api)"; - return `# ${jobName}: cron "${cron}", ${SELECTOR_VAR}="${spec.name}", finding-mode ${mode}${tokenNote}`; -} - -/** - * The follow-up line an Op with an `environment` adds under its setup line - * (#2257). The `environment:` key below binds the job to the environment; it - * cannot declare the approval rule, which is a project setting, so the header - * says where that is set the same way it says where the schedule is created. + * The follow-up line an Op with an `environment` adds under its own header + * line (#2257). The `environment:` key on the job binds it to the + * environment; it cannot declare the approval rule, which is a project + * setting, so the header says where that is set the same way it says where a + * schedule is created. */ function environmentLine(environment: OpEnvironment): string { return ( @@ -174,11 +331,41 @@ function environmentLine(environment: OpEnvironment): string { ); } +/** The artifact path a push job's pending-gate block is written to (#2243, #2256). */ +function gateSummaryPath(jobName: string): string { + return `chant-gate-${jobName}.md`; +} + +/** One line per Op in the generated file's header comment, naming what fires it. */ +function headerLineFor( + spec: ScheduledOpSpec, + trigger: OpTrigger, + jobName: string, + mode: OpFindingMode, +): string { + const tokenNote = + mode === "report" ? "" : " — needs a GITLAB_TOKEN CI/CD variable (masked, scope: api)"; + switch (trigger.kind) { + case "cron": + return `# ${jobName}: cron "${trigger.schedule}", ${SELECTOR_VAR}="${spec.name}", finding-mode ${mode}${tokenNote}`; + case "pull_request": { + const onto = trigger.branches?.length ? trigger.branches.join(", ") : "any branch"; + return `# ${jobName}: merge_request_event onto ${onto}, finding-mode ${mode}${tokenNote}`; + } + case "push": { + const branches = trigger.branches?.length ? trigger.branches : [DEFAULT_PUSH_BRANCH]; + return ( + `# ${jobName}: push to ${branches.join(", ")}, finding-mode ${mode}${tokenNote}` + + ` — a gated apply stays green, its pending gate in the log and in ${gateSummaryPath(jobName)}` + ); + } + } +} + /** - * Synthesize one `.gitlab-ci.yml` job per scheduled Op, all in a single file - * (GitLab has no per-file cron — see the module doc). Wired into core's Op - * generate mode via the gitlab lexicon plugin's `generateOpPipeline` - * (../plugin.ts). + * Synthesize one `.gitlab-ci.yml` job per Op, all in a single file (a GitLab + * trigger is job-scoped — see the module doc). Wired into core's Op generate + * mode via the gitlab lexicon plugin's `generateOpPipeline` (../plugin.ts). */ export function generateGitlabOpPipeline( ops: ScheduledOpSpec[], @@ -193,52 +380,39 @@ export function generateGitlabOpPipeline( const doc: Record = { stages: [STAGE] }; if (options.variables && Object.keys(options.variables).length > 0) doc.variables = options.variables; - const headerLines = [ - "# Scheduled Ops (chant #927) — GitLab has no in-file cron. Create one", - "# Pipeline Schedule per Op below (Settings > CI/CD > Schedules): set its", - `# cron to the value noted here and its ${SELECTOR_VAR} CI/CD variable to`, - "# the Op's name, so only that job runs on that schedule.", - "#", - ]; + const opLines: string[] = []; + let anyCron = false; for (const spec of ops) { const setupScript = gitlabSetupScript(spec); + const idTokens = idTokensFor(spec); const findingMode = spec.findingMode ?? "report"; - if (findingMode === "comment") { - // The mode posts onto the pull request that triggered the run (#2231), - // read out of the GitHub Actions event payload by `reconcilePr`. GitLab - // has neither that event model nor that payload, and core carries no - // GitLab API client that would post the merge-request note instead, so - // this refuses the mode by name rather than emitting a job whose finding - // step fails on every pipeline. - throw new Error( - `Scheduled Op "${spec.name}" has findingMode "comment", which posts its finding on the pull request ` + - `that triggered the run. GitLab has no pull_request event and chant has no GitLab merge-request ` + - `note activity (#2231). Use findingMode "issue" or "merge-request" here, or generate this Op for ` + - `github.`, - ); - } const trigger = resolveOpTrigger(spec); - if (trigger.kind !== "cron") { - throw new Error( - `Scheduled Op "${spec.name}" has a "${trigger.kind}" trigger, but GitLab has no pull_request/push event model ` + - `(#2084) — only a project-level Pipeline Schedule (cron). Give it a cron trigger, or generate it for github/forgejo instead.`, - ); - } + assertTriggerSupportsMode(spec.name, findingMode, trigger); + if (trigger.kind === "cron") anyCron = true; + const jobName = toJobName(spec.name); jobs.push({ jobName, op: spec.name, trigger, findingMode }); - headerLines.push(setupLine(spec, trigger.schedule, jobName, findingMode)); + opLines.push(headerLineFor(spec, trigger, jobName, findingMode)); if (spec.environment) { assertGitlabEnvironment(spec.name, spec.environment); - headerLines.push(environmentLine(spec.environment)); + opLines.push(environmentLine(spec.environment)); } + // A push job is the one a gate would otherwise paint red on every merge + // (#2243). Every other trigger keeps the plain one-line invocation. + const gated = trigger.kind === "push"; const runParts = runCommand.map((part) => part.replace("{name}", spec.name)); - const script = [...setupScript, ...beforeScript, runParts.join(" "), ...extraScript]; + const invocation = gated ? [...runParts, ...GATED_EXIT_FLAG] : runParts; + const gateSummary = gateSummaryPath(jobName); doc[jobName] = { stage: STAGE, image, + // GitLab's stand-in for github's per-Op concurrency group: queue the + // next run rather than cancel the current one. + resource_group: jobName, + ...(idTokens ? { id_tokens: idTokens } : {}), ...(spec.environment ? { environment: { @@ -247,11 +421,35 @@ export function generateGitlabOpPipeline( }, } : {}), - rules: [{ if: `$CI_PIPELINE_SOURCE == "schedule" && $${SELECTOR_VAR} == "${spec.name}"` }], - script, + ...(gated ? { variables: { [GATE_SUMMARY_VAR]: gateSummary } } : {}), + rules: rulesFor(spec, trigger), + script: [...setupScript, ...beforeScript, invocation.join(" "), ...extraScript], + // `when: always` because the run this publishes for is the green one: a + // gated apply succeeds, and the block is the only thing that says a + // human still has to act. A run that walked through its gate writes no + // block, and GitLab reports the empty upload as a warning, not a failure. + ...(gated + ? { artifacts: { when: "always", paths: [gateSummary], expire_in: GATE_ARTIFACT_EXPIRY } } + : {}), }; } + const headerLines = [ + "# chant Ops (#927, #2084) — one job per Op, each selected by its own", + "# rules:. A merge_request_event or push job needs no setup; its rule", + "# fires on the event itself.", + ]; + if (anyCron) { + headerLines.push( + "#", + "# GitLab has no in-file cron. Create one Pipeline Schedule per cron Op", + "# below (Settings > CI/CD > Schedules): set its cron to the value noted", + `# here and its ${SELECTOR_VAR} CI/CD variable to the Op's name, so only`, + "# that job runs on that schedule.", + ); + } + headerLines.push("#", ...opLines); + const sections: string[] = []; sections.push("stages:" + emitYAML(doc.stages, 1)); if (doc.variables) sections.push("variables:" + emitYAML(doc.variables, 1)); diff --git a/lexicons/gitlab/src/plugin.ts b/lexicons/gitlab/src/plugin.ts index 2254c3e87e..1218b2e8ec 100644 --- a/lexicons/gitlab/src/plugin.ts +++ b/lexicons/gitlab/src/plugin.ts @@ -30,7 +30,8 @@ export const gitlabPlugin: LexiconPlugin = { auditCatalog: () => gitlabAuditCatalog, // Generate mode (#688): synthesize a .gitlab-ci.yml from the component graph. generateComponentPipeline: (components, options) => generateGitlabPipeline(components, options), - // Generate mode, Op counterpart (#927): scheduled Op → GitLab CI job. + // Generate mode, Op counterpart (#927): an Op → one GitLab CI job, on a + // Pipeline Schedule, a merge request or a push (#2084, #2256). generateOpPipeline: (ops, options) => generateGitlabOpPipeline(ops, options), // Self-upgrade: where the pinned GitLab schema version lives + its upstream (#685). upstreamPin: { diff --git a/packages/core/src/lexicon.ts b/packages/core/src/lexicon.ts index 45f91b57bc..e11c48313d 100644 --- a/packages/core/src/lexicon.ts +++ b/packages/core/src/lexicon.ts @@ -494,10 +494,11 @@ export interface ComponentPipelineResult { * the generated job needs to act on a finding — elevated write access for * `issue`/`comment`/`pull-request`/`merge-request`, none for `report`. * - * `comment` posts the finding on the pull request that triggered the run - * (#2231), so unlike every other mode it constrains the trigger: the github - * generator refuses it by name on anything but `pull_request`, and the gitlab - * and forgejo generators refuse it outright. + * `comment` posts the finding on the pull request — or, on GitLab, the merge + * request (#2256) — that triggered the run, so unlike every other mode it + * constrains the trigger: the github and gitlab generators both refuse it by + * name on anything but `pull_request`. The forgejo generator refuses it + * outright, having no forge client to post the equivalent comment with. */ export type OpFindingMode = "report" | "issue" | "comment" | "pull-request" | "merge-request"; @@ -525,7 +526,9 @@ export type OpTrigger = * * A CI provider with no action concept degrades by name rather than * silently: the gitlab generator refuses a `uses` entry at build time and - * emits a `run` entry as an ordinary script line. + * emits a `run` entry as an ordinary script line. The additive `permissions` + * map degrades the same way there, with one exception: `id-token: write` + * becomes GitLab's own `id_tokens:` declaration (#2256). */ export type OpSetupStep = OpSetupUsesStep | OpSetupRunStep; From d0b486f6293b850044bbfcae850d63b8079bf9ab Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:18:23 -0600 Subject: [PATCH 3/5] test(gitlab): re-pin #2257's byte fixture over #2256's two moved lines #2257 pinned the whole emitted document for a cron Op with no `environment`, to prove its own option is additive. #2256 moves two things inside that pin: the header's opening paragraph, since the cron setup instructions are now printed only for the Ops that need a Pipeline Schedule, and `resource_group`, which every job gains. The pin is rewritten to the new bytes rather than loosened into a containment check, so it still proves what it was written to prove. The cron job's rule, script and stage are byte-for-byte unchanged. --- .../components/generate-op-pipeline.test.ts | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/lexicons/gitlab/src/components/generate-op-pipeline.test.ts b/lexicons/gitlab/src/components/generate-op-pipeline.test.ts index b653039852..933bf4c80d 100644 --- a/lexicons/gitlab/src/components/generate-op-pipeline.test.ts +++ b/lexicons/gitlab/src/components/generate-op-pipeline.test.ts @@ -372,13 +372,27 @@ describe("generateGitlabOpPipeline: setup steps and additive permissions (#2242) describe("generateGitlabOpPipeline: a deployment environment (#2257)", () => { const AUDIT: ScheduledOpSpec = { name: "actions-audit", schedule: "0 6 * * *", findingMode: "issue" }; - /** The document a spec with no `environment` emitted before the option existed. */ + /** + * The document a cron spec with no `environment` emits. #2257 pinned this to + * prove its option is additive; #2256 moved two lines of it and it is + * re-pinned rather than loosened, so it still proves the same thing. + * + * What moved: the header's opening paragraph, because a merge_request_event + * or push job needs no Pipeline Schedule and the cron instructions are now + * printed only for the Ops that do; and `resource_group`, which every job + * gains as GitLab's stand-in for github's per-Op concurrency group. The + * cron job's own rule, script and stage are byte-for-byte what they were. + */ const YAML_BEFORE_2257 = [ - "# Scheduled Ops (chant #927) — GitLab has no in-file cron. Create one", - "# Pipeline Schedule per Op below (Settings > CI/CD > Schedules): set its", - "# cron to the value noted here and its CHANT_SCHEDULED_OP CI/CD variable to", - "# the Op's name, so only that job runs on that schedule.", + "# chant Ops (#927, #2084) — one job per Op, each selected by its own", + "# rules:. A merge_request_event or push job needs no setup; its rule", + "# fires on the event itself.", + "#", + "# GitLab has no in-file cron. Create one Pipeline Schedule per cron Op", + "# below (Settings > CI/CD > Schedules): set its cron to the value noted", + "# here and its CHANT_SCHEDULED_OP CI/CD variable to the Op's name, so only", + "# that job runs on that schedule.", "#", '# actions-audit: cron "0 6 * * *", CHANT_SCHEDULED_OP="actions-audit", finding-mode issue' + " — needs a GITLAB_TOKEN CI/CD variable (masked, scope: api)", @@ -389,6 +403,7 @@ describe("generateGitlabOpPipeline: a deployment environment (#2257)", () => { "actions-audit:", " stage: scheduled-ops", " image: node:22-slim", + " resource_group: actions-audit", " rules:", ` - if: '$CI_PIPELINE_SOURCE == "schedule" && $CHANT_SCHEDULED_OP == "actions-audit"'`, " script:", From 87cb54ea568747a96a6671887ee9f13020a66679 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:23:05 -0600 Subject: [PATCH 4/5] docs(terraform): plan-on-pr gains a gitlab generation beside its github one (#2256) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The example shipped one CI shape and a paragraph saying the other forges refuse it. Both halves now generate for gitlab, and the suite asserts the emitted document field by field the way it already asserts the two workflows. Two things about the specs differ, and both are properties of the forge rather than of the example, which is why the example carries a second setup list instead of sharing one. The marketplace action becomes a shell line, because a GitLab job runs `script` and nothing else — and one that needs no AWS CLI: `id_tokens:` puts the OIDC JWT in an environment variable, and the AWS SDK inside the terraform provider does the AssumeRoleWithWebIdentity exchange itself once it has AWS_ROLE_ARN and a file to read the token from. Every `script` line runs in one shell, so an `export` on one line is still set on the next, which is exactly what a GitHub Actions `run:` step cannot do. Asserted: the two rules, one document rather than two, the per-Op resource_group, the id_tokens declaration and the absence of any `permissions:` block, the merge-request note mode and its refusal on the push half, the green gated apply with its log and artifact surfaces, the environment on the apply and not on the plan, and the refusal of the github `uses:` step rather than a silent drop. Also ratchets the docs prose baseline to the value #2257 left it below. Refs #2084, #2231, #2242, #2243, #2257. --- lexicons/terraform/examples/examples.test.ts | 208 ++++++++++++++++++ .../terraform/examples/plan-on-pr/README.md | 112 +++++++++- scripts/docs-sentences-baseline.json | 4 +- 3 files changed, 317 insertions(+), 7 deletions(-) diff --git a/lexicons/terraform/examples/examples.test.ts b/lexicons/terraform/examples/examples.test.ts index c6cd5d0ddb..6479f9fabc 100644 --- a/lexicons/terraform/examples/examples.test.ts +++ b/lexicons/terraform/examples/examples.test.ts @@ -203,6 +203,89 @@ const APPLY_SPEC: ScheduledOpSpec = { environment: { name: APPLY_ENVIRONMENT }, }; +/** + * The same pair on GitLab (#2256). Two things differ from the github specs + * above, and both are properties of the forge rather than of the example. + * + * The AWS auth is a shell line rather than a marketplace action, because + * GitLab CI jobs run `script` and nothing else. It needs no AWS CLI either: + * GitLab's `id_tokens:` puts the OIDC JWT in an environment variable, and the + * AWS SDK inside the terraform provider does the `AssumeRoleWithWebIdentity` + * exchange itself when it is handed `AWS_ROLE_ARN` and a + * `AWS_WEB_IDENTITY_TOKEN_FILE` to read the token out of. Every `script` line + * in a GitLab job runs in one shell, so an `export` on one line is still set + * on the next — which is exactly what a GitHub Actions `run:` step cannot do, + * and why the same setup is an action there. + * + * The role ARN is a plain `$AWS_PLAN_ROLE_ARN`, because a GitLab CI/CD + * variable is already in the job's environment; there is no `${{ vars.X }}` + * expression to interpolate at generation time. + */ +const GITLAB_TOKEN_FILE = "/tmp/chant-web-identity-token"; + +function assumeRoleOnGitlab(roleVariable: string): ScheduledOpSpec["setup"] { + return [ + { + run: + `echo "$CHANT_ID_TOKEN" > ${GITLAB_TOKEN_FILE} && ` + + `export AWS_ROLE_ARN="$${roleVariable}" ` + + `AWS_WEB_IDENTITY_TOKEN_FILE=${GITLAB_TOKEN_FILE} ` + + `AWS_REGION=${AWS_REGION}`, + }, + ]; +} + +const GITLAB_PLAN_SPEC: ScheduledOpSpec = { + name: "app-plan", + trigger: { kind: "pull_request", branches: ["main"] }, + findingMode: "comment", + setup: assumeRoleOnGitlab("AWS_PLAN_ROLE_ARN"), + permissions: { "id-token": "write" }, +}; + +const GITLAB_APPLY_SPEC: ScheduledOpSpec = { + name: "app-apply", + trigger: { kind: "push", branches: ["main"] }, + setup: assumeRoleOnGitlab("AWS_APPLY_ROLE_ARN"), + permissions: { "id-token": "write" }, + environment: { name: APPLY_ENVIRONMENT }, +}; + +/** + * The GitLab generation is one document, not two: a GitHub trigger is + * workflow-scoped, so each Op needs its own file, while a GitLab trigger is + * job-scoped and both jobs live in one `.gitlab-ci.yml`. + */ +async function planOnPrGitlabPipeline(): Promise { + const result = await generateOpsPipeline( + [GITLAB_PLAN_SPEC, GITLAB_APPLY_SPEC], + "gitlab", + { beforeScript: [INSTALL_TERRAFORM] }, + planOnPrDir, + ); + expect(result.error).toBeUndefined(); + expect(result.success).toBe(true); + expect(result.files, "one document, both jobs").toHaveLength(1); + return result.files![0].yaml; +} + +/** One GitLab job, as much of it as this suite reads back. */ +interface GitlabJob { + stage: string; + image: string; + resource_group: string; + rules: Array<{ if: string }>; + script: string[]; + id_tokens?: Record; + variables?: Record; + environment?: Record; + artifacts?: { when: string; paths: string[]; expire_in: string }; +} + +function gitlabJobs(yaml: string): Record { + return parseYAML(yaml) as unknown as Record; +} + async function planOnPrWorkflows(): Promise<{ plan: string; apply: string }> { const result = await generateOpsPipeline( [PLAN_SPEC, APPLY_SPEC], @@ -561,6 +644,131 @@ describe("plan-on-pr generates the pull_request plan and push apply pair (#2221) expect(applyOp.props.phases.map((p) => p.name)).toContain("Gate"); }); + // ── The same pair on GitLab (#2256) ──────────────────────────────────── + + it("plans on a merge request and applies on a push, both in one document", async () => { + const jobs = gitlabJobs(await planOnPrGitlabPipeline()); + // The branch filter maps onto the branch the merge request would merge + // INTO, which is what github's `on.pull_request.branches` filters on too. + expect(jobs["app-plan"].rules).toEqual([ + { + if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main"', + }, + ]); + expect(jobs["app-apply"].rules).toEqual([ + { if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"' }, + ]); + // One run at a time per Op, which on the apply is also the state lock. + expect(jobs["app-plan"].resource_group).toBe("app-plan"); + expect(jobs["app-apply"].resource_group).toBe("app-apply"); + }); + + it("posts the plan as a merge-request note, and refuses the mode where there is no merge request", async () => { + const result = await generateOpsPipeline( + [GITLAB_PLAN_SPEC, GITLAB_APPLY_SPEC], + "gitlab", + {}, + planOnPrDir, + ); + expect(result.jobs?.[0]).toEqual({ + jobName: "app-plan", + op: "app-plan", + trigger: { kind: "pull_request", branches: ["main"] }, + findingMode: "comment", + }); + // The Op is the same one github runs: one `reconcilePr` step in `comment` + // mode, which writes a merge-request note when the run is a + // merge_request_event pipeline. Nothing about the Op is forge-specific — + // the trigger is. + const built = await build(join(planOnPrDir, "src"), [terraformSerializer]); + const planOp = built.entities.get("app-plan") as unknown as { props: OpConfig }; + const step = planOp.props.phases.find((p) => p.name === "Report")?.steps[0] as ActivityStep; + expect(step.fn).toBe("reconcilePr"); + expect(step.args?.mode).toBe("comment"); + // And the mode is still tied to the trigger, on GitLab as on GitHub: a + // push pipeline has no merge request to post on. + await expect( + generateOpsPipeline( + [{ ...GITLAB_APPLY_SPEC, findingMode: "comment" }], + "gitlab", + {}, + planOnPrDir, + ), + ).rejects.toThrow(/findingMode "comment".*trigger is "push"/s); + }); + + it("mints the OIDC token through id_tokens, and stores no static key", async () => { + const yaml = await planOnPrGitlabPipeline(); + const jobs = gitlabJobs(yaml); + for (const [op, roleVariable] of [ + ["app-plan", "AWS_PLAN_ROLE_ARN"], + ["app-apply", "AWS_APPLY_ROLE_ARN"], + ] as const) { + // GitLab's own OIDC surface, which is what the spec's `id-token: write` + // becomes here — there is no `permissions:` block to put it in. + expect(jobs[op].id_tokens).toEqual({ CHANT_ID_TOKEN: { aud: "$CI_SERVER_URL" } }); + // Setup first, then the terraform install, then the Op. + expect(jobs[op].script[0]).toContain(`AWS_ROLE_ARN="$${roleVariable}"`); + expect(jobs[op].script[0]).toContain(GITLAB_TOKEN_FILE); + expect(jobs[op].script[1]).toContain("/tmp/terraform.zip"); + expect(jobs[op].script[2]).toContain(`chant run ${op}`); + } + // The credentials are the ones the provider's own SDK exchanged the token + // for; nothing durable is stored on the project. + expect(yaml).not.toContain("AWS_ACCESS_KEY_ID"); + expect(yaml).not.toContain("AWS_SECRET_ACCESS_KEY"); + }); + + it("has no permissions: block at all, and says where the note's write access comes from", async () => { + const yaml = await planOnPrGitlabPipeline(); + // GitLab has no per-job token-scope mapping, so the whole github + // permission surface is absent rather than approximated. What the comment + // mode spends is a project CI/CD variable, which the header names. + expect(parseYAML(yaml)).not.toHaveProperty("permissions"); + expect(yaml).not.toContain("pull-requests:"); + expect(yaml).toContain("GITLAB_TOKEN"); + // And a scope that has no GitLab meaning is refused rather than dropped. + await expect( + generateOpsPipeline( + [{ ...GITLAB_PLAN_SPEC, permissions: { "id-token": "write", issues: "write" } }], + "gitlab", + {}, + planOnPrDir, + ), + ).rejects.toThrow(/no per-job token-scope mapping/); + }); + + it("keeps a gated apply green, with the pending gate in the log and in an artifact", async () => { + const jobs = gitlabJobs(await planOnPrGitlabPipeline()); + const apply = jobs["app-apply"]; + // The same one mapped outcome github's push job gets. No `--json`: the + // human render of the gate is the job log, which is one of GitLab's two + // surfaces for it. + expect(apply.script.at(-1)).toBe("chant run app-apply --gated-exit 0"); + // The other surface. Core writes the pending block to whatever + // CHANT_GATE_SUMMARY names, and the job publishes that path. + expect(apply.variables?.CHANT_GATE_SUMMARY).toBe("chant-gate-app-apply.md"); + expect(apply.artifacts?.paths).toEqual(["chant-gate-app-apply.md"]); + expect(apply.artifacts?.when).toBe("always"); + // The plan half is not gated: nobody is waiting on a merge for it. + expect(jobs["app-plan"].script.at(-1)).toBe("chant run app-plan"); + expect(jobs["app-plan"].artifacts).toBeUndefined(); + }); + + it("puts the apply behind a GitLab environment too, and the plan behind none (#2257)", async () => { + const jobs = gitlabJobs(await planOnPrGitlabPipeline()); + expect(jobs["app-apply"].environment).toEqual({ name: APPLY_ENVIRONMENT }); + expect(jobs["app-plan"].environment).toBeUndefined(); + }); + + it("refuses the github marketplace action rather than dropping it", async () => { + // The github specs' `uses:` setup step has no GitLab shape at all, which + // is why this example carries a second setup list rather than one. + await expect( + generateOpsPipeline([PLAN_SPEC], "gitlab", {}, planOnPrDir), + ).rejects.toThrow(/is `uses: "aws-actions\/configure-aws-credentials@v6"`/); + }); + it("applies only the plan its own Plan step saved", async () => { const result = await build(join(planOnPrDir, "src"), [terraformSerializer]); const applyOp = result.entities.get("app-apply") as unknown as { props: OpConfig }; diff --git a/lexicons/terraform/examples/plan-on-pr/README.md b/lexicons/terraform/examples/plan-on-pr/README.md index 1acf163b0b..e24cce5fe2 100644 --- a/lexicons/terraform/examples/plan-on-pr/README.md +++ b/lexicons/terraform/examples/plan-on-pr/README.md @@ -127,10 +127,14 @@ strictly better: nothing durable is stored, a leaked log line expires within the hour, and the role's trust policy names the repository and ref that may assume it, so an unrelated repository holding the same secret gets nothing. -Off GitHub the mode is refused rather than approximated: `reconcilePr` shells -to `gh` against the GitHub API and reads the GitHub Actions event payload, and -chant carries no GitLab or Forgejo client that would post the equivalent note. -The gitlab and forgejo Op generators say so by name at build time. +On GitLab the same mode writes a merge-request note instead, by the same +recipe: `reconcilePr` reads the merge request out of `CI_MERGE_REQUEST_IID` +and the project out of `CI_MERGE_REQUEST_PROJECT_ID`, finds its own note by +the marker and edits it (chant #2256). See "The same pair on GitLab" below. +On Forgejo it is still refused rather than approximated: the activity's +GitHub half shells to `gh`, and chant carries no Forgejo client that would +post the equivalent comment, so the forgejo Op generator says so by name at +build time. Only the human plan is ever posted, on either half. `terraform show -json` over a plan file carries resource attribute values, provider secrets among @@ -211,3 +215,103 @@ scopes are the same `contents: read` and `id-token: write` they were before the environment was named. `app-apply-gate-notice` stays outside the environment too: it exists to say the chant gate is pending, and behind the same reviewer it would only be readable once somebody had already acted. + +## The same pair on GitLab + +The two specs generate for gitlab too, and into one document rather than two: +a GitHub trigger is workflow-scoped, so each Op needs its own workflow file, +while a GitLab trigger is job-scoped and both jobs live in one +`.gitlab-ci.yml`. `$CI_PIPELINE_SOURCE` is what tells the events apart, and +`rules:` is what selects a job on either: + +```yaml +app-plan: + resource_group: app-plan + rules: + - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main"' + +app-apply: + resource_group: app-apply + rules: + - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"' +``` + +`$CI_MERGE_REQUEST_TARGET_BRANCH_NAME` is the branch the merge request would +merge into, which is the same thing `on.pull_request.branches` filters on. +`resource_group` is GitLab's per-Op concurrency: one run at a time, the next +queued rather than cancelled, which on the apply is also the state lock. + +Two things about the specs differ, and both are properties of the forge: + +```ts +const assumeRole = (roleVariable: string) => [ + { + run: + `echo "$CHANT_ID_TOKEN" > /tmp/chant-web-identity-token && ` + + `export AWS_ROLE_ARN="$${roleVariable}" ` + + `AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/chant-web-identity-token AWS_REGION=eu-west-1`, + }, +]; +``` + +A GitLab job runs `script` lines and nothing else, so the marketplace action +is a shell line here — and the generator refuses a `uses:` entry by name +rather than dropping it, which is why this example carries a second setup list +instead of sharing one. The line needs no AWS CLI: GitLab's `id_tokens:` puts +the OIDC JWT in an environment variable, and the AWS SDK inside the terraform +provider does the `AssumeRoleWithWebIdentity` exchange itself once it has +`AWS_ROLE_ARN` and a file to read the token from. Every `script` line in a job +runs in one shell, so an `export` on one line is still set on the next — which +is exactly what a GitHub Actions `run:` step cannot do, and why the same setup +is an action there. + +`permissions: { "id-token": "write" }` stays on the spec and becomes GitLab's +own OIDC surface: + +```yaml +id_tokens: + CHANT_ID_TOKEN: + aud: $CI_SERVER_URL +``` + +That is the only additive scope with a GitLab meaning. Every other one is +refused by name, because there is no per-job token-scope mapping to put it in +and a silently dropped scope would emit a job that reads as granted and runs +with nothing. So the generated document has no `permissions:` block at all, +and what the `comment` mode spends is a `GITLAB_TOKEN` CI/CD variable (masked, +scope: `api`) that the generated header names. A project access token is +enough. `CI_JOB_TOKEN` is accepted as a fallback and is enough only on an +instance whose job-token allowlist reaches the notes API, which is not the +default. + +The gated apply keeps its two halves. The push job runs `chant run app-apply +--gated-exit 0`, so a pending approval is a green pipeline rather than a red +one on every merge. GitLab has no step summary, so the pending block lands in +the two surfaces it does have: the job's own log, which is where the run's +human render already goes, and an artifact — + +```yaml +variables: + CHANT_GATE_SUMMARY: chant-gate-app-apply.md +artifacts: + when: always + paths: + - chant-gate-app-apply.md +``` + +— rather than in a follow-up job. GitHub's `app-apply-gate-notice` posts on +the merged pull request through the forge API; doing that here would cost a +token an apply Op that posts nothing should not have to carry. + +`environment: { name: "production" }` crosses over unchanged: GitLab has +environments under the same key with the same two fields, and a protected +environment's approval rule holds the job the way a required reviewer does. +Where the rule is configured differs — Settings > CI/CD > Protected +environments rather than Settings > Environments — and the generated header +says so. + +Only the cron trigger has no in-file form on GitLab. A schedule is a +project-level Pipeline Schedule that runs the project's existing +`.gitlab-ci.yml`, so a cron Op becomes a job selected by +`$CHANT_SCHEDULED_OP`, and the generated header says which schedule to create. +Neither Op in this example has one. diff --git a/scripts/docs-sentences-baseline.json b/scripts/docs-sentences-baseline.json index 4f8e6d86b2..0f10435ce5 100644 --- a/scripts/docs-sentences-baseline.json +++ b/scripts/docs-sentences-baseline.json @@ -1059,11 +1059,9 @@ "tricolon/comma-series": 1 }, "docs/src/content/docs/tutorials/terraform-carve-out.mdx": { - "formatting/em-dash-density": 20, + "formatting/em-dash-density": 19, "claude/colon-reveal": 4, "claude-technical-vocabulary": 1, - "anaphora/repeated-opening": 1, - "claude/figurative-suffixes": 1, "tricolon/comma-series": 1 }, "docs/src/content/docs/whats-new.mdx": { From f5982d23f2ba2d021c8bab6b04c240ac8b933fb2 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:26:15 -0600 Subject: [PATCH 5/5] docs: the three pages that said GitLab refuses the trigger pair and the comment mode (#2256) `guide/ops.mdx` said the generators synthesize one cron-triggered CI file per Op and that gitlab refuses `comment` outright; `lexicon-authoring/ci-integration.mdx` said gitlab refuses an additive `permissions` map; the terraform lexicon's ops page said the mode is refused off GitHub. Each now says what the generator does, including where the note's write access comes from and why the permission table is a GitHub column. The lexicon page is authored in `docs/pages/` and regenerated into `docs/src/content/docs/`; both are committed. Also ratchets the docs prose baseline to 4084. Six findings left it below its recorded value across four pages none of this branch touches (contributing/examples, tutorials/sprites-build-sandbox, tutorials/sprites-managed-agent-worker, tutorials/terraform-carve-out); the per-file counts confirm this branch's own doc edits added none. --- docs/src/content/docs/guide/ops.mdx | 4 ++-- docs/src/content/docs/lexicon-authoring/ci-integration.mdx | 7 ++++--- lexicons/terraform/docs/pages/ops.mdx | 2 +- lexicons/terraform/docs/src/content/docs/ops.mdx | 2 +- scripts/docs-sentences-baseline.json | 6 +++--- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/src/content/docs/guide/ops.mdx b/docs/src/content/docs/guide/ops.mdx index 2322b50212..eff0e2e5bc 100644 --- a/docs/src/content/docs/guide/ops.mdx +++ b/docs/src/content/docs/guide/ops.mdx @@ -244,7 +244,7 @@ export const { op: scheduledOp } = WorkflowAuditOp({ `schedule` above is data on the Op: `{ cron, overlap: "skip" }`, and nothing about it names a runtime. Three readers render it. -`generateOpsPipeline` (`@intentius/chant/op`) validates that every named Op exists, then delegates to the target lexicon's `generateOpPipeline` (gitlab, github, forgejo), which synthesizes one cron-triggered CI file per Op — `chant run ` in the job, with only the token/permission scope its finding-mode needs (read-only for `report`; scoped write for `issue`/`comment`/`pull-request`/`merge-request`). This is the Op counterpart to [generate mode](/chant/components/orchestration/#generate-mode)'s component pipeline. +`generateOpsPipeline` (`@intentius/chant/op`) validates that every named Op exists, then delegates to the target lexicon's `generateOpPipeline` (gitlab, github, forgejo), which synthesizes one CI file per Op (on gitlab, one document holding a job apiece, since a trigger there is job-scoped) — `chant run ` in the job, with only the token/permission scope its finding-mode needs (read-only for `report`; scoped write for `issue`/`comment`/`pull-request`/`merge-request`). This is the Op counterpart to [generate mode](/chant/components/orchestration/#generate-mode)'s component pipeline. Finding-modes and the scopes they cost on GitHub: @@ -255,7 +255,7 @@ Finding-modes and the scopes they cost on GitHub: | `comment` | `pull_request` | `contents: read`, `pull-requests: write` | | `pull-request` / `merge-request` | any | `contents: write`, `pull-requests: write` | -Any non-`report` mode on a `pull_request` trigger also gets `pull-requests: write`, which is why `comment` costs nothing beyond what that trigger already grants. `comment` is the one mode that constrains the trigger as well as the scope: the github generator refuses it by name on a cron or push trigger, and the gitlab and forgejo generators refuse it outright, since the activity behind it shells to `gh` against the GitHub API and chant carries no client for the other two forges. +Any non-`report` mode on a `pull_request` trigger also gets `pull-requests: write`, which is why `comment` costs nothing beyond what that trigger already grants. `comment` is the one mode that constrains the trigger as well as the scope: the github and gitlab generators both refuse it by name on a cron or push trigger, since a run triggered by neither a pull request nor a merge request has nothing to post on. On GitLab the finding is a merge-request note written through the REST API with a `GITLAB_TOKEN`, read out of the pipeline's own `CI_MERGE_REQUEST_IID` ([#2256](https://github.com/INTENTIUS/chant/issues/2256)); GitLab has no `permissions:` block at all, so the table's scopes are a GitHub column. The forgejo generator still refuses the mode outright, since the GitHub half of the activity shells to `gh` and chant carries no Forgejo client. [`chant operator`](/chant/guide/operator/) is the second. A timer and a ref lease around the local executor, ticking every discovered `ConvergeOp` from your own machine or from a CronJob. diff --git a/docs/src/content/docs/lexicon-authoring/ci-integration.mdx b/docs/src/content/docs/lexicon-authoring/ci-integration.mdx index 64b0f94ba0..143f9a5346 100644 --- a/docs/src/content/docs/lexicon-authoring/ci-integration.mdx +++ b/docs/src/content/docs/lexicon-authoring/ci-integration.mdx @@ -229,9 +229,10 @@ env? }` / `{ run, env? }` steps emitted ahead of the `beforeScript` lines, finding mode already grants (chant #2242), and `environment`, a `{ name, url? }` naming the forge deployment environment the job runs in (chant #2257). A provider with no equivalent degrades by name at build time rather than -dropping the option: gitlab refuses a `uses` entry and an additive -`permissions` map, forgejo emits the steps and drops the permissions the way -it already drops the mode's own. +dropping the option: gitlab refuses a `uses` entry outright, and refuses every +additive scope except `id-token: write`, which it maps onto GitLab's own +`id_tokens:` declaration (chant #2256); forgejo emits the steps and drops the +permissions the way it already drops the mode's own. `environment` is the one of the three where a silent drop would be worst, because the option exists so a human can hold a job. A provider without diff --git a/lexicons/terraform/docs/pages/ops.mdx b/lexicons/terraform/docs/pages/ops.mdx index 05058c5317..f05a9be418 100644 --- a/lexicons/terraform/docs/pages/ops.mdx +++ b/lexicons/terraform/docs/pages/ops.mdx @@ -264,7 +264,7 @@ The additive `permissions` map can only add. A scope the mode already granted is **The plan lands as a comment on the pull request that triggered the run.** That is `findingMode: "comment"` ([#2231](https://github.com/INTENTIUS/chant/issues/2231)), the fourth mode on `reconcilePr` and the one this shape was missing. It writes a hidden marker as the comment's first line and finds the comment again by that marker on the next run, so a pull request pushed to five times carries one comment holding the current plan rather than five stale ones. The pull request comes out of the run's own event payload (`GITHUB_EVENT_PATH`, falling back to `GITHUB_REF`), which is why the mode constrains the trigger rather than only the permission set: the github generator refuses it by name on a cron or push trigger, and a run reaching the Report step with no pull request fails there instead of posting the plan somewhere else. -Off GitHub the mode is refused rather than approximated. The activity shells to `gh` against the GitHub API and reads the GitHub Actions event payload, and chant carries no GitLab or Forgejo client that would post the equivalent note, so the gitlab and forgejo Op generators refuse `comment` by name at build time and point at `"issue"` (or, on GitLab, `"merge-request"`). +On GitLab the same mode writes a merge-request note ([#2256](https://github.com/INTENTIUS/chant/issues/2256)), by the same recipe: the marker is the note's first line, the next pipeline finds the note by it and edits it in place. The merge request comes out of `CI_MERGE_REQUEST_IID` and the project out of `CI_MERGE_REQUEST_PROJECT_ID`, so the gitlab generator constrains the trigger exactly as the github one does and refuses the mode by name on a cron or push job. On Forgejo it is still refused rather than approximated: the GitHub half of the activity shells to `gh` and chant carries no Forgejo client, so the forgejo Op generator points at `"issue"` instead. The push run stops at the apply's gate. It reaches the gate, finds no resolution on the ledger, records the pending fact and ends there instead of holding a runner open. `chant approve app-apply approve-app-apply --approver you` records the answer and re-running the workflow applies. A root whose merges should apply unattended sets `gate: "never"`. diff --git a/lexicons/terraform/docs/src/content/docs/ops.mdx b/lexicons/terraform/docs/src/content/docs/ops.mdx index 877439fdbc..919d418d8c 100644 --- a/lexicons/terraform/docs/src/content/docs/ops.mdx +++ b/lexicons/terraform/docs/src/content/docs/ops.mdx @@ -268,7 +268,7 @@ The additive `permissions` map can only add. A scope the mode already granted is **The plan lands as a comment on the pull request that triggered the run.** That is `findingMode: "comment"` ([#2231](https://github.com/INTENTIUS/chant/issues/2231)), the fourth mode on `reconcilePr` and the one this shape was missing. It writes a hidden marker as the comment's first line and finds the comment again by that marker on the next run, so a pull request pushed to five times carries one comment holding the current plan rather than five stale ones. The pull request comes out of the run's own event payload (`GITHUB_EVENT_PATH`, falling back to `GITHUB_REF`), which is why the mode constrains the trigger rather than only the permission set: the github generator refuses it by name on a cron or push trigger, and a run reaching the Report step with no pull request fails there instead of posting the plan somewhere else. -Off GitHub the mode is refused rather than approximated. The activity shells to `gh` against the GitHub API and reads the GitHub Actions event payload, and chant carries no GitLab or Forgejo client that would post the equivalent note, so the gitlab and forgejo Op generators refuse `comment` by name at build time and point at `"issue"` (or, on GitLab, `"merge-request"`). +On GitLab the same mode writes a merge-request note ([#2256](https://github.com/INTENTIUS/chant/issues/2256)), by the same recipe: the marker is the note's first line, the next pipeline finds the note by it and edits it in place. The merge request comes out of `CI_MERGE_REQUEST_IID` and the project out of `CI_MERGE_REQUEST_PROJECT_ID`, so the gitlab generator constrains the trigger exactly as the github one does and refuses the mode by name on a cron or push job. On Forgejo it is still refused rather than approximated: the GitHub half of the activity shells to `gh` and chant carries no Forgejo client, so the forgejo Op generator points at `"issue"` instead. The push run stops at the apply's gate. It reaches the gate, finds no resolution on the ledger, records the pending fact and ends there instead of holding a runner open. `chant approve app-apply approve-app-apply --approver you` records the answer and re-running the workflow applies. A root whose merges should apply unattended sets `gate: "never"`. diff --git a/scripts/docs-sentences-baseline.json b/scripts/docs-sentences-baseline.json index 0f10435ce5..d3895257d1 100644 --- a/scripts/docs-sentences-baseline.json +++ b/scripts/docs-sentences-baseline.json @@ -476,7 +476,7 @@ "docs/src/content/docs/contributing/examples.mdx": { "formatting/em-dash-density": 14, "claude/colon-reveal": 2, - "anaphora/repeated-opening": 2, + "anaphora/repeated-opening": 1, "claude/figurative-suffixes": 1, "tricolon/density": 1 }, @@ -1046,7 +1046,7 @@ "tricolon/comma-series": 4 }, "docs/src/content/docs/tutorials/sprites-build-sandbox.mdx": { - "formatting/em-dash-density": 15, + "formatting/em-dash-density": 14, "claude/colon-reveal": 2, "tricolon/comma-series": 2, "repetition/near-duplicate": 1 @@ -1054,7 +1054,7 @@ "docs/src/content/docs/tutorials/sprites-managed-agent-worker.mdx": { "formatting/em-dash-density": 17, "claude/colon-reveal": 3, - "anaphora/repeated-opening": 2, + "anaphora/repeated-opening": 1, "repetition/near-duplicate": 2, "tricolon/comma-series": 1 },