GitLab workflow best practices and glab CLI usage

GitLab workflow best practices and glab CLI usage for Claude Code.
.gitlab-ci.yml authoring and lintingci-monitor)glab api --jq, gh pr on a GitLab remote, escaped-$ inline GraphQL, hallucinated mutations) with the corrected form, and nudges loading gitlab:merge-request before hand-rolled MR transactionsregister.ts watches the current branch's merge request and shows its pipeline and approval state at the end of the prompt footer. The model is told when the MR merges or closes, when it conflicts with its target or needs a rebase that the target requires, when its branch moves to a commit the local repository lacks, when a job newly fails, when changes are requested, and when other people approve, revoke an approval, or comment, in one line per author. A conflict alert points at the git:conflicts skill and fires even when the conflict is already there as the MR is first seen. Every decision and send is logged to mod-events. Needs a signed-in glab. Set the watch option to false to turn it offbun test plugins/gitlab
bun scripts/mod-test.ts gitlabmod/register.ts 432 lines1import type { EngineInterface, On, PluginOptions } from "claude-code";
2import {
3 STALE,
4 type Job,
5 type Promoted,
6 type Snapshot,
7 baselineOf,
8 combine,
9 decide,
10 isOpen,
11 messageOf,
12 parseApprovals,
13 parseJobs,
14 parseNotes,
15 parseUser,
16 parseView,
17 snapshotOf,
18 statusOf,
19} from "./mr.ts";
20
21const MOD = "gitlab";
22
23export const POLL_MS = {
24 pending: 60_000,
25 settled: 180_000,
26 idle: 120_000,
27 closed: 600_000,
28 error: 300_000,
29} as const;
30
31// A dropped injection is retried on later polls, up to this many attempts.
32export const MAX_ATTEMPTS = 3;
33// Fallback default branches when origin/HEAD is unset.
34const DEFAULT_BRANCHES = new Set(["main", "master"]);
35// /clear and /resume keep the process running, so the watch continues.
36const CONTINUING = new Set(["clear", "resume"]);
37
38interface Undelivered {
39 head: string;
40 decisions: Promoted[];
41 attempts: number;
42}
43
44interface Watch {
45 snapshot: Snapshot | undefined;
46 branch: string | undefined;
47 me: string | undefined;
48 undelivered: Undelivered | undefined;
49 error: string | undefined;
50 timer: { cancel(): void } | undefined;
51 line: string | undefined;
52 generation: number;
53 isStopped: boolean;
54}
55
56type Read = { kind: "none" } | { kind: "mr"; snapshot: Snapshot; branch: string };
57
58function show($: EngineInterface, watch: Watch, text: string | undefined) {
59 const line = text === "" ? undefined : text;
60 if (line === watch.line) return;
61 watch.line = line;
62 $.ui.invalidate("ui.render");
63}
64
65function emit($: EngineInterface, event: string, detail: Record<string, unknown>, ok = true) {
66 void $.modEvents.emit({ mod: MOD, event, ok, detail });
67}
68
69async function isDefaultBranch($: EngineInterface, cwd: string, branch: string): Promise<boolean> {
70 const origin = await $.process.run(
71 ["git", "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"],
72 { cwd },
73 );
74 if (origin.exitCode !== 0) return DEFAULT_BRANCHES.has(branch);
75 return origin.stdout.trim() === `origin/${branch}`;
76}
77
78const NO_MR = /no (open )?merge request/i;
79
80// glab resolves the host from the git remote, which covers self-managed instances.
81async function glab($: EngineInterface, cwd: string, args: string[]): Promise<string> {
82 const result = await $.process.run(["glab", ...args], { cwd, timeoutMs: 20_000 });
83 if (result.exitCode === 0) return result.stdout;
84 // glab opens its stderr with a styled ERROR banner line ahead of the cause.
85 const line = result.stderr
86 .split("\n")
87 .map((text) => text.trim())
88 .find((text) => text !== "" && text !== "ERROR");
89 throw new Error(line ?? `glab exited ${result.exitCode}`);
90}
91
92function parsed<T>(value: T | undefined, source: string): T {
93 if (value === undefined) throw new Error(`${source} returned an unexpected shape`);
94 return value;
95}
96
97// glab mr view finds only an open MR by branch, so a tracked MR is re-read by IID
98// to see it merge or close.
99async function viewMr(
100 $: EngineInterface,
101 watch: Watch,
102 cwd: string,
103 branch: string,
104): Promise<string | undefined> {
105 try {
106 return await glab($, cwd, ["mr", "view", "-F", "json"]);
107 } catch (error) {
108 if (!(error instanceof Error && NO_MR.test(error.message))) throw error;
109 if (watch.snapshot === undefined || watch.branch !== branch) return undefined;
110 return glab($, cwd, ["mr", "view", String(watch.snapshot.mr), "-F", "json"]);
111 }
112}
113
114async function jobsOf($: EngineInterface, cwd: string, projectId: number, pipeline: number) {
115 const path = `projects/${projectId}/pipelines/${pipeline}/jobs?per_page=100`;
116 const stdout = await glab($, cwd, ["api", "--paginate", "--output", "ndjson", path]);
117 return parsed(parseJobs(stdout), "pipeline jobs");
118}
119
120async function meOf($: EngineInterface, watch: Watch, cwd: string): Promise<string> {
121 if (watch.me !== undefined) return watch.me;
122 watch.me = parsed(parseUser(await glab($, cwd, ["api", "user"])), "glab api user");
123 return watch.me;
124}
125
126// Every worktree of the repository shares one object store, so only a push from
127// another clone or from GitLab itself leaves the head unknown here. Only exit 1
128// means a missing object, so a failing git reads as known rather than crying push.
129async function isKnown($: EngineInterface, cwd: string, sha: string): Promise<boolean> {
130 const argv = ["git", "rev-parse", "--verify", "--quiet", `${sha}^{commit}`];
131 const result = await $.process.run(argv, { cwd });
132 return result.exitCode !== 1;
133}
134
135// A commit once present stays present, so only a new or missing head is checked again.
136async function isHeadKnownOf(
137 $: EngineInterface,
138 watch: Watch,
139 cwd: string,
140 sha: string,
141): Promise<boolean> {
142 const prev = watch.snapshot;
143 if (prev?.head === sha && prev.isHeadKnown) return true;
144 return isKnown($, cwd, sha);
145}
146
147async function readMr($: EngineInterface, watch: Watch, isRetry = false): Promise<Read> {
148 const cwd = await $.session.cwd();
149 const head = await $.process.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd });
150 const branch = head.stdout.trim();
151 if (head.exitCode !== 0 || branch === "HEAD" || (await isDefaultBranch($, cwd, branch))) {
152 return { kind: "none" };
153 }
154 const stdout = await viewMr($, watch, cwd, branch);
155 if (stdout === undefined) return { kind: "none" };
156 const view = parsed(parseView(stdout), "glab mr view");
157 const prev = watch.snapshot;
158 // A merged or closed MR changes nothing else the watch shows.
159 if (prev?.mr === view.iid && !isOpen(prev) && view.state === prev.state) {
160 return { kind: "mr", snapshot: prev, branch };
161 }
162 const mr = `projects/${view.projectId}/merge_requests/${view.iid}`;
163 const pipeline = view.pipeline;
164 const [approvals, notes, jobs, me, isHeadKnown] = await Promise.all([
165 glab($, cwd, ["api", `${mr}/approvals`]),
166 glab($, cwd, ["api", `${mr}/notes?sort=desc&order_by=created_at&per_page=100`]),
167 pipeline === null
168 ? Promise.resolve<Job[]>([])
169 : jobsOf($, cwd, pipeline.projectId, pipeline.id),
170 meOf($, watch, cwd),
171 isHeadKnownOf($, watch, cwd, view.sha),
172 ]);
173 const read = snapshotOf({
174 view,
175 approvals: parsed(parseApprovals(approvals), "MR approvals"),
176 notes: parsed(parseNotes(notes), "MR notes"),
177 jobs,
178 me,
179 isHeadKnown,
180 });
181 // A deleted note can lower the newest id seen, which would re-admit older notes.
182 const snapshot =
183 prev?.mr === read.mr
184 ? { ...read, noteCursor: Math.max(prev.noteCursor, read.noteCursor) }
185 : read;
186 // The reads are not atomic, so approvals a push reset can look withdrawn on the
187 // head read before it.
188 if (
189 !isRetry &&
190 prev?.mr === snapshot.mr &&
191 prev.head === snapshot.head &&
192 prev.approvers.some((name) => !snapshot.approvers.includes(name))
193 ) {
194 const recheck = parsed(
195 parseView(await glab($, cwd, ["mr", "view", String(view.iid), "-F", "json"])),
196 "glab mr view",
197 );
198 if (recheck.sha !== view.sha) return readMr($, watch, true);
199 }
200 return { kind: "mr", snapshot, branch };
201}
202
203async function inject(
204 $: EngineInterface,
205 snapshot: Snapshot,
206 promoted: Promoted[],
207 attempt: number,
208): Promise<boolean> {
209 const text = messageOf(snapshot, promoted);
210 const kinds = promoted.map((d) => d.kind);
211 const detail = { mr: snapshot.mr, head: snapshot.head, kinds, chars: text.length, attempt };
212 try {
213 const result = await $.prompt.submit({ text });
214 if (result.drop !== undefined) {
215 emit($, "inject", { ...detail, dropped: result.drop }, false);
216 return false;
217 }
218 emit($, "inject", detail);
219 return true;
220 } catch (error) {
221 emit($, "inject", { ...detail, error: String(error) }, false);
222 return false;
223 }
224}
225
226interface Due {
227 due: Promoted[];
228 /** Blocks waiting on the forge to decide mergeability, kept unsent. */
229 held: Promoted[];
230}
231
232// `decided` is this poll's own mergeability answer, before any carry-forward.
233function stillDue(
234 undelivered: Undelivered | undefined,
235 next: Snapshot,
236 decided: Snapshot["block"],
237): Due {
238 if (undelivered === undefined) return { due: [], held: [] };
239 const held: Promoted[] = [];
240 const due = undelivered.decisions.flatMap((decision): Promoted[] => {
241 if (decision.kind === "mr.merged") return next.state === "merged" ? [decision] : [];
242 if (decision.kind === "mr.closed") return next.state === "closed" ? [decision] : [];
243 if (!isOpen(next)) return [];
244 if (decision.kind === "conflict" || decision.kind === "behind") {
245 if (decided === undefined) held.push(decision);
246 return decided === decision.kind ? [decision] : [];
247 }
248 if (decision.kind === "push.foreign") return next.isHeadKnown ? [] : [decision];
249 if (decision.kind === "changes_requested") return next.isChangesRequested ? [decision] : [];
250 if (decision.kind !== "ci.failed") return [decision];
251 if (undelivered.head !== next.head) return [];
252 const failed = decision.failed.filter((label) => next.failed.includes(label));
253 return failed.length > 0 ? [{ ...decision, failed }] : [];
254 });
255 return { due, held };
256}
257
258// A failed send joins whatever a poll that ran meanwhile left undelivered.
259async function send(
260 $: EngineInterface,
261 watch: Watch,
262 next: Snapshot,
263 due: Promoted[],
264 attempt: number,
265 isCurrent: () => boolean,
266): Promise<void> {
267 const isSent = await inject($, next, due, attempt);
268 if (!isCurrent() || isSent || attempt >= MAX_ATTEMPTS) return;
269 const pending = watch.undelivered;
270 watch.undelivered = {
271 head: pending?.head ?? next.head,
272 decisions: pending === undefined ? due : combine(due, pending.decisions),
273 attempts: Math.max(attempt, pending?.attempts ?? 0),
274 };
275}
276
277function delayOf(snapshot: Snapshot): number {
278 if (!isOpen(snapshot)) return POLL_MS.closed;
279 return snapshot.phase === "pending" ? POLL_MS.pending : POLL_MS.settled;
280}
281
282interface Applied {
283 delay: number;
284 /** The send, which waits for an idle session, so the next poll is not held on it. */
285 delivery: Promise<void> | undefined;
286}
287
288function apply($: EngineInterface, watch: Watch, read: Read, isCurrent: () => boolean): Applied {
289 if (read.kind === "none") {
290 show($, watch, undefined);
291 watch.snapshot = undefined;
292 watch.branch = undefined;
293 watch.undelivered = undefined;
294 return { delay: POLL_MS.idle, delivery: undefined };
295 }
296 const prev = watch.snapshot;
297 const isSameMr =
298 prev !== undefined &&
299 prev.mr === read.snapshot.mr &&
300 prev.projectId === read.snapshot.projectId;
301 // An undecided poll keeps the last answer, so a recompute does not re-announce a block.
302 const decided = read.snapshot.block;
303 const next =
304 isSameMr && decided === undefined ? { ...read.snapshot, block: prev.block } : read.snapshot;
305 let due: Promoted[];
306 let attempt = 1;
307 if (!isSameMr) {
308 emit($, "mr.tracked", { mr: next.mr, head: next.head, phase: next.phase, state: next.state });
309 watch.undelivered = undefined;
310 due = baselineOf(next);
311 for (const { action, ...detail } of due) {
312 emit($, action, { mr: next.mr, head: next.head, baseline: true, ...detail });
313 }
314 } else {
315 const decisions = decide(prev, next);
316 for (const { action, ...detail } of decisions) {
317 emit($, action, { mr: next.mr, head: next.head, ...detail });
318 }
319 const fresh = decisions.filter((d): d is Promoted => d.action === "promote");
320 const still = stillDue(watch.undelivered, next, decided);
321 attempt = fresh.length > 0 ? 1 : (watch.undelivered?.attempts ?? 0) + 1;
322 watch.undelivered =
323 still.held.length > 0
324 ? { head: next.head, decisions: still.held, attempts: attempt - 1 }
325 : undefined;
326 due = combine(still.due, fresh);
327 }
328 watch.snapshot = next;
329 watch.branch = read.branch;
330 show($, watch, statusOf(next));
331 const delivery = due.length > 0 ? send($, watch, next, due, attempt, isCurrent) : undefined;
332 return { delay: delayOf(next), delivery };
333}
334
335async function poll($: EngineInterface, watch: Watch, generation: number): Promise<void> {
336 const isCurrent = () => !watch.isStopped && watch.generation === generation;
337 if (!isCurrent()) return;
338 let delay: number;
339 let delivery: Promise<void> | undefined;
340 try {
341 const read = await readMr($, watch);
342 // A session.end that landed while glab ran has already cleared the status.
343 if (!isCurrent()) return;
344 ({ delay, delivery } = apply($, watch, read, isCurrent));
345 watch.error = undefined;
346 } catch (error) {
347 const message = error instanceof Error ? error.message : String(error);
348 if (message !== watch.error) emit($, "poll.error", { error: message }, false);
349 watch.error = message;
350 delay = POLL_MS.error;
351 if (watch.snapshot !== undefined && isCurrent()) {
352 const line = statusOf(watch.snapshot);
353 show($, watch, line === "" ? STALE : `${line} · ${STALE}`);
354 }
355 }
356 if (!isCurrent()) return;
357 watch.timer = $.clock.after(delay, () => void poll($, watch, generation));
358 await delivery;
359}
360
361async function hasGlab($: EngineInterface): Promise<boolean> {
362 try {
363 return (await $.process.run(["glab", "--version"], { timeoutMs: 5000 })).exitCode === 0;
364 } catch {
365 // run() rejects when glab is not on PATH.
366 return false;
367 }
368}
369
370/**
371 * Watches the current branch's merge request with `glab` and shows its pipeline
372 * and approval state at the end of the prompt footer. What `decide` promotes is
373 * sent to the model, along with a block already present when an MR is first
374 * seen. Every other change is only shown and logged.
375 */
376export function register(on: On, options: PluginOptions): void {
377 const watch: Watch = {
378 snapshot: undefined,
379 branch: undefined,
380 me: undefined,
381 undelivered: undefined,
382 error: undefined,
383 timer: undefined,
384 line: undefined,
385 generation: 0,
386 isStopped: true,
387 };
388
389 on("session.start", async ($, e, next) => {
390 const generation = watch.generation;
391 const started = await next(e);
392 if (!e.isInteractive) {
393 emit($, "session.start", { active: false, reason: "non-interactive" });
394 return started;
395 }
396 if (options.watch === false) {
397 emit($, "session.start", { active: false, reason: "watch off" });
398 return started;
399 }
400 if (!(await hasGlab($))) {
401 emit($, "session.start", { active: false, reason: "glab unavailable" });
402 return started;
403 }
404 // A session.end while this start was in flight has moved the generation on.
405 if (watch.generation !== generation) return started;
406 emit($, "session.start", { active: true });
407 if (watch.isStopped) {
408 watch.isStopped = false;
409 watch.me = undefined;
410 watch.generation += 1;
411 void poll($, watch, watch.generation);
412 }
413 return started;
414 });
415
416 on("ui.render", { component: "PromptHint" }, ($, e, next) => {
417 if (watch.line === undefined) return next(e);
418 const tail = e.props.tail === undefined ? watch.line : `${e.props.tail} · ${watch.line}`;
419 return next({ ...e, props: { ...e.props, tail } });
420 });
421
422 on("session.end", ($, e, next) => {
423 if (!CONTINUING.has(e.reason)) {
424 watch.isStopped = true;
425 watch.generation += 1;
426 watch.timer?.cancel();
427 show($, watch, undefined);
428 }
429 return next(e);
430 });
431}
432mod/mr.ts 530 lines1type Reader<T> = (value: unknown) => T | undefined;
2type Out<R> = R extends Reader<infer T> ? T : never;
3type Shaped<S> = { [K in keyof S]: Out<S[K]> };
4
5const isRecord = (value: unknown): value is Record<string, unknown> =>
6 typeof value === "object" && value !== null && !Array.isArray(value);
7
8const str: Reader<string> = (value) => (typeof value === "string" ? value : undefined);
9const num: Reader<number> = (value) => (typeof value === "number" ? value : undefined);
10const bool: Reader<boolean> = (value) => (typeof value === "boolean" ? value : undefined);
11
12const or =
13 <T, F>(read: Reader<T>, fallback: F): Reader<T | F> =>
14 (value) =>
15 read(value) ?? fallback;
16
17const map =
18 <T, U>(read: Reader<T>, to: (value: T) => U): Reader<U> =>
19 (value) => {
20 const result = read(value);
21 return result === undefined ? undefined : to(result);
22 };
23
24const list =
25 <T>(item: Reader<T>): Reader<T[]> =>
26 (value) =>
27 Array.isArray(value)
28 ? value.map(item).filter((entry): entry is T => entry !== undefined)
29 : undefined;
30
31function obj<S extends Record<string, Reader<unknown>>>(shape: S): Reader<Shaped<S>> {
32 // Every field holds its own reader's output, so a full read fits the shape.
33 const isRead = (out: Record<string, unknown>): out is Shaped<S> =>
34 Object.keys(shape).every((key) => out[key] !== undefined);
35 return (value) => {
36 if (!isRecord(value)) return undefined;
37 const out = Object.fromEntries(
38 Object.entries(shape).map(([key, read]) => [key, read(value[key])]),
39 );
40 return isRead(out) ? out : undefined;
41 };
42}
43
44function decoded<T>(stdout: string, read: Reader<T>): T | undefined {
45 let value: unknown;
46 try {
47 value = JSON.parse(stdout);
48 } catch {
49 // The caller reports malformed output as an unexpected shape.
50 return undefined;
51 }
52 return read(value);
53}
54
55const readUsername = map(obj({ username: str }), (user) => user.username);
56
57const readPipeline = map(obj({ id: num, project_id: num, status: str }), (p) => ({
58 id: p.id,
59 projectId: p.project_id,
60 status: p.status,
61}));
62
63const readView = map(
64 obj({
65 iid: num,
66 project_id: num,
67 web_url: str,
68 state: str,
69 sha: str,
70 target_branch: or(str, ""),
71 has_conflicts: or(bool, false),
72 detailed_merge_status: or(str, null),
73 head_pipeline: or(readPipeline, null),
74 }),
75 (v) => ({
76 iid: v.iid,
77 projectId: v.project_id,
78 url: v.web_url,
79 state: v.state,
80 sha: v.sha,
81 target: v.target_branch,
82 hasConflicts: v.has_conflicts,
83 detailedMergeStatus: v.detailed_merge_status,
84 pipeline: v.head_pipeline,
85 }),
86);
87
88const readApprovals = map(
89 obj({
90 approvals_required: or(num, 0),
91 approvals_left: or(num, 0),
92 approved_by: list(map(obj({ user: readUsername }), (entry) => entry.user)),
93 }),
94 (a) => ({
95 approvalsRequired: a.approvals_required,
96 approvalsLeft: a.approvals_left,
97 approvedBy: a.approved_by,
98 }),
99);
100
101const readNote = map(
102 obj({ id: num, author: or(readUsername, "someone"), system: or(bool, false) }),
103 (n) => ({ id: n.id, author: n.author, isSystem: n.system }),
104);
105
106const readJob = map(
107 obj({ id: num, name: or(str, "job"), status: str, allow_failure: or(bool, false) }),
108 (j) => ({ id: j.id, name: j.name, status: j.status, allowFailure: j.allow_failure }),
109);
110
111export type MrView = Out<typeof readView>;
112export type Approvals = Out<typeof readApprovals>;
113export type Note = Out<typeof readNote>;
114export type Job = Out<typeof readJob>;
115
116/** Narrows `glab mr view -F json` output to an MrView, or undefined when it is not one. */
117export const parseView = (stdout: string): MrView | undefined => decoded(stdout, readView);
118export const parseApprovals = (stdout: string): Approvals | undefined =>
119 decoded(stdout, readApprovals);
120export const parseNotes = (stdout: string): Note[] | undefined => decoded(stdout, list(readNote));
121// `glab api --paginate --output ndjson` prints one job per line across every page.
122export const parseJobs = (stdout: string): Job[] | undefined =>
123 decoded(`[${stdout.split("\n").filter(Boolean).join(",")}]`, list(readJob));
124export const parseUser = (stdout: string): string | undefined => decoded(stdout, readUsername);
125
126export type Phase = "none" | "pending" | "passing" | "failing";
127
128/** What stands between the branch and a merge that the session can fix. */
129export type Block = "conflict" | "behind" | "none";
130
131export interface Snapshot {
132 mr: number;
133 projectId: number;
134 url: string;
135 state: string;
136 head: string;
137 /** False when the head is a commit this checkout has never seen. */
138 isHeadKnown: boolean;
139 target: string;
140 /** Undefined while GitLab is still computing mergeability. */
141 block: Block | undefined;
142 pipeline: number | undefined;
143 phase: Phase;
144 total: number;
145 pending: number;
146 failed: string[];
147 isChangesRequested: boolean;
148 isApproved: boolean;
149 approvalsLeft: number;
150 approvers: string[];
151 noteCursor: number;
152 notes: { id: number; author: string }[];
153}
154
155export type Approval = "approved" | "unapproved" | null;
156
157export type Decision =
158 | { action: "promote"; kind: "mr.merged" }
159 | { action: "promote"; kind: "mr.closed" }
160 | { action: "promote"; kind: "conflict" }
161 | { action: "promote"; kind: "behind" }
162 | { action: "promote"; kind: "push.foreign"; from: string }
163 | { action: "promote"; kind: "ci.failed"; failed: string[] }
164 | { action: "promote"; kind: "changes_requested" }
165 | { action: "promote"; kind: "feedback"; author: string; approval: Approval; notes: number }
166 | { action: "drop"; kind: "unblocked" }
167 | { action: "drop"; kind: "ci.passing" | "ci.pending" | "ci.none" }
168 | { action: "drop"; kind: "push"; from: string }
169 | { action: "drop"; kind: "approvals.reset"; authors: string[] };
170
171export type Promoted = Extract<Decision, { action: "promote" }>;
172
173// A locked MR is mid-merge and still open.
174const OPEN = new Set(["opened", "locked"]);
175export const isOpen = (snapshot: Snapshot): boolean => OPEN.has(snapshot.state);
176
177const PENDING = new Set([
178 "created",
179 "waiting_for_resource",
180 "preparing",
181 "pending",
182 "running",
183 "scheduled",
184]);
185
186// A pipeline is manual only when a blocking manual job holds it, while a
187// non-blocking manual job sits in a finished pipeline.
188const PIPELINE_PENDING = new Set([...PENDING, "manual"]);
189
190const LABEL_MAX = 80;
191
192// Anyone who can edit .gitlab-ci.yml names its jobs, and the label reaches the model.
193function flatten(text: string): string {
194 const flat = text
195 .replaceAll(/[\p{Cc}\u2028\u2029]/gu, " ")
196 .replaceAll(/\s+/g, " ")
197 .trim();
198 return flat === "" ? "job" : flat;
199}
200
201function shown(label: string): string {
202 return label.length > LABEL_MAX ? `${label.slice(0, LABEL_MAX - 1)}…` : label;
203}
204
205export interface Read {
206 view: MrView;
207 approvals: Approvals;
208 notes: Note[];
209 jobs: Job[];
210 me: string;
211 isHeadKnown: boolean;
212}
213
214function phaseOf(read: Read, failed: string[], pending: number): Phase {
215 const pipeline = read.view.pipeline;
216 if (pipeline === null) return "none";
217 if (failed.length > 0) return "failing";
218 if (pending > 0 || PIPELINE_PENDING.has(pipeline.status)) return "pending";
219 if (pipeline.status === "canceled" || pipeline.status === "skipped") return "none";
220 return "passing";
221}
222
223const UNDECIDED = new Set(["checking", "unchecked", "preparing"]);
224
225// `detailed_merge_status` can lead `has_conflicts`, so either one decides.
226// GitLab reports need_rebase only where the merge method requires an up-to-date branch.
227function blockOf(view: MrView): Block | undefined {
228 if (view.hasConflicts || view.detailedMergeStatus === "conflict") return "conflict";
229 if (UNDECIDED.has(view.detailedMergeStatus ?? "")) return undefined;
230 return view.detailedMergeStatus === "need_rebase" ? "behind" : "none";
231}
232
233export function snapshotOf(read: Read): Snapshot {
234 const { view, approvals, notes, jobs, me } = read;
235 const failed: string[] = [];
236 let pending = 0;
237 const isManual = view.pipeline?.status === "manual";
238 for (const job of jobs) {
239 if (job.status === "failed" && !job.allowFailure) failed.push(flatten(job.name));
240 else if (PENDING.has(job.status) || (isManual && job.status === "manual")) pending += 1;
241 }
242 // A failed downstream pipeline fails its trigger job, which the jobs list leaves out.
243 if (view.pipeline?.status === "failed" && failed.length === 0) failed.push("pipeline");
244 failed.sort();
245 return {
246 mr: view.iid,
247 projectId: view.projectId,
248 url: view.url,
249 state: view.state,
250 head: view.sha,
251 isHeadKnown: read.isHeadKnown,
252 target: view.target,
253 block: blockOf(view),
254 pipeline: view.pipeline?.id,
255 phase: phaseOf(read, failed, pending),
256 total: jobs.length,
257 pending,
258 failed: [...new Set(failed)],
259 isChangesRequested: view.detailedMergeStatus === "requested_changes",
260 isApproved: approvals.approvedBy.length > 0 && approvals.approvalsLeft === 0,
261 approvalsLeft: approvals.approvalsLeft,
262 approvers: approvals.approvedBy.filter((name) => name !== me).toSorted(),
263 noteCursor: Math.max(0, ...notes.map((n) => n.id)),
264 notes: notes
265 .filter((n) => !n.isSystem && n.author !== me)
266 .map(({ id, author }) => ({ id, author })),
267 };
268}
269
270const isBlocked = (block: Block | undefined): block is "conflict" | "behind" =>
271 block === "conflict" || block === "behind";
272
273/** What an MR first seen already blocked has to say. Nothing else counts at baseline. */
274export function baselineOf(snapshot: Snapshot): Promoted[] {
275 if (!isOpen(snapshot) || !isBlocked(snapshot.block)) return [];
276 return [{ action: "promote", kind: snapshot.block }];
277}
278
279type Feedback = Extract<Promoted, { kind: "feedback" }>;
280
281function feedbackOf(prev: Snapshot, next: Snapshot, isSameHead: boolean): Decision[] {
282 const decisions: Decision[] = [];
283 const byAuthor = new Map<string, Feedback>();
284 const entry = (author: string): Feedback => {
285 const held = byAuthor.get(author) ?? {
286 action: "promote",
287 kind: "feedback",
288 author,
289 approval: null,
290 notes: 0,
291 };
292 byAuthor.set(author, held);
293 return held;
294 };
295 const before = new Set(prev.approvers);
296 const after = new Set(next.approvers);
297 for (const author of next.approvers) {
298 if (!before.has(author)) entry(author).approval = "approved";
299 }
300 const removed = prev.approvers.filter((author) => !after.has(author));
301 // A push can reset approvals, which no reviewer did.
302 if (removed.length > 0 && !isSameHead) {
303 decisions.push({ action: "drop", kind: "approvals.reset", authors: removed });
304 } else {
305 for (const author of removed) entry(author).approval = "unapproved";
306 }
307 for (const note of next.notes.toSorted((a, b) => a.id - b.id)) {
308 if (note.id > prev.noteCursor) entry(note.author).notes += 1;
309 }
310
311 // GitLab names no reviewer for a request for changes.
312 if (next.isChangesRequested && !prev.isChangesRequested) {
313 decisions.push({ action: "promote", kind: "changes_requested" });
314 }
315 decisions.push(...byAuthor.values());
316 return decisions;
317}
318
319/**
320 * What changed between two polls of the same MR. The MR merging or closing, a
321 * new conflict or required rebase, a push from outside this checkout, a job
322 * that newly fails, a request for changes, and new approvals, unapprovals, or
323 * comments from someone else are promoted. Every other change is dropped.
324 */
325export function decide(prev: Snapshot, next: Snapshot): Decision[] {
326 if (!isOpen(next)) {
327 if (!isOpen(prev)) return [];
328 return [{ action: "promote", kind: next.state === "merged" ? "mr.merged" : "mr.closed" }];
329 }
330 const decisions: Decision[] = [];
331 const isSameHead = prev.head === next.head;
332 if (!isSameHead) {
333 decisions.push(
334 next.isHeadKnown
335 ? { action: "drop", kind: "push", from: prev.head }
336 : { action: "promote", kind: "push.foreign", from: prev.head },
337 );
338 }
339
340 // A reopened MR starts clear, so a block it still carries is news again.
341 const before = isOpen(prev) ? prev.block : "none";
342 if (isBlocked(next.block) && next.block !== before) {
343 decisions.push({ action: "promote", kind: next.block });
344 } else if (next.block === "none" && isBlocked(before)) {
345 decisions.push({ action: "drop", kind: "unblocked" });
346 }
347
348 const known = new Set(isSameHead ? prev.failed : []);
349 const failed = next.failed.filter((label) => !known.has(label));
350 if (failed.length > 0) decisions.push({ action: "promote", kind: "ci.failed", failed });
351 else if (next.phase !== prev.phase || !isSameHead) {
352 if (next.phase === "passing") decisions.push({ action: "drop", kind: "ci.passing" });
353 else if (next.phase === "pending") decisions.push({ action: "drop", kind: "ci.pending" });
354 else if (next.phase === "none") decisions.push({ action: "drop", kind: "ci.none" });
355 }
356
357 decisions.push(...feedbackOf(prev, next, isSameHead));
358 return decisions;
359}
360
361// An approval and its revocation cancel out, since the model saw neither.
362function approvalOf(carried: Approval, fresh: Approval): Approval {
363 if (fresh === null) return carried;
364 if (carried === null) return fresh;
365 return carried === fresh ? fresh : null;
366}
367
368/**
369 * Folds a retried send into fresh decisions as one message: the latest block,
370 * the earliest foreign push, every failed job once, and one entry per author
371 * holding their latest approval change.
372 */
373export function combine(carried: Promoted[], fresh: Promoted[]): Promoted[] {
374 const all = [...carried, ...fresh];
375 const ended = all.findLast((d) => d.kind === "mr.merged" || d.kind === "mr.closed");
376 if (ended !== undefined) return [ended];
377 const out: Promoted[] = [];
378 const block = all.findLast((d) => d.kind === "conflict" || d.kind === "behind");
379 if (block !== undefined) out.push(block);
380 const push = all.find((d) => d.kind === "push.foreign");
381 if (push !== undefined) out.push(push);
382 const failed = all.flatMap((d) => (d.kind === "ci.failed" ? d.failed : []));
383 if (failed.length > 0) {
384 out.push({ action: "promote", kind: "ci.failed", failed: [...new Set(failed)].toSorted() });
385 }
386 if (all.some((d) => d.kind === "changes_requested")) {
387 out.push({ action: "promote", kind: "changes_requested" });
388 }
389 const byAuthor = new Map<string, Feedback>();
390 for (const d of all) {
391 if (d.kind !== "feedback") continue;
392 const held = byAuthor.get(d.author);
393 byAuthor.set(d.author, {
394 ...d,
395 approval: approvalOf(held?.approval ?? null, d.approval),
396 notes: (held?.notes ?? 0) + d.notes,
397 });
398 }
399 out.push(...byAuthor.values());
400 return out;
401}
402
403const short = (sha: string) => sha.slice(0, 7);
404
405function listed(labels: string[], max = 3): string {
406 const head = labels.slice(0, max).map(shown).join(", ");
407 return labels.length > max ? `${head} (+${labels.length - max})` : head;
408}
409
410function feedbackLineOf(mr: string, decision: Feedback): string {
411 const { author, approval, notes } = decision;
412 const comments = notes === 1 ? "1 new comment" : `${notes} new comments`;
413 if (approval === null) return `@${author} commented on ${mr} (${comments})`;
414 const line =
415 approval === "approved"
416 ? `@${author} approved ${mr}`
417 : `@${author} revoked their approval of ${mr}`;
418 return notes > 0 ? `${line} (${comments})` : line;
419}
420
421function paragraphOf(
422 snapshot: Snapshot,
423 decision: Exclude<Promoted, { kind: "feedback" | "changes_requested" }>,
424): string {
425 const mr = `MR !${snapshot.mr}`;
426 const target = snapshot.target === "" ? "its target branch" : `\`${snapshot.target}\``;
427 if (decision.kind === "mr.merged") return `${mr} merged: ${snapshot.url}`;
428 if (decision.kind === "mr.closed") return `${mr} closed without merging: ${snapshot.url}`;
429 if (decision.kind === "conflict") {
430 return [
431 `${mr} has merge conflicts with ${target} at ${short(snapshot.head)}.`,
432 `Update the branch from ${target}, resolve the conflicts with the \`git:conflicts\` skill, and push.`,
433 ].join("\n");
434 }
435 if (decision.kind === "behind") {
436 return [
437 `${mr} is behind ${target} at ${short(snapshot.head)}, and merging requires a rebase.`,
438 `Rebase onto ${target}, resolve any conflicts with the \`git:conflicts\` skill, and push.`,
439 ].join("\n");
440 }
441 if (decision.kind === "push.foreign") {
442 return [
443 `${mr}'s branch moved from ${short(decision.from)} to ${short(snapshot.head)}, a commit this checkout does not have.`,
444 "Pull it before committing or pushing again.",
445 ].join("\n");
446 }
447 return [
448 `Pipeline failed on ${mr} at ${short(snapshot.head)}: ${decision.failed.map(shown).join(", ")}.`,
449 `Read the failure with \`glab ci get --merge-request=${snapshot.mr} --status=failed\` and \`glab ci trace <job> --pipeline-id ${snapshot.pipeline}\`.`,
450 ].join("\n");
451}
452
453export function messageOf(snapshot: Snapshot, promoted: Promoted[]): string {
454 const mr = `MR !${snapshot.mr}`;
455 const paragraphs: string[] = [];
456 const feedback: string[] = [];
457 for (const decision of promoted) {
458 if (decision.kind === "changes_requested") feedback.push(`Changes were requested on ${mr}`);
459 else if (decision.kind === "feedback") feedback.push(feedbackLineOf(mr, decision));
460 else paragraphs.push(paragraphOf(snapshot, decision));
461 }
462 if (feedback.length > 0) {
463 paragraphs.push(
464 [
465 ...feedback,
466 snapshot.url,
467 `Read the discussion with \`glab mr view ${snapshot.mr} --comments\`.`,
468 ].join("\n"),
469 );
470 }
471 if (isOpen(snapshot)) {
472 paragraphs.push(
473 "The gitlab plugin watches this MR's pipeline, reviews, comments, and mergeability, so polling them is unnecessary.",
474 );
475 }
476 return paragraphs.join("\n\n");
477}
478
479// Nerd Font Octicons, keyed by glyph name: nf-oct-git_merge is gitMerge.
480const OCT = {
481 alert: "\u{f421}",
482 check: "\u{f42e}",
483 checkCircle: "\u{f49e}",
484 dotFill: "\u{f444}",
485 eye: "\u{f441}",
486 fileDiff: "\u{f4d2}",
487 gitCompare: "\u{f47f}",
488 gitMerge: "\u{f419}",
489 gitPullRequestClosed: "\u{f4dc}",
490 xCircle: "\u{f52f}",
491};
492
493export const STALE = `${OCT.alert} stale`;
494
495const BLOCKS: Record<Block, string | undefined> = {
496 conflict: `${OCT.gitCompare} conflicts`,
497 behind: `${OCT.gitCompare} behind`,
498 none: undefined,
499};
500
501const ENDED: Partial<Record<string, string>> = {
502 merged: `${OCT.gitMerge} merged`,
503 closed: `${OCT.gitPullRequestClosed} closed`,
504};
505
506const CHECKS: Record<Phase, (snapshot: Snapshot) => string | undefined> = {
507 none: () => undefined,
508 pending: (s) => `${OCT.dotFill} CI ${s.total - s.pending}/${s.total}`,
509 passing: () => `${OCT.checkCircle} CI`,
510 failing: (s) => `${OCT.xCircle} ${listed(s.failed)}`,
511};
512
513function reviewOf(snapshot: Snapshot): string | undefined {
514 if (snapshot.isChangesRequested) return `${OCT.fileDiff} changes requested`;
515 if (snapshot.approvalsLeft > 0) {
516 const left = snapshot.approvalsLeft;
517 return `${OCT.eye} ${left} ${left === 1 ? "approval" : "approvals"} needed`;
518 }
519 return snapshot.isApproved ? `${OCT.check} approved` : undefined;
520}
521
522// The footer already links the MR, so the state rides after it on that line.
523export function statusOf(snapshot: Snapshot): string {
524 const ended = ENDED[snapshot.state];
525 if (ended !== undefined) return ended;
526 return [BLOCKS[snapshot.block ?? "none"], CHECKS[snapshot.phase](snapshot), reviewOf(snapshot)]
527 .filter((part) => part !== undefined)
528 .join(" · ");
529}
530