@leitwerk-dev/gitlab 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1160 @@
1
+ // src/client.ts
2
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
3
+ import { repositoryHttpsUrl as repositoryHttpsUrl2 } from "@leitwerk-dev/process-sdk";
4
+
5
+ // src/preflight.ts
6
+ import { execFile } from "child_process";
7
+ import { mkdtemp, rm, writeFile } from "fs/promises";
8
+ import { tmpdir } from "os";
9
+ import { join } from "path";
10
+ import { promisify } from "util";
11
+ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
12
+ var exec = promisify(execFile);
13
+ async function preflightGitLabRepository(input) {
14
+ const url = repositoryHttpsUrl(input.url);
15
+ if (url.origin !== input.origin)
16
+ throw new Error("GitLab repository origin does not match its profile");
17
+ const directory = await mkdtemp(join(tmpdir(), "leitwerk-gitlab-preflight-"));
18
+ try {
19
+ const askpass = join(directory, "askpass");
20
+ await writeFile(
21
+ askpass,
22
+ '#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" oauth2;; *) printf "%s\\n" "$LEITWERK_GITLAB_PREFLIGHT_TOKEN";; esac\n',
23
+ { mode: 448 }
24
+ );
25
+ const env = {
26
+ ...process.env,
27
+ GIT_CONFIG_NOSYSTEM: "1",
28
+ GIT_CONFIG_GLOBAL: "/dev/null",
29
+ GIT_TERMINAL_PROMPT: "0",
30
+ GIT_ASKPASS: askpass,
31
+ LEITWERK_GITLAB_PREFLIGHT_TOKEN: input.token
32
+ };
33
+ const git = (args) => exec("git", ["-c", "credential.helper=", "-c", "http.followRedirects=false", ...args], {
34
+ env,
35
+ signal: input.signal
36
+ });
37
+ await git(["check-ref-format", `refs/heads/${input.baseBranch}`]);
38
+ await git(["check-ref-format", `refs/heads/${input.workBranch}`]);
39
+ await git(["ls-remote", "--exit-code", input.url, `refs/heads/${input.baseBranch}`]);
40
+ await git(["init", "--quiet", directory]);
41
+ await git([
42
+ "-C",
43
+ directory,
44
+ "fetch",
45
+ "--quiet",
46
+ "--depth=1",
47
+ input.url,
48
+ `refs/heads/${input.baseBranch}`
49
+ ]);
50
+ await git([
51
+ "-C",
52
+ directory,
53
+ "push",
54
+ "--dry-run",
55
+ input.url,
56
+ `FETCH_HEAD:refs/heads/${input.workBranch}`
57
+ ]);
58
+ } catch {
59
+ throw new Error(
60
+ "GitLab HTTPS read/write admission failed; check repository access and write_repository scope"
61
+ );
62
+ } finally {
63
+ await rm(directory, { recursive: true, force: true });
64
+ }
65
+ }
66
+
67
+ // src/client.ts
68
+ var GitLabError = class extends Error {
69
+ /** @internal */
70
+ constructor(status, retryable) {
71
+ super(
72
+ `GitLab request failed (${status || "network unavailable"})${retryable ? "; retryable" : "; check profile and project access"}`
73
+ );
74
+ this.status = status;
75
+ this.retryable = retryable;
76
+ }
77
+ status;
78
+ retryable;
79
+ };
80
+ function parseGitLabProfiles(raw) {
81
+ const profiles = /* @__PURE__ */ new Map();
82
+ for (const [name, value] of Object.entries(
83
+ asUnknownRecord(asUnknownRecord(raw)?.profiles) ?? {}
84
+ )) {
85
+ const item = asUnknownRecord(value) ?? {};
86
+ const baseUrl = typeof item.base_url === "string" ? item.base_url.replace(/\/+$/, "") : "";
87
+ const url = repositoryHttpsUrl2(`${baseUrl}/` === "/" ? "" : `${baseUrl}/repository`);
88
+ if (url.origin !== baseUrl)
89
+ throw new Error(`GitLab profile '${name}' requires an HTTPS origin base_url`);
90
+ const configuredToken = typeof item.token === "string" ? item.token : "";
91
+ const token = configuredToken.startsWith("env:") ? process.env[configuredToken.slice(4)] ?? "" : configuredToken;
92
+ if (!token || /[\r\n\0]/.test(token))
93
+ throw new Error(`GitLab profile '${name}' requires a token`);
94
+ const identity = asUnknownRecord(item.git_identity);
95
+ if (identity && [identity.name, identity.email].some(
96
+ (v) => typeof v !== "string" || !v.trim() || /[\r\n<>]/.test(v)
97
+ ))
98
+ throw new Error(`GitLab profile '${name}' requires a valid git_identity name and email`);
99
+ profiles.set(name, {
100
+ baseUrl,
101
+ token,
102
+ ...identity ? { gitIdentity: { name: String(identity.name), email: String(identity.email) } } : {}
103
+ });
104
+ }
105
+ return profiles;
106
+ }
107
+ var projectPath = (id) => `/projects/${encodeURIComponent(id)}`;
108
+ var mrPath = (id, iid) => `${projectPath(id)}/merge_requests/${iid}`;
109
+ var GitLabClient = class {
110
+ /** @public */
111
+ baseUrl;
112
+ #profile;
113
+ #fetch;
114
+ #sleep;
115
+ /** @internal */
116
+ constructor(profile, options = {}) {
117
+ if (repositoryHttpsUrl2(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
118
+ throw new Error("GitLab requires an HTTPS origin baseUrl");
119
+ if (!profile.token || /[\r\n\0]/.test(profile.token))
120
+ throw new Error("GitLab requires a valid token");
121
+ this.#profile = profile;
122
+ this.baseUrl = profile.baseUrl;
123
+ this.#fetch = options.fetch ?? fetch;
124
+ this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
125
+ }
126
+ async response(path, signal, body, method) {
127
+ for (let attempt = 0; ; attempt++) {
128
+ let response;
129
+ try {
130
+ response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
131
+ method: method ?? (body === void 0 ? "GET" : "POST"),
132
+ redirect: "error",
133
+ headers: {
134
+ "PRIVATE-TOKEN": this.#profile.token,
135
+ Accept: "application/json",
136
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
137
+ },
138
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4),
139
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
140
+ });
141
+ } catch {
142
+ if (signal?.aborted) throw new GitLabError(0, true);
143
+ if (body !== void 0 || attempt >= 2) throw new GitLabError(0, true);
144
+ await this.#sleep(1e3 * 2 ** attempt);
145
+ continue;
146
+ }
147
+ if (response.ok) return response;
148
+ const retryable = response.status === 429 || response.status >= 500 || response.status === 408;
149
+ await response.body?.cancel();
150
+ if (!retryable || body !== void 0 || attempt >= 2)
151
+ throw new GitLabError(response.status, retryable);
152
+ const seconds = Number(response.headers.get("retry-after"));
153
+ await this.#sleep(Math.min(3e4, seconds > 0 ? seconds * 1e3 : 1e3 * 2 ** attempt));
154
+ }
155
+ }
156
+ async request(path, signal, body, method) {
157
+ return this.json(await this.response(path, signal, body, method));
158
+ }
159
+ async json(response) {
160
+ try {
161
+ return await response.json();
162
+ } catch {
163
+ throw new GitLabError(502, true);
164
+ }
165
+ }
166
+ async pages(path, signal) {
167
+ const rows = [];
168
+ let page = 1;
169
+ for (let n = 0; n < 1e4; n++) {
170
+ const response = await this.response(
171
+ `${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
172
+ signal
173
+ );
174
+ const batch = await this.json(response);
175
+ if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
176
+ rows.push(...batch);
177
+ const next = response.headers.get("x-next-page");
178
+ if (next === "" || next === null && batch.length < 100) return rows;
179
+ const nextPage = next === null ? page + 1 : Number(next);
180
+ if (!Number.isInteger(nextPage) || nextPage <= page)
181
+ throw new Error("Invalid GitLab pagination");
182
+ page = nextPage;
183
+ }
184
+ throw new Error("GitLab pagination limit exceeded; discovery incomplete");
185
+ }
186
+ /** @public */
187
+ listIssues(id, signal) {
188
+ return this.pages(`${projectPath(id)}/issues?state=opened&scope=all`, signal);
189
+ }
190
+ /** @public */
191
+ getIssue(id, iid, signal) {
192
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal);
193
+ }
194
+ /** @public */
195
+ updateIssue(id, iid, patch, signal) {
196
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal, patch, "PUT");
197
+ }
198
+ /** @public */
199
+ listIssueNotes(id, iid, signal) {
200
+ return this.pages(`${projectPath(id)}/issues/${iid}/notes`, signal);
201
+ }
202
+ /** @public */
203
+ addIssueNote(id, iid, body, signal) {
204
+ return this.request(`${projectPath(id)}/issues/${iid}/notes`, signal, { body });
205
+ }
206
+ /** @public */
207
+ listLabels(id, signal) {
208
+ return this.pages(`${projectPath(id)}/labels`, signal);
209
+ }
210
+ /** @public */
211
+ createLabel(id, name, signal) {
212
+ return this.request(`${projectPath(id)}/labels`, signal, { name, color: "#2da44e" });
213
+ }
214
+ /** @public */
215
+ listBranchMergeRequests(id, source, target, signal) {
216
+ return this.pages(
217
+ `${projectPath(id)}/merge_requests?state=all&source_branch=${encodeURIComponent(source)}&target_branch=${encodeURIComponent(target)}`,
218
+ signal
219
+ );
220
+ }
221
+ /** @public */
222
+ createMergeRequest(id, input, signal) {
223
+ return this.request(`${projectPath(id)}/merge_requests`, signal, {
224
+ ...input,
225
+ remove_source_branch: false
226
+ });
227
+ }
228
+ /** @public */
229
+ async preflightRepository(projectId, baseBranch, workBranch, signal) {
230
+ const project = await this.getProject(projectId, signal);
231
+ await preflightGitLabRepository({
232
+ url: project.http_url_to_repo,
233
+ origin: this.baseUrl,
234
+ token: this.#profile.token,
235
+ baseBranch,
236
+ workBranch,
237
+ signal
238
+ });
239
+ }
240
+ /** @public */
241
+ getProject(id, signal) {
242
+ return this.request(projectPath(id), signal);
243
+ }
244
+ /** @internal */
245
+ listProjects(signal) {
246
+ return this.pages("/projects?archived=false", signal);
247
+ }
248
+ /** @internal */
249
+ getGroup(id, signal) {
250
+ return this.request(`/groups/${encodeURIComponent(id)}`, signal);
251
+ }
252
+ /** @internal */
253
+ listGroupProjects(id, signal) {
254
+ return this.pages(
255
+ `/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
256
+ signal
257
+ );
258
+ }
259
+ /** @public */
260
+ listMergeRequests(id, label, signal) {
261
+ return this.pages(
262
+ `${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
263
+ signal
264
+ );
265
+ }
266
+ /** @internal */
267
+ getMergeRequest(id, iid, signal) {
268
+ return this.request(mrPath(id, iid), signal);
269
+ }
270
+ /** @public */
271
+ getChanges(id, iid, signal) {
272
+ return this.pages(`${mrPath(id, iid)}/diffs`, signal);
273
+ }
274
+ /** @public */
275
+ getBranch(id, branch, signal) {
276
+ return this.request(
277
+ `${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
278
+ signal
279
+ );
280
+ }
281
+ /** @internal */
282
+ getCommit(id, sha, signal) {
283
+ return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
284
+ }
285
+ /** @internal */
286
+ listMergeRequestPipelines(id, iid, signal) {
287
+ return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
288
+ }
289
+ /** @internal */
290
+ listBranchPipelines(id, branch, sha, signal) {
291
+ return this.pages(
292
+ `${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
293
+ signal
294
+ );
295
+ }
296
+ /** @internal */
297
+ getPipeline(id, pipeline, signal) {
298
+ return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
299
+ }
300
+ /** @public */
301
+ listFailedJobs(id, pipeline, signal) {
302
+ return this.pages(
303
+ `${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
304
+ signal
305
+ );
306
+ }
307
+ /** @internal */
308
+ listNotes(id, iid, signal) {
309
+ return this.pages(`${mrPath(id, iid)}/notes`, signal);
310
+ }
311
+ /** @internal */
312
+ getDiscussion(id, iid, discussionId, signal) {
313
+ return this.request(
314
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
315
+ signal
316
+ );
317
+ }
318
+ /** @internal */
319
+ replyToDiscussion(id, iid, discussionId, body, signal) {
320
+ return this.request(
321
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
322
+ signal,
323
+ { body }
324
+ );
325
+ }
326
+ /** @internal */
327
+ listNoteReactions(id, iid, noteId, signal) {
328
+ return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
329
+ }
330
+ /** @internal */
331
+ addNoteReaction(id, iid, noteId, name, signal) {
332
+ return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
333
+ }
334
+ /** @public */
335
+ async listMergeRequestFeedback(id, iid, signal) {
336
+ const discussions = await this.pages(
337
+ `${mrPath(id, iid)}/discussions`,
338
+ signal
339
+ );
340
+ const feedback = [];
341
+ for (const discussion of discussions) {
342
+ for (const note of discussion.notes) {
343
+ if (note.system || note.resolved || note.author.bot || /<!-- leitwerk:gitlab:[a-f0-9]{64} -->/.test(note.body) || !note.body.trim() || !Number.isFinite(Date.parse(note.created_at)))
344
+ continue;
345
+ const position = note.position ?? discussion.notes[0]?.position;
346
+ feedback.push({
347
+ id: note.id,
348
+ discussionId: discussion.id,
349
+ body: note.body,
350
+ author: note.author.username,
351
+ createdAt: note.created_at,
352
+ ...position ? {
353
+ path: position.new_path ?? position.old_path,
354
+ line: position.new_line ?? position.old_line
355
+ } : {}
356
+ });
357
+ }
358
+ }
359
+ return feedback.sort((a, b) => a.id - b.id);
360
+ }
361
+ /** @internal */
362
+ addNote(id, iid, body, signal) {
363
+ return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
364
+ }
365
+ /** @public */
366
+ async resolveGitIdentity(signal) {
367
+ const user = await this.request("/user", signal);
368
+ const name = this.#profile.gitIdentity?.name ?? user.name;
369
+ const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
370
+ if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
371
+ throw new Error(
372
+ "GitLab bot Git identity is unavailable; configure git_identity on the profile"
373
+ );
374
+ return { name, email, username: user.username };
375
+ }
376
+ /** @public */
377
+ async getJobTrace(id, job, maxBytes = 65536, signal) {
378
+ const limit = Math.min(262144, Math.max(1, Math.floor(maxBytes) || 65536));
379
+ const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
380
+ const reader = response.body?.getReader();
381
+ if (!reader) return { text: "", truncated: false };
382
+ const chunks = [];
383
+ let size = 0;
384
+ let truncated = false;
385
+ try {
386
+ while (true) {
387
+ const item = await reader.read();
388
+ if (item.done) break;
389
+ const take = Math.min(item.value.length, limit - size);
390
+ chunks.push(item.value.slice(0, take));
391
+ size += take;
392
+ if (size >= limit) {
393
+ truncated = true;
394
+ break;
395
+ }
396
+ }
397
+ } finally {
398
+ await reader.cancel();
399
+ }
400
+ return { text: Buffer.concat(chunks).toString("utf8"), truncated };
401
+ }
402
+ };
403
+ async function observeMergeRequest(client, projectId, iid, signal) {
404
+ const mr = await client.getMergeRequest(projectId, iid, signal);
405
+ if (mr.state !== "opened") return { mr, pipeline: null };
406
+ const targetHead = (await client.getBranch(mr.target_project_id, mr.target_branch, signal)).commit.id;
407
+ const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
408
+ (a, b) => b.id - a.id
409
+ );
410
+ for (const candidate of associated) {
411
+ const id = candidate.project_id ?? projectId;
412
+ let matches = candidate.sha === mr.sha;
413
+ if (!matches && (candidate.ref === `refs/merge-requests/${iid}/merge` || candidate.sha === mr.merge_commit_sha)) {
414
+ const commit = await client.getCommit(id, candidate.sha, signal);
415
+ matches = commit.parent_ids.includes(mr.sha);
416
+ }
417
+ if (matches)
418
+ return { mr, targetHead, pipeline: await client.getPipeline(id, candidate.id, signal) };
419
+ }
420
+ const candidates = await client.listBranchPipelines(
421
+ mr.source_project_id,
422
+ mr.source_branch,
423
+ mr.sha,
424
+ signal
425
+ );
426
+ const latest = candidates.filter((p) => p.sha === mr.sha && p.ref === mr.source_branch && p.source === "push").sort((a, b) => b.id - a.id)[0];
427
+ return {
428
+ mr,
429
+ targetHead,
430
+ pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null
431
+ };
432
+ }
433
+
434
+ // src/capability.ts
435
+ import {
436
+ createCapabilityToken
437
+ } from "@leitwerk-dev/process-sdk";
438
+ var gitlabIntegration = createCapabilityToken(
439
+ "@leitwerk-dev/gitlab.integration"
440
+ );
441
+ function gitlabRepositoryCredentials(profile, projects) {
442
+ return projects.map((project) => ({
443
+ projectKey: project.key,
444
+ kind: "git_https",
445
+ credentialRef: `gitlab:${profile}`
446
+ }));
447
+ }
448
+
449
+ // src/tools.ts
450
+ import { createHash } from "crypto";
451
+ import {
452
+ numberArg,
453
+ projectParameters,
454
+ stringArg
455
+ } from "@leitwerk-dev/process-sdk";
456
+ async function existingRemote(read) {
457
+ try {
458
+ return await read();
459
+ } catch (error) {
460
+ if (error instanceof GitLabError && error.status === 404) return null;
461
+ throw error;
462
+ }
463
+ }
464
+ function resolveGitLabRepositoryBinding(ctx) {
465
+ if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
466
+ throw new Error("An authorized GitLab process project is required");
467
+ const binding = ctx.project.metadata?.gitlab;
468
+ if (!binding || typeof binding.profile !== "string" || !binding.profile.trim() || typeof binding.projectId !== "number" || !Number.isSafeInteger(binding.projectId) || binding.projectId <= 0)
469
+ throw new Error("Invalid GitLab project binding");
470
+ return { profile: binding.profile, projectId: binding.projectId };
471
+ }
472
+ function resolveGitLabBinding(ctx) {
473
+ const repository = resolveGitLabRepositoryBinding(ctx);
474
+ const iid = ctx.project?.metadata?.gitlab?.iid;
475
+ if (typeof iid !== "number" || !Number.isSafeInteger(iid) || iid <= 0)
476
+ throw new Error("Invalid GitLab project binding: a merge request is required");
477
+ return { ...repository, iid };
478
+ }
479
+ async function ensureGitLabComment(input) {
480
+ const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
481
+ const identity = [client.baseUrl, projectId, iid, instanceId, writeKey];
482
+ if (input.discussionId) identity.push(input.discussionId);
483
+ const digest = createHash("sha256").update(JSON.stringify(identity)).digest("hex");
484
+ const marker = `<!-- leitwerk:gitlab:${digest} -->`;
485
+ const find = async () => {
486
+ const notes = input.discussionId ? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes : await client.listNotes(projectId, iid, signal);
487
+ return notes.find((note) => note.body.includes(marker));
488
+ };
489
+ await writes.ensure(
490
+ { writeType: "gitlab.comment", dedupKey: digest },
491
+ {
492
+ reconcile: () => existingRemote(async () => await find() ?? null),
493
+ execute: () => {
494
+ const body = `${input.body}
495
+
496
+ ${marker}`;
497
+ return input.discussionId ? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal) : client.addNote(projectId, iid, body, signal);
498
+ },
499
+ toMetadata: (note) => ({ projectId, iid, noteId: note.id, marker })
500
+ }
501
+ );
502
+ return { marker };
503
+ }
504
+ async function ensureGitLabSeenReaction(input) {
505
+ const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
506
+ const digest = createHash("sha256").update(JSON.stringify([client.baseUrl, projectId, iid, instanceId, "eyes", noteId])).digest("hex");
507
+ await writes.ensure(
508
+ { writeType: "gitlab.reaction", dedupKey: digest },
509
+ {
510
+ reconcile: () => existingRemote(async () => {
511
+ const identity = await client.resolveGitIdentity(signal);
512
+ return (await client.listNoteReactions(projectId, iid, noteId, signal)).find(
513
+ (reaction) => reaction.name === "eyes" && reaction.user.username === identity.username
514
+ ) ?? null;
515
+ }),
516
+ execute: () => client.addNoteReaction(projectId, iid, noteId, "eyes", signal),
517
+ toMetadata: (reaction) => ({ projectId, iid, noteId, reactionId: reaction.id, name: "eyes" })
518
+ }
519
+ );
520
+ }
521
+ function registerGitLabTools(api, integration) {
522
+ for (const [name, description, required] of [
523
+ ["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
524
+ ["gitlab_get_changes", "Read the MR changes", []],
525
+ ["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
526
+ ["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
527
+ [
528
+ "gitlab_get_job_trace",
529
+ "Read a bounded trace from a failed MR pipeline job",
530
+ ["pipelineId", "jobId"]
531
+ ],
532
+ ["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
533
+ [
534
+ "gitlab_reply",
535
+ "Post a retry-safe reply in an MR discussion",
536
+ ["body", "writeKey", "discussionId"]
537
+ ]
538
+ ]) {
539
+ api.tool({
540
+ name,
541
+ description,
542
+ parameters: projectParameters(
543
+ {
544
+ pipelineId: { type: "integer" },
545
+ jobId: { type: "integer" },
546
+ maxBytes: { type: "integer" },
547
+ body: { type: "string" },
548
+ writeKey: { type: "string" },
549
+ discussionId: { type: "string" }
550
+ },
551
+ [...required]
552
+ ),
553
+ async execute(ctx, args) {
554
+ if (name === "gitlab_get_identity")
555
+ return integration.client(resolveGitLabRepositoryBinding(ctx).profile).resolveGitIdentity(ctx.signal);
556
+ const b = resolveGitLabBinding(ctx);
557
+ const client = integration.client(b.profile);
558
+ if (name === "gitlab_observe_merge_request")
559
+ return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
560
+ if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
561
+ if (name === "gitlab_comment" || name === "gitlab_reply")
562
+ return ensureGitLabComment({
563
+ client,
564
+ writes: ctx.externalWrites,
565
+ instanceId: ctx.process.id,
566
+ projectId: b.projectId,
567
+ iid: b.iid,
568
+ writeKey: stringArg(args, "writeKey"),
569
+ body: stringArg(args, "body"),
570
+ ...name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {},
571
+ signal: ctx.signal
572
+ });
573
+ const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
574
+ if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
575
+ throw new Error("Pipeline is not current for the authorized MR");
576
+ const jobs = await client.listFailedJobs(
577
+ observation.pipeline.project_id,
578
+ observation.pipeline.id,
579
+ ctx.signal
580
+ );
581
+ if (name === "gitlab_list_failed_jobs") return jobs;
582
+ const job = jobs.find((job2) => job2.id === numberArg(args, "jobId"));
583
+ if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
584
+ return client.getJobTrace(
585
+ observation.pipeline.project_id,
586
+ job.id,
587
+ typeof args.maxBytes === "number" ? args.maxBytes : void 0,
588
+ ctx.signal
589
+ );
590
+ }
591
+ });
592
+ }
593
+ }
594
+
595
+ // src/selection.ts
596
+ function parseGitLabSelection(raw) {
597
+ const list = (value) => {
598
+ if (value === void 0) return [];
599
+ if (!Array.isArray(value) || value.some(
600
+ (v) => typeof v !== "string" || !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(v) || v.split("/").some((p) => p === "." || p === "..")
601
+ ))
602
+ throw new Error("GitLab selectors require exact namespace paths");
603
+ return [...new Set(value)];
604
+ };
605
+ const pair = (value) => {
606
+ if (value !== void 0 && (!value || typeof value !== "object" || Array.isArray(value)))
607
+ throw new Error("GitLab selectors must be objects");
608
+ const item = value;
609
+ return { include: list(item?.include), exclude: list(item?.exclude) };
610
+ };
611
+ if (raw.all_accessible !== void 0 && typeof raw.all_accessible !== "boolean")
612
+ throw new Error("all_accessible must be a boolean");
613
+ const parsed = {
614
+ projects: pair(raw.projects),
615
+ groups: pair(raw.groups),
616
+ allAccessible: raw.all_accessible === true
617
+ };
618
+ if (!parsed.allAccessible && !parsed.projects.include.length && !parsed.groups.include.length)
619
+ throw new Error("GitLab requires explicit project/group includes or all_accessible: true");
620
+ return parsed;
621
+ }
622
+ function projectExcluded(selection, name) {
623
+ return selection.projects.exclude.includes(name) || selection.groups.exclude.some((group) => name.startsWith(`${group}/`));
624
+ }
625
+ async function selectGitLabProjects(client, selection) {
626
+ const candidates = selection.allAccessible ? await client.listProjects() : [];
627
+ for (const name of selection.projects.include) candidates.push(await client.getProject(name));
628
+ for (const group of selection.groups.include)
629
+ candidates.push(...await client.listGroupProjects(group));
630
+ return [
631
+ ...new Map(
632
+ candidates.filter((p) => !p.archived && !projectExcluded(selection, p.path_with_namespace)).map((p) => [p.id, p])
633
+ ).values()
634
+ ];
635
+ }
636
+
637
+ // src/issue-watcher.ts
638
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
639
+ import {
640
+ defineProcessWatcherSource,
641
+ parseProcessWatcherLaunchModelConfig
642
+ } from "@leitwerk-dev/process-sdk";
643
+ import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
644
+ var gitlabIssueExternalId = (origin, projectId, iid) => `gitlab:${origin}:${projectId}#${iid}`;
645
+ var gitlabIssueWatcherSource = defineProcessWatcherSource({
646
+ id: "@leitwerk-dev/gitlab.issue",
647
+ label: "GitLab issue",
648
+ parseConfig(raw) {
649
+ const c = asUnknownRecord2(raw);
650
+ if (!c || typeof c.enabled !== "boolean") throw new Error("GitLab watcher requires enabled");
651
+ const text = (value, name) => {
652
+ if (typeof value !== "string" || !value.trim())
653
+ throw new Error(`GitLab watcher requires ${name}`);
654
+ return value.trim();
655
+ };
656
+ const labels = asUnknownRecord2(c.labels) ?? {};
657
+ const trigger = text(labels.trigger, "labels.trigger");
658
+ const done = text(labels.done, "labels.done");
659
+ if (trigger === done || trigger.includes(",") || done.includes(","))
660
+ throw new Error("GitLab trigger/done labels must be distinct and contain no comma");
661
+ const pollInterval = text(c.poll_interval ?? "30s", "poll_interval");
662
+ if (parseDurationMs(pollInterval, -1) <= 0) throw new Error("Invalid GitLab polling interval");
663
+ return {
664
+ enabled: c.enabled,
665
+ config: {
666
+ ...parseGitLabSelection(c),
667
+ profile: text(c.profile, "profile"),
668
+ pollInterval,
669
+ labels: { trigger, done }
670
+ },
671
+ launchModelConfig: parseProcessWatcherLaunchModelConfig(c.launch)
672
+ };
673
+ },
674
+ presentConfig(c) {
675
+ return {
676
+ targetSummary: `Profile ${c.profile} \xB7 trigger ${c.labels.trigger}`,
677
+ details: [
678
+ { label: "Projects", value: c.projects.include.join(", ") || "selected groups" },
679
+ { label: "Groups", value: c.groups.include.join(", ") || "none" }
680
+ ]
681
+ };
682
+ }
683
+ });
684
+ function createGitLabIssueDiscovery(deps, integration, now) {
685
+ const due = /* @__PURE__ */ new Map();
686
+ return async (result) => {
687
+ for (const watcher of deps.processWatchers?.listBySource(gitlabIssueWatcherSource) ?? []) {
688
+ if (!watcher.enabled) continue;
689
+ const key = `${watcher.processId}:${watcher.watcherId}`;
690
+ const c = watcher.config;
691
+ const eligible = (issue) => issue.state === "opened" && issue.labels.includes(c.labels.trigger) && !issue.labels.includes(c.labels.done);
692
+ if ((due.get(key) ?? 0) > now()) continue;
693
+ due.set(key, now() + parseDurationMs(c.pollInterval, 3e4));
694
+ const client = integration.client(c.profile);
695
+ for (const repository of await selectGitLabProjects(client, c))
696
+ for (const issue of await client.listIssues(repository.id)) {
697
+ if (!eligible(issue)) continue;
698
+ const id = gitlabIssueExternalId(client.baseUrl, repository.id, issue.iid);
699
+ if (deps.processes.listAll().some((p) => p.externalId === id)) {
700
+ result.skipped.push(id);
701
+ continue;
702
+ }
703
+ const guarded = {
704
+ ...watcher,
705
+ async resolveLaunchAttempt(...args) {
706
+ const attempt = await watcher.resolveLaunchAttempt(...args);
707
+ if (!attempt) return null;
708
+ return {
709
+ ...attempt,
710
+ preparationChecks: [
711
+ ...attempt.preparationChecks,
712
+ {
713
+ id: "gitlab-issue-eligibility",
714
+ label: "Recheck GitLab source issue",
715
+ async run() {
716
+ const fresh = await client.getIssue(repository.id, issue.iid);
717
+ if (!eligible(fresh))
718
+ throw new Error("GitLab source issue eligibility changed before launch");
719
+ }
720
+ }
721
+ ]
722
+ };
723
+ }
724
+ };
725
+ const launched = await deps.launchRuns.startWatcher(
726
+ guarded,
727
+ { profile: c.profile, repository, issue, labels: c.labels },
728
+ { idempotencyKey: id }
729
+ );
730
+ if (launched.error) result.errors.push(`${id}:launch_failed`);
731
+ else if (launched.process) result.created.push(id);
732
+ else result.skipped.push(id);
733
+ }
734
+ }
735
+ };
736
+ }
737
+
738
+ // src/external.ts
739
+ import { conflictKey } from "@leitwerk-dev/coding/repository-rebase";
740
+ import {
741
+ createExternalSourcePollReporter
742
+ } from "@leitwerk-dev/process-sdk";
743
+ import { emptyPollResult, parseDurationMs as parseDurationMs2 } from "@leitwerk-dev/watcher-utils";
744
+ var GITLAB_ISSUE_CANCELLED_KIND = "@leitwerk-dev/gitlab.issue-cancelled";
745
+ var GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
746
+ function pendingGitLabFeedback(items, afterId, since) {
747
+ const start = since ? Date.parse(since) : 0;
748
+ return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
749
+ }
750
+ function gitLabFeedbackReadyAt(items, quietPeriodMs) {
751
+ return items.length ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs : null;
752
+ }
753
+ var observationKey = ({ mr, pipeline, targetHead }) => JSON.stringify([
754
+ mr.state,
755
+ mr.sha,
756
+ [...mr.labels].sort(),
757
+ pipeline?.project_id,
758
+ pipeline?.id,
759
+ pipeline?.status,
760
+ mr.source_project_id,
761
+ mr.source_branch,
762
+ mr.target_project_id,
763
+ mr.target_branch,
764
+ targetHead,
765
+ mr.has_conflicts,
766
+ mr.merge_status,
767
+ mr.detailed_merge_status
768
+ ]);
769
+ var gitlabExternal = {
770
+ /** @public */
771
+ issueCancelled(resolve) {
772
+ return {
773
+ kind: GITLAB_ISSUE_CANCELLED_KIND,
774
+ label: "GitLab source issue cancelled",
775
+ config: {},
776
+ inputMode: "none",
777
+ resolve
778
+ };
779
+ },
780
+ /** @public */
781
+ mergeRequest(resolve) {
782
+ return {
783
+ kind: GITLAB_MR_KIND,
784
+ label: "GitLab merge request",
785
+ description: "Observe MR state, current source head and revision-correlated CI",
786
+ config: {},
787
+ inputMode: "none",
788
+ resolve
789
+ };
790
+ }
791
+ };
792
+ function createGitLabProvider(deps, integration, options = {}) {
793
+ const schedule = /* @__PURE__ */ new Map();
794
+ const now = options.now ?? Date.now;
795
+ const discover = createGitLabIssueDiscovery(deps, integration, now);
796
+ return deps.polling.create({
797
+ id: "gitlab",
798
+ pollInterval: () => "5s",
799
+ isEnabled: () => true,
800
+ defaultIntervalMs: 5e3,
801
+ async pollOnce() {
802
+ const result = emptyPollResult();
803
+ try {
804
+ await discover(result);
805
+ } catch (error) {
806
+ result.errors.push(error instanceof Error ? error.message : "GitLab discovery failed");
807
+ }
808
+ const reporter = createExternalSourcePollReporter(deps.externalSources, result, {
809
+ forwardGeneration: true
810
+ });
811
+ const current = (armed) => [GITLAB_MR_KIND, GITLAB_ISSUE_CANCELLED_KIND].some(
812
+ (kind) => reporter.isCurrent(kind, armed)
813
+ );
814
+ const report = {
815
+ ...reporter,
816
+ fire(armed, event, mergeKey) {
817
+ return current(armed) ? reporter.fire(armed, event, mergeKey) : Promise.resolve(false);
818
+ },
819
+ observe(armed, input) {
820
+ if (current(armed)) return reporter.observe(armed, input);
821
+ }
822
+ };
823
+ await report.poll(GITLAB_MR_KIND, async (armed) => {
824
+ const c = armed.resolved;
825
+ if (!c || typeof c.profile !== "string" || !Number.isInteger(c.projectId) || !Number.isInteger(c.iid))
826
+ throw new Error("Invalid GitLab external source");
827
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
828
+ const previous = schedule.get(key);
829
+ if (previous && previous.at > now()) return;
830
+ try {
831
+ const observation = await observeMergeRequest(
832
+ integration.client(c.profile),
833
+ c.projectId,
834
+ c.iid
835
+ );
836
+ let conflict;
837
+ const client = integration.client(c.profile);
838
+ if (c.delivery && observation.mr.state === "opened" && observation.mr.sha === c.delivery.headSha && (observation.mr.has_conflicts === true || observation.mr.detailed_merge_status === "conflict")) {
839
+ const mr = observation.mr;
840
+ const d = c.delivery;
841
+ if (mr.source_project_id !== c.projectId || mr.target_project_id !== c.projectId || mr.source_branch !== d.headBranch || mr.target_branch !== d.baseBranch)
842
+ throw new Error("GitLab merge request branches changed");
843
+ const base = await client.getBranch(c.projectId, d.baseBranch);
844
+ const evidence = {
845
+ owner: d.owner,
846
+ repo: d.repo,
847
+ prNumber: c.iid,
848
+ headBranch: d.headBranch,
849
+ baseBranch: d.baseBranch,
850
+ headSha: mr.sha,
851
+ baseSha: base.commit.id,
852
+ url: mr.web_url
853
+ };
854
+ if (conflictKey(evidence) !== d.lastConflictKey) conflict = evidence;
855
+ }
856
+ const observedKey = observationKey(observation) + (c.delivery ? `:${conflict ? conflictKey(conflict) : ""}` : "");
857
+ const feedback = c.feedback && observation.mr.state === "opened" ? pendingGitLabFeedback(
858
+ await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
859
+ c.feedback.afterId,
860
+ c.feedback.since
861
+ ) : [];
862
+ const feedbackReadyAt = gitLabFeedbackReadyAt(
863
+ feedback,
864
+ c.feedback?.quietPeriodMs ?? 12e4
865
+ );
866
+ const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
867
+ if (c.delivery) {
868
+ const fresh = await client.getMergeRequest(c.projectId, c.iid);
869
+ if (fresh.sha !== observation.mr.sha || fresh.state !== observation.mr.state) return;
870
+ }
871
+ await report.observe(armed, {
872
+ observation: {
873
+ summary: `${observation.mr.state} \xB7 ${observation.pipeline?.status ?? "no current pipeline"}`,
874
+ observedAt: new Date(now()).toISOString(),
875
+ subject: observation.mr.web_url,
876
+ revision: observation.mr.sha
877
+ }
878
+ });
879
+ if (observedKey !== c.afterKey || feedbackReady || c.wakeAt !== void 0 && c.wakeAt <= now())
880
+ await report.fire(
881
+ armed,
882
+ {
883
+ ...observation,
884
+ ...c.delivery ? {
885
+ observationKey: observedKey,
886
+ feedback: feedbackReady ? feedback : [],
887
+ ...conflict ? { conflict } : {}
888
+ } : {}
889
+ },
890
+ `${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`
891
+ );
892
+ schedule.set(key, {
893
+ at: now() + parseDurationMs2(c.pollInterval ?? "30s", 3e4),
894
+ failures: 0
895
+ });
896
+ } catch (error) {
897
+ const failures = (previous?.failures ?? 0) + 1;
898
+ schedule.set(key, {
899
+ at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
900
+ failures
901
+ });
902
+ await report.observe(armed, {
903
+ refreshError: error instanceof Error ? error.message : "GitLab observation unavailable"
904
+ });
905
+ throw error;
906
+ }
907
+ });
908
+ await report.poll(GITLAB_ISSUE_CANCELLED_KIND, async (armed) => {
909
+ const c = armed.resolved;
910
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
911
+ if ((schedule.get(key)?.at ?? 0) > now()) return;
912
+ const client = integration.client(c.profile);
913
+ const issue = await client.getIssue(c.projectId, c.issueIid);
914
+ if (issue.state !== "opened" || !issue.labels.includes(c.triggerLabel)) {
915
+ const mr = await client.getMergeRequest(c.projectId, c.iid);
916
+ if (mr.state !== "opened") return;
917
+ await report.fire(
918
+ armed,
919
+ { issue },
920
+ `${issue.iid}:${issue.state}:${issue.labels.includes(c.triggerLabel)}`
921
+ );
922
+ }
923
+ schedule.set(key, {
924
+ at: now() + parseDurationMs2(c.pollInterval ?? "30s", 3e4),
925
+ failures: 0
926
+ });
927
+ });
928
+ return result;
929
+ }
930
+ });
931
+ }
932
+
933
+ // src/setup.ts
934
+ import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
935
+
936
+ // src/delivery-tools.ts
937
+ import { createHash as createHash2 } from "crypto";
938
+ import {
939
+ numberArg as numberArg2,
940
+ projectParameters as projectParameters2,
941
+ stringArg as stringArg2
942
+ } from "@leitwerk-dev/process-sdk";
943
+ function registerGitLabDeliveryTools(api, integration, projects) {
944
+ api.tool({
945
+ name: "gitlab_ensure_merge_request",
946
+ description: "Create or reconcile and pin the process merge request",
947
+ parameters: projectParameters2({ title: { type: "string" }, body: { type: "string" } }, [
948
+ "title",
949
+ "body"
950
+ ]),
951
+ async execute(ctx, args) {
952
+ const binding = resolveGitLabRepositoryBinding(ctx);
953
+ const client = integration.client(binding.profile);
954
+ const project = projects.getByInstanceAndKey(ctx.process.id, ctx.project?.key ?? "");
955
+ if (!project?.workBranch || project.workBranch === project.baseBranch)
956
+ throw new Error("A process feature branch is required");
957
+ const workBranch = project.workBranch;
958
+ const identity = {
959
+ writeType: "gitlab.ensure_mr",
960
+ dedupKey: `${binding.projectId}:${project.key}:${workBranch}:${project.baseBranch}`
961
+ };
962
+ const marker = `<!-- leitwerk:gitlab:merge-request:${ctx.process.id}:${project.key} -->`;
963
+ const find = async () => (await client.listBranchMergeRequests(
964
+ binding.projectId,
965
+ workBranch,
966
+ project.baseBranch,
967
+ ctx.signal
968
+ )).find(
969
+ (mr) => mr.source_project_id === binding.projectId && mr.target_project_id === binding.projectId && mr.source_branch === project.workBranch && mr.target_branch === project.baseBranch && mr.description?.includes(marker)
970
+ );
971
+ const request = await ctx.externalWrites.ensure(identity, {
972
+ reconcile: async () => await find() ?? null,
973
+ execute: () => client.createMergeRequest(
974
+ binding.projectId,
975
+ {
976
+ title: stringArg2(args, "title"),
977
+ description: `${stringArg2(args, "body")}
978
+
979
+ ${marker}`,
980
+ source_branch: workBranch,
981
+ target_branch: project.baseBranch
982
+ },
983
+ ctx.signal
984
+ ),
985
+ toMetadata: (mr) => ({ iid: mr.iid, url: mr.web_url })
986
+ });
987
+ const latest = projects.getByInstanceAndKey(ctx.process.id, project.key);
988
+ if (!latest || latest.workBranch !== project.workBranch || latest.baseBranch !== project.baseBranch)
989
+ throw new Error("Process repository binding changed during publication");
990
+ const metadata = latest.metadata ?? {};
991
+ const previous = metadata.gitlab;
992
+ if (previous.iid && previous.iid !== request.iid)
993
+ throw new Error("Process is already bound to another merge request");
994
+ projects.update(latest.id, {
995
+ metadata: { ...metadata, gitlab: { ...previous, ...binding, iid: request.iid } },
996
+ externalId: String(request.iid),
997
+ externalUrl: request.web_url
998
+ });
999
+ return request;
1000
+ }
1001
+ });
1002
+ api.tool({
1003
+ name: "gitlab_list_merge_request_feedback",
1004
+ description: "Read human discussion feedback on the bound merge request",
1005
+ parameters: projectParameters2(),
1006
+ async execute(ctx) {
1007
+ const b = resolveGitLabBinding(ctx);
1008
+ return integration.client(b.profile).listMergeRequestFeedback(b.projectId, b.iid, ctx.signal);
1009
+ }
1010
+ });
1011
+ api.tool({
1012
+ name: "gitlab_acknowledge_feedback",
1013
+ description: "Reconcile the bot's seen reaction on bound merge request feedback",
1014
+ parameters: projectParameters2({ noteId: { type: "integer" } }, ["noteId"]),
1015
+ async execute(ctx, args) {
1016
+ const b = resolveGitLabBinding(ctx);
1017
+ const client = integration.client(b.profile);
1018
+ const noteId = numberArg2(args, "noteId");
1019
+ if (!(await client.listMergeRequestFeedback(b.projectId, b.iid, ctx.signal)).some(
1020
+ (n) => n.id === noteId
1021
+ ))
1022
+ throw new Error("Note is not actionable feedback on the bound merge request");
1023
+ await ensureGitLabSeenReaction({
1024
+ client,
1025
+ writes: ctx.externalWrites,
1026
+ instanceId: ctx.process.id,
1027
+ projectId: b.projectId,
1028
+ iid: b.iid,
1029
+ noteId,
1030
+ signal: ctx.signal
1031
+ });
1032
+ return { ok: true };
1033
+ }
1034
+ });
1035
+ for (const name of [
1036
+ "gitlab_get_issue",
1037
+ "gitlab_add_issue_comment",
1038
+ "gitlab_finalize_source_issue"
1039
+ ]) {
1040
+ api.tool({
1041
+ name,
1042
+ description: "Read or reconcile the process source issue",
1043
+ parameters: projectParameters2(
1044
+ {
1045
+ issueNumber: { type: "integer" },
1046
+ body: { type: "string" },
1047
+ writeKey: { type: "string" },
1048
+ merged: { type: "boolean" },
1049
+ triggerLabel: { type: "string" },
1050
+ doneLabel: { type: "string" }
1051
+ },
1052
+ ["issueNumber"]
1053
+ ),
1054
+ async execute(ctx, args) {
1055
+ const b = resolveGitLabRepositoryBinding(ctx);
1056
+ const client = integration.client(b.profile);
1057
+ const iid = numberArg2(args, "issueNumber");
1058
+ const bound = ctx.project?.metadata?.gitlab?.issueIid;
1059
+ if (bound !== iid) throw new Error("Issue does not match the process source issue");
1060
+ if (name === "gitlab_get_issue") return client.getIssue(b.projectId, iid, ctx.signal);
1061
+ const key = stringArg2(args, "writeKey");
1062
+ const digest = createHash2("sha256").update(JSON.stringify([client.baseUrl, b.projectId, iid, ctx.process.id, key])).digest("hex");
1063
+ if (name === "gitlab_add_issue_comment") {
1064
+ const marker = `<!-- leitwerk:gitlab:issue:${digest} -->`;
1065
+ const note = await ctx.externalWrites.ensure(
1066
+ { writeType: name, dedupKey: digest },
1067
+ {
1068
+ reconcile: async () => (await client.listIssueNotes(b.projectId, iid, ctx.signal)).find(
1069
+ (n) => n.body.includes(marker)
1070
+ ) ?? null,
1071
+ execute: () => client.addIssueNote(
1072
+ b.projectId,
1073
+ iid,
1074
+ `${stringArg2(args, "body")}
1075
+
1076
+ ${marker}`,
1077
+ ctx.signal
1078
+ ),
1079
+ toMetadata: (note2) => ({ noteId: note2.id })
1080
+ }
1081
+ );
1082
+ return { noteId: note.id };
1083
+ }
1084
+ const merged = args.merged === true;
1085
+ const trigger = stringArg2(args, "triggerLabel");
1086
+ const done = stringArg2(args, "doneLabel");
1087
+ if (merged) {
1088
+ await ctx.externalWrites.ensure(
1089
+ {
1090
+ writeType: "gitlab.ensure_label",
1091
+ dedupKey: JSON.stringify([client.baseUrl, b.projectId, done])
1092
+ },
1093
+ {
1094
+ reconcile: async () => (await client.listLabels(b.projectId, ctx.signal)).find((l) => l.name === done) ?? null,
1095
+ execute: () => client.createLabel(b.projectId, done, ctx.signal),
1096
+ toMetadata: (label) => ({ name: label.name })
1097
+ }
1098
+ );
1099
+ }
1100
+ await ctx.externalWrites.ensure(
1101
+ { writeType: name, dedupKey: digest },
1102
+ {
1103
+ reconcile: async () => {
1104
+ const fresh = await client.getIssue(b.projectId, iid, ctx.signal);
1105
+ return !fresh.labels.includes(trigger) && (!merged || fresh.state === "closed" && fresh.labels.includes(done)) ? fresh : null;
1106
+ },
1107
+ execute: async () => {
1108
+ const issue = await client.getIssue(b.projectId, iid, ctx.signal);
1109
+ const labels = [
1110
+ .../* @__PURE__ */ new Set([
1111
+ ...issue.labels.filter((l) => l !== trigger),
1112
+ ...merged ? [done] : []
1113
+ ])
1114
+ ];
1115
+ return client.updateIssue(
1116
+ b.projectId,
1117
+ iid,
1118
+ { labels: labels.join(","), ...merged ? { state_event: "close" } : {} },
1119
+ ctx.signal
1120
+ );
1121
+ },
1122
+ toMetadata: () => ({ issueIid: iid, merged })
1123
+ }
1124
+ );
1125
+ return { issueIid: iid, merged };
1126
+ }
1127
+ });
1128
+ }
1129
+ }
1130
+
1131
+ // src/setup.ts
1132
+ function setupGitLabIntegration(api, integration, options = {}) {
1133
+ api.provide(gitlabIntegration, integration);
1134
+ const deps = api.get(coreHostCapabilities.serverSetup);
1135
+ if (!deps || Array.isArray(deps)) return;
1136
+ registerGitLabTools(api, integration);
1137
+ registerGitLabDeliveryTools(api, integration, deps.projects);
1138
+ return createGitLabProvider(deps, integration, options);
1139
+ }
1140
+
1141
+ export {
1142
+ parseGitLabProfiles,
1143
+ GitLabClient,
1144
+ observeMergeRequest,
1145
+ gitlabIntegration,
1146
+ gitlabRepositoryCredentials,
1147
+ resolveGitLabBinding,
1148
+ ensureGitLabSeenReaction,
1149
+ parseGitLabSelection,
1150
+ selectGitLabProjects,
1151
+ gitlabIssueExternalId,
1152
+ gitlabIssueWatcherSource,
1153
+ GITLAB_MR_KIND,
1154
+ pendingGitLabFeedback,
1155
+ gitLabFeedbackReadyAt,
1156
+ observationKey,
1157
+ gitlabExternal,
1158
+ setupGitLabIntegration
1159
+ };
1160
+ //# sourceMappingURL=chunk-TQIZKDAM.js.map