@leitwerk-dev/gitlab 0.3.0 → 0.4.0

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.
Files changed (56) hide show
  1. package/README.md +154 -1
  2. package/dist/capability.d.ts +3 -0
  3. package/dist/capability.d.ts.map +1 -1
  4. package/dist/chunk-YPCOVBQS.js +2343 -0
  5. package/dist/chunk-YPCOVBQS.js.map +1 -0
  6. package/dist/client.d.ts +99 -7
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/external.d.ts +24 -4
  9. package/dist/external.d.ts.map +1 -1
  10. package/dist/index.d.ts +8 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +512 -10
  13. package/dist/index.js.map +1 -1
  14. package/dist/issue-watcher.d.ts +2 -2
  15. package/dist/issue-watcher.d.ts.map +1 -1
  16. package/dist/launch.d.ts +40 -0
  17. package/dist/launch.d.ts.map +1 -0
  18. package/dist/maintenance-labels.d.ts +30 -0
  19. package/dist/maintenance-labels.d.ts.map +1 -0
  20. package/dist/maintenance.d.ts +132 -0
  21. package/dist/maintenance.d.ts.map +1 -0
  22. package/dist/publication-maintenance.d.ts +7 -0
  23. package/dist/publication-maintenance.d.ts.map +1 -0
  24. package/dist/publication.d.ts +37 -0
  25. package/dist/publication.d.ts.map +1 -0
  26. package/dist/repository-catalog.d.ts +16 -0
  27. package/dist/repository-catalog.d.ts.map +1 -0
  28. package/dist/setup.d.ts +8 -2
  29. package/dist/setup.d.ts.map +1 -1
  30. package/dist/testing.d.ts +10 -1
  31. package/dist/testing.d.ts.map +1 -1
  32. package/dist/testing.js +125 -5
  33. package/dist/testing.js.map +1 -1
  34. package/dist/ticket-creation.d.ts +5 -0
  35. package/dist/ticket-creation.d.ts.map +1 -0
  36. package/dist/tools.d.ts +100 -3
  37. package/dist/tools.d.ts.map +1 -1
  38. package/package.json +7 -7
  39. package/src/capability.ts +3 -0
  40. package/src/client.ts +275 -12
  41. package/src/delivery-tools.ts +4 -4
  42. package/src/external.ts +91 -24
  43. package/src/index.ts +58 -10
  44. package/src/issue-watcher.ts +16 -14
  45. package/src/launch.ts +63 -0
  46. package/src/maintenance-labels.ts +129 -0
  47. package/src/maintenance.ts +759 -0
  48. package/src/publication-maintenance.ts +288 -0
  49. package/src/publication.ts +234 -0
  50. package/src/repository-catalog.ts +94 -0
  51. package/src/setup.ts +115 -6
  52. package/src/testing.ts +143 -4
  53. package/src/ticket-creation.ts +145 -0
  54. package/src/tools.ts +382 -26
  55. package/dist/chunk-H4JCQNDY.js +0 -1162
  56. package/dist/chunk-H4JCQNDY.js.map +0 -1
@@ -0,0 +1,2343 @@
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
+ ignoredCommentUsers: parseIgnoredCommentUsers(item.ignored_comment_users),
103
+ ...identity ? { gitIdentity: { name: String(identity.name), email: String(identity.email) } } : {}
104
+ });
105
+ }
106
+ return profiles;
107
+ }
108
+ function parseIgnoredCommentUsers(raw) {
109
+ if (raw === void 0) return [];
110
+ if (!Array.isArray(raw) || raw.some((user) => typeof user !== "string"))
111
+ throw new Error("GitLab ignored_comment_users must be a list of usernames");
112
+ const users = raw.map((user) => user.trim().replace(/^@/, "").toLowerCase());
113
+ if (users.some((user) => !/^[a-z0-9_.-]+$/.test(user)))
114
+ throw new Error("GitLab ignored_comment_users requires nonempty GitLab usernames");
115
+ return [...new Set(users)];
116
+ }
117
+ var projectPath = (id) => `/projects/${encodeURIComponent(id)}`;
118
+ var mrPath = (id, iid) => `${projectPath(id)}/merge_requests/${iid}`;
119
+ function nextGitLabPage(response, page, count, perPage = 100) {
120
+ const next = response.headers.get("x-next-page");
121
+ if (next === "" || next === null && count < perPage) return null;
122
+ return next === null ? page + 1 : Number(next);
123
+ }
124
+ var GitLabClient = class {
125
+ /** @public */
126
+ baseUrl;
127
+ #profile;
128
+ #ignoredCommentUsers;
129
+ #fetch;
130
+ #sleep;
131
+ /** @internal */
132
+ constructor(profile, options = {}) {
133
+ if (repositoryHttpsUrl2(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
134
+ throw new Error("GitLab requires an HTTPS origin baseUrl");
135
+ if (!profile.token || /[\r\n\0]/.test(profile.token))
136
+ throw new Error("GitLab requires a valid token");
137
+ this.#profile = profile;
138
+ this.#ignoredCommentUsers = new Set(parseIgnoredCommentUsers(profile.ignoredCommentUsers));
139
+ this.baseUrl = profile.baseUrl;
140
+ this.#fetch = options.fetch ?? fetch;
141
+ this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
142
+ }
143
+ async response(path, signal, body, method) {
144
+ for (let attempt = 0; ; attempt++) {
145
+ let response;
146
+ try {
147
+ response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
148
+ method: method ?? (body === void 0 ? "GET" : "POST"),
149
+ redirect: "error",
150
+ headers: {
151
+ "PRIVATE-TOKEN": this.#profile.token,
152
+ Accept: "application/json",
153
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
154
+ },
155
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4),
156
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
157
+ });
158
+ } catch {
159
+ if (signal?.aborted) throw new GitLabError(0, true);
160
+ if (body !== void 0 || attempt >= 2) throw new GitLabError(0, true);
161
+ await this.#sleep(1e3 * 2 ** attempt);
162
+ continue;
163
+ }
164
+ if (response.ok) return response;
165
+ const retryable = response.status === 429 || response.status >= 500 || response.status === 408;
166
+ await response.body?.cancel();
167
+ if (!retryable || body !== void 0 || attempt >= 2)
168
+ throw new GitLabError(response.status, retryable);
169
+ const seconds = Number(response.headers.get("retry-after"));
170
+ await this.#sleep(Math.min(3e4, seconds > 0 ? seconds * 1e3 : 1e3 * 2 ** attempt));
171
+ }
172
+ }
173
+ async request(path, signal, body, method) {
174
+ return this.json(await this.response(path, signal, body, method));
175
+ }
176
+ async json(response) {
177
+ try {
178
+ return await response.json();
179
+ } catch {
180
+ throw new GitLabError(502, true);
181
+ }
182
+ }
183
+ async pages(path, signal) {
184
+ const rows = [];
185
+ let page = 1;
186
+ for (let n = 0; n < 1e4; n++) {
187
+ const response = await this.response(
188
+ `${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
189
+ signal
190
+ );
191
+ const batch = await this.json(response);
192
+ if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
193
+ rows.push(...batch);
194
+ const nextPage = nextGitLabPage(response, page, batch.length);
195
+ if (nextPage === null) return rows;
196
+ if (!Number.isInteger(nextPage) || nextPage <= page)
197
+ throw new Error("Invalid GitLab pagination");
198
+ page = nextPage;
199
+ }
200
+ throw new Error("GitLab pagination limit exceeded; discovery incomplete");
201
+ }
202
+ /** @public */
203
+ listIssues(id, signal, state = "opened") {
204
+ return this.pages(`${projectPath(id)}/issues?state=${state}&scope=all`, signal);
205
+ }
206
+ /** @internal */
207
+ createIssue(id, input, signal) {
208
+ return this.request(`${projectPath(id)}/issues`, signal, input);
209
+ }
210
+ /** @public */
211
+ getIssue(id, iid, signal) {
212
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal);
213
+ }
214
+ /** @public */
215
+ updateIssue(id, iid, patch, signal) {
216
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal, patch, "PUT");
217
+ }
218
+ /** @public */
219
+ listIssueNotes(id, iid, signal) {
220
+ return this.pages(`${projectPath(id)}/issues/${iid}/notes`, signal);
221
+ }
222
+ /** @public */
223
+ addIssueNote(id, iid, body, signal) {
224
+ return this.request(`${projectPath(id)}/issues/${iid}/notes`, signal, { body });
225
+ }
226
+ /** @public */
227
+ listLabels(id, signal) {
228
+ return this.pages(`${projectPath(id)}/labels`, signal);
229
+ }
230
+ /** @public */
231
+ createLabel(id, name, signal) {
232
+ return this.request(`${projectPath(id)}/labels`, signal, { name, color: "#2da44e" });
233
+ }
234
+ /** @public */
235
+ listBranchMergeRequests(id, source, target, signal) {
236
+ return this.pages(
237
+ `${projectPath(id)}/merge_requests?state=all&source_branch=${encodeURIComponent(source)}&target_branch=${encodeURIComponent(target)}`,
238
+ signal
239
+ );
240
+ }
241
+ /** @public */
242
+ createMergeRequest(id, input, signal) {
243
+ return this.request(`${projectPath(id)}/merge_requests`, signal, {
244
+ ...input,
245
+ remove_source_branch: false
246
+ });
247
+ }
248
+ /** @public */
249
+ async preflightRepository(projectId, baseBranch, workBranch, signal) {
250
+ const project = await this.getProject(projectId, signal);
251
+ await preflightGitLabRepository({
252
+ url: project.http_url_to_repo,
253
+ origin: this.baseUrl,
254
+ token: this.#profile.token,
255
+ baseBranch,
256
+ workBranch,
257
+ signal
258
+ });
259
+ }
260
+ /** @public */
261
+ getProject(id, signal) {
262
+ return this.request(projectPath(id), signal);
263
+ }
264
+ /** @internal */
265
+ listProjects(signal) {
266
+ return this.pages("/projects?archived=false", signal);
267
+ }
268
+ /** Read at most one page of matching repositories. @internal */
269
+ searchProjects(search, signal) {
270
+ const query = new URLSearchParams({
271
+ archived: "false",
272
+ search,
273
+ search_namespaces: "true",
274
+ per_page: "100",
275
+ page: "1",
276
+ order_by: "path",
277
+ sort: "asc"
278
+ });
279
+ return this.request(`/projects?${query}`, signal);
280
+ }
281
+ /** @internal */
282
+ listRepositoryTree(id, ref, path = "", signal) {
283
+ return this.pages(
284
+ `${projectPath(id)}/repository/tree?ref=${encodeURIComponent(ref)}&path=${encodeURIComponent(path)}`,
285
+ signal
286
+ );
287
+ }
288
+ /** @internal */
289
+ getRepositoryFile(id, ref, path, signal) {
290
+ return this.request(
291
+ `${projectPath(id)}/repository/files/${encodeURIComponent(path)}?ref=${encodeURIComponent(ref)}`,
292
+ signal
293
+ );
294
+ }
295
+ /** Project-scoped basic blob search at a full commit, one page per request. @internal */
296
+ async searchRepositoryCode(id, ref, search, page = 1, perPage = 20, signal) {
297
+ if (!/^[a-f0-9]{40,64}$/i.test(ref)) throw new Error("Code search requires a full commit ID");
298
+ if (!search.trim()) throw new Error("Code search requires a search term");
299
+ if (!Number.isSafeInteger(page) || page < 1 || !Number.isSafeInteger(perPage) || perPage < 1 || perPage > 100)
300
+ throw new Error("Invalid GitLab search pagination");
301
+ const query = new URLSearchParams({
302
+ scope: "blobs",
303
+ search_type: "basic",
304
+ ref,
305
+ search,
306
+ page: String(page),
307
+ per_page: String(perPage)
308
+ });
309
+ const response = await this.response(`${projectPath(id)}/search?${query}`, signal);
310
+ const rows = await this.json(response);
311
+ if (!Array.isArray(rows) || rows.some(
312
+ (row) => !row || typeof row.path !== "string" || typeof row.data !== "string" || !Number.isSafeInteger(row.startline)
313
+ ))
314
+ throw new Error("Invalid GitLab code search response");
315
+ const nextPage = nextGitLabPage(response, page, rows.length, perPage);
316
+ if (nextPage !== null && (!Number.isSafeInteger(nextPage) || nextPage <= page))
317
+ throw new Error("Invalid GitLab pagination");
318
+ return {
319
+ revision: ref,
320
+ results: rows.map((row) => ({ path: row.path, snippet: row.data, startLine: row.startline })),
321
+ page,
322
+ nextPage
323
+ };
324
+ }
325
+ /** @internal */
326
+ getGroup(id, signal) {
327
+ return this.request(`/groups/${encodeURIComponent(id)}`, signal);
328
+ }
329
+ /** @internal */
330
+ listGroupProjects(id, signal) {
331
+ return this.pages(
332
+ `/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
333
+ signal
334
+ );
335
+ }
336
+ /** @public */
337
+ listMergeRequests(id, label, signal) {
338
+ return this.pages(
339
+ `${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
340
+ signal
341
+ );
342
+ }
343
+ /** @internal */
344
+ getMergeRequest(id, iid, signal) {
345
+ return this.request(mrPath(id, iid), signal);
346
+ }
347
+ /** Read every label transition, including changes between watcher polls. @public */
348
+ listMergeRequestLabelEvents(id, iid, signal) {
349
+ return this.pages(`${mrPath(id, iid)}/resource_label_events`, signal);
350
+ }
351
+ /** Apply label deltas without replacing unrelated labels. @public */
352
+ updateMergeRequestLabels(id, iid, patch, signal) {
353
+ return this.request(mrPath(id, iid), signal, patch, "PUT");
354
+ }
355
+ /** @public */
356
+ getChanges(id, iid, signal) {
357
+ return this.pages(`${mrPath(id, iid)}/diffs`, signal);
358
+ }
359
+ /** @public */
360
+ getBranch(id, branch, signal) {
361
+ return this.request(
362
+ `${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
363
+ signal
364
+ );
365
+ }
366
+ /** @internal */
367
+ getCommit(id, sha, signal) {
368
+ return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
369
+ }
370
+ /** Find shared ancestry without cloning a repository. @public */
371
+ getMergeBase(id, refs, signal) {
372
+ const query = new URLSearchParams();
373
+ for (const ref of refs) query.append("refs[]", ref);
374
+ return this.request(`${projectPath(id)}/repository/merge_base?${query}`, signal);
375
+ }
376
+ /** @internal */
377
+ listMergeRequestPipelines(id, iid, signal) {
378
+ return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
379
+ }
380
+ /** @internal */
381
+ listBranchPipelines(id, branch, sha, signal) {
382
+ return this.pages(
383
+ `${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
384
+ signal
385
+ );
386
+ }
387
+ /** @internal */
388
+ getPipeline(id, pipeline, signal) {
389
+ return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
390
+ }
391
+ /** @public */
392
+ listFailedJobs(id, pipeline, signal) {
393
+ return this.pages(
394
+ `${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
395
+ signal
396
+ );
397
+ }
398
+ /** @internal */
399
+ listNotes(id, iid, signal) {
400
+ return this.pages(`${mrPath(id, iid)}/notes`, signal);
401
+ }
402
+ /** @internal */
403
+ getDiscussion(id, iid, discussionId, signal) {
404
+ return this.request(
405
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
406
+ signal
407
+ );
408
+ }
409
+ /** @internal */
410
+ listDiscussions(id, iid, signal) {
411
+ return this.pages(`${mrPath(id, iid)}/discussions`, signal);
412
+ }
413
+ /** @internal */
414
+ addDiscussion(id, iid, body, position, signal) {
415
+ return this.request(`${mrPath(id, iid)}/discussions`, signal, { body, position });
416
+ }
417
+ /** @internal */
418
+ replyToDiscussion(id, iid, discussionId, body, signal) {
419
+ return this.request(
420
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
421
+ signal,
422
+ { body }
423
+ );
424
+ }
425
+ /** @internal */
426
+ resolveDiscussion(id, iid, discussionId, resolved, signal) {
427
+ return this.request(
428
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
429
+ signal,
430
+ { resolved },
431
+ "PUT"
432
+ );
433
+ }
434
+ /** @internal */
435
+ listNoteReactions(id, iid, noteId, signal) {
436
+ return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
437
+ }
438
+ /** @internal */
439
+ addNoteReaction(id, iid, noteId, name, signal) {
440
+ return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
441
+ }
442
+ /** @public */
443
+ async listMergeRequestFeedback(id, iid, signal) {
444
+ const discussions = await this.pages(
445
+ `${mrPath(id, iid)}/discussions`,
446
+ signal
447
+ );
448
+ const feedback = [];
449
+ for (const discussion of discussions) {
450
+ for (const note of discussion.notes) {
451
+ if (note.system || note.resolved || note.author.bot || this.#ignoredCommentUsers.has(note.author.username.toLowerCase()) || /<!-- leitwerk:gitlab:[a-f0-9]{64} -->/.test(note.body) || !note.body.trim() || !Number.isFinite(Date.parse(note.created_at)))
452
+ continue;
453
+ const position = note.position ?? discussion.notes[0]?.position;
454
+ feedback.push({
455
+ id: note.id,
456
+ discussionId: discussion.id,
457
+ body: note.body,
458
+ author: note.author.username,
459
+ createdAt: note.created_at,
460
+ ...position ? {
461
+ path: position.new_path ?? position.old_path,
462
+ line: position.new_line ?? position.old_line
463
+ } : {}
464
+ });
465
+ }
466
+ }
467
+ return feedback.sort((a, b) => a.id - b.id);
468
+ }
469
+ /** @internal */
470
+ addNote(id, iid, body, signal) {
471
+ return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
472
+ }
473
+ /** @internal */
474
+ updateNote(id, iid, noteId, body, signal) {
475
+ return this.request(`${mrPath(id, iid)}/notes/${noteId}`, signal, { body }, "PUT");
476
+ }
477
+ /** @public */
478
+ async resolveGitIdentity(signal) {
479
+ const user = await this.request("/user", signal);
480
+ const name = this.#profile.gitIdentity?.name ?? user.name;
481
+ const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
482
+ if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
483
+ throw new Error(
484
+ "GitLab bot Git identity is unavailable; configure git_identity on the profile"
485
+ );
486
+ return { name, email, username: user.username };
487
+ }
488
+ /** @public */
489
+ async getJobTrace(id, job, maxBytes = 65536, signal) {
490
+ const limit = Math.min(262144, Math.max(1, Math.floor(maxBytes) || 65536));
491
+ const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
492
+ const reader = response.body?.getReader();
493
+ if (!reader) return { text: "", truncated: false };
494
+ const chunks = [];
495
+ let size = 0;
496
+ let truncated = false;
497
+ try {
498
+ while (true) {
499
+ const item = await reader.read();
500
+ if (item.done) break;
501
+ const take = Math.min(item.value.length, limit - size);
502
+ chunks.push(item.value.slice(0, take));
503
+ size += take;
504
+ if (size >= limit) {
505
+ truncated = true;
506
+ break;
507
+ }
508
+ }
509
+ } finally {
510
+ await reader.cancel();
511
+ }
512
+ return { text: Buffer.concat(chunks).toString("utf8"), truncated };
513
+ }
514
+ };
515
+ async function observeMergeRequest(client, projectId, iid, signal) {
516
+ const mr = await client.getMergeRequest(projectId, iid, signal);
517
+ if (mr.state !== "opened") return { mr, pipeline: null };
518
+ const targetHead = (await client.getBranch(mr.target_project_id, mr.target_branch, signal)).commit.id;
519
+ const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
520
+ (a, b) => b.id - a.id
521
+ );
522
+ for (const candidate of associated) {
523
+ const id = candidate.project_id ?? projectId;
524
+ let matches = candidate.sha === mr.sha;
525
+ if (!matches && (candidate.ref === `refs/merge-requests/${iid}/merge` || candidate.sha === mr.merge_commit_sha)) {
526
+ const commit = await client.getCommit(id, candidate.sha, signal);
527
+ matches = commit.parent_ids.includes(mr.sha);
528
+ }
529
+ if (matches)
530
+ return { mr, targetHead, pipeline: await client.getPipeline(id, candidate.id, signal) };
531
+ }
532
+ const candidates = await client.listBranchPipelines(
533
+ mr.source_project_id,
534
+ mr.source_branch,
535
+ mr.sha,
536
+ signal
537
+ );
538
+ 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];
539
+ return {
540
+ mr,
541
+ targetHead,
542
+ pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null
543
+ };
544
+ }
545
+
546
+ // src/capability.ts
547
+ import {
548
+ createCapabilityToken
549
+ } from "@leitwerk-dev/process-sdk";
550
+ var gitlabIntegration = createCapabilityToken(
551
+ "@leitwerk-dev/gitlab.integration"
552
+ );
553
+ function gitlabRepositoryCredentials(profile, projects) {
554
+ return projects.map((project) => ({
555
+ projectKey: project.key,
556
+ kind: "git_https",
557
+ credentialRef: `gitlab:${profile}`
558
+ }));
559
+ }
560
+
561
+ // src/tools.ts
562
+ import { createHash } from "crypto";
563
+ import {
564
+ numberArg,
565
+ projectParameters,
566
+ stringArg
567
+ } from "@leitwerk-dev/process-sdk";
568
+ var hashIdentity = (identity) => createHash("sha256").update(JSON.stringify(identity)).digest("hex");
569
+ async function existingRemote(read) {
570
+ try {
571
+ return await read();
572
+ } catch (error) {
573
+ if (error instanceof GitLabError && error.status === 404) return null;
574
+ throw error;
575
+ }
576
+ }
577
+ function resolveGitLabRepositoryBinding(ctx, integration) {
578
+ if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
579
+ throw new Error("An authorized GitLab process project is required");
580
+ const binding = ctx.project.metadata?.gitlab;
581
+ if (!binding || typeof binding.profile !== "string" || !binding.profile.trim() || typeof binding.projectId !== "number" || !Number.isSafeInteger(binding.projectId) || binding.projectId <= 0)
582
+ throw new Error("Invalid GitLab project binding");
583
+ if (binding.origin !== void 0 && integration && integration.client(binding.profile).baseUrl !== binding.origin)
584
+ throw new Error("GitLab profile installation changed from the pinned repository");
585
+ return { profile: binding.profile, projectId: binding.projectId };
586
+ }
587
+ function resolveGitLabBinding(ctx, integration) {
588
+ const repository = resolveGitLabRepositoryBinding(ctx, integration);
589
+ const iid = ctx.project?.metadata?.gitlab?.iid;
590
+ if (typeof iid !== "number" || !Number.isSafeInteger(iid) || iid <= 0)
591
+ throw new Error("Invalid GitLab project binding: a merge request is required");
592
+ return { ...repository, iid };
593
+ }
594
+ function gitLabCommentMarker(input) {
595
+ const identity = [
596
+ input.baseUrl,
597
+ input.projectId,
598
+ input.iid,
599
+ input.instanceId,
600
+ input.writeKey
601
+ ];
602
+ if (input.discussionId) identity.push(input.discussionId);
603
+ return `<!-- leitwerk:gitlab:${hashIdentity(identity)} -->`;
604
+ }
605
+ async function ensureGitLabComment(input) {
606
+ const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
607
+ const marker = gitLabCommentMarker({
608
+ baseUrl: client.baseUrl,
609
+ projectId,
610
+ iid,
611
+ instanceId,
612
+ writeKey,
613
+ discussionId: input.discussionId
614
+ });
615
+ const digest = marker.slice("<!-- leitwerk:gitlab:".length, -4);
616
+ const find = async () => {
617
+ const notes = input.discussionId ? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes : await client.listNotes(projectId, iid, signal);
618
+ return notes.find((note) => note.body.includes(marker));
619
+ };
620
+ await writes.ensure(
621
+ { writeType: "gitlab.comment", dedupKey: digest },
622
+ {
623
+ reconcile: () => existingRemote(async () => await find() ?? null),
624
+ execute: async () => {
625
+ await input.beforeWrite?.();
626
+ const body = `${input.body}
627
+
628
+ ${marker}`;
629
+ return input.discussionId ? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal) : client.addNote(projectId, iid, body, signal);
630
+ },
631
+ toMetadata: (note) => ({ projectId, iid, noteId: note.id, marker })
632
+ }
633
+ );
634
+ return { marker };
635
+ }
636
+ async function updateGitLabComment(input) {
637
+ const { client, instanceId, projectId, iid, writeKey, body, signal } = input;
638
+ const marker = gitLabCommentMarker({
639
+ baseUrl: client.baseUrl,
640
+ projectId,
641
+ iid,
642
+ instanceId,
643
+ writeKey
644
+ });
645
+ const note = (await client.listNotes(projectId, iid, signal)).find(
646
+ (item) => item.body.includes(marker)
647
+ );
648
+ if (!note) throw new Error("GitLab comment to update was not found");
649
+ const next = `${body}
650
+
651
+ ${marker}`;
652
+ if (note.body !== next) {
653
+ await input.beforeWrite?.();
654
+ await client.updateNote(projectId, iid, note.id, next, signal);
655
+ }
656
+ return { marker };
657
+ }
658
+ async function ensureGitLabInlineComment(input) {
659
+ const {
660
+ client,
661
+ writes,
662
+ instanceId,
663
+ projectId,
664
+ iid,
665
+ writeKey,
666
+ body,
667
+ path,
668
+ line,
669
+ side,
670
+ baseSha,
671
+ startSha,
672
+ headSha,
673
+ signal
674
+ } = input;
675
+ const marker = gitLabCommentMarker({
676
+ baseUrl: client.baseUrl,
677
+ projectId,
678
+ iid,
679
+ instanceId,
680
+ writeKey
681
+ });
682
+ const digest = marker.slice("<!-- leitwerk:gitlab:".length, -4);
683
+ const find = async () => {
684
+ const discussions = await client.listDiscussions(projectId, iid, signal);
685
+ return discussions.find(
686
+ (discussion2) => discussion2.notes.some((note) => note.body.includes(marker))
687
+ );
688
+ };
689
+ const diff = (await client.getChanges(projectId, iid, signal)).find(
690
+ (candidate) => side === "new" ? candidate.new_path === path : candidate.old_path === path
691
+ );
692
+ if (!diff) throw new Error("GitLab inline comment path is not in the merge request diff");
693
+ await writes.ensure(
694
+ { writeType: "gitlab.discussion", dedupKey: digest },
695
+ {
696
+ reconcile: () => existingRemote(async () => await find() ?? null),
697
+ execute: () => client.addDiscussion(
698
+ projectId,
699
+ iid,
700
+ `${body}
701
+
702
+ ${marker}`,
703
+ {
704
+ position_type: "text",
705
+ base_sha: baseSha,
706
+ start_sha: startSha,
707
+ head_sha: headSha,
708
+ old_path: diff.old_path,
709
+ new_path: diff.new_path,
710
+ ...side === "new" ? { new_line: line } : { old_line: line }
711
+ },
712
+ signal
713
+ ),
714
+ toMetadata: (discussion2) => ({
715
+ projectId,
716
+ iid,
717
+ discussionId: discussion2.id,
718
+ marker
719
+ })
720
+ }
721
+ );
722
+ const discussion = await find();
723
+ if (!discussion) throw new Error("GitLab inline discussion is unavailable after create");
724
+ return { marker, discussionId: discussion.id };
725
+ }
726
+ async function ensureGitLabResolveDiscussion(input) {
727
+ const { client, writes, instanceId, projectId, iid, writeKey, discussionId, signal } = input;
728
+ const digest = hashIdentity([
729
+ client.baseUrl,
730
+ projectId,
731
+ iid,
732
+ instanceId,
733
+ "resolve",
734
+ writeKey,
735
+ discussionId
736
+ ]);
737
+ await writes.ensure(
738
+ { writeType: "gitlab.discussion.resolve", dedupKey: digest },
739
+ {
740
+ reconcile: () => existingRemote(async () => {
741
+ const discussion = await client.getDiscussion(projectId, iid, discussionId, signal);
742
+ return discussion.notes.some((note) => note.resolved) ? discussion : null;
743
+ }),
744
+ execute: () => client.resolveDiscussion(projectId, iid, discussionId, true, signal),
745
+ toMetadata: () => ({ projectId, iid, discussionId, resolved: true })
746
+ }
747
+ );
748
+ return { discussionId, resolved: true };
749
+ }
750
+ async function ensureGitLabSeenReaction(input) {
751
+ const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
752
+ const digest = hashIdentity([client.baseUrl, projectId, iid, instanceId, "eyes", noteId]);
753
+ await writes.ensure(
754
+ { writeType: "gitlab.reaction", dedupKey: digest },
755
+ {
756
+ reconcile: () => existingRemote(async () => {
757
+ const identity = await client.resolveGitIdentity(signal);
758
+ return (await client.listNoteReactions(projectId, iid, noteId, signal)).find(
759
+ (reaction) => reaction.name === "eyes" && reaction.user.username === identity.username
760
+ ) ?? null;
761
+ }),
762
+ execute: async () => {
763
+ await input.beforeWrite?.();
764
+ return client.addNoteReaction(projectId, iid, noteId, "eyes", signal);
765
+ },
766
+ toMetadata: (reaction) => ({ projectId, iid, noteId, reactionId: reaction.id, name: "eyes" })
767
+ }
768
+ );
769
+ }
770
+ function registerGitLabTools(api, integration, beforeWrite) {
771
+ for (const name of [
772
+ "gitlab_inspect_project",
773
+ "gitlab_repository_tree",
774
+ "gitlab_repository_file",
775
+ "gitlab_code_search"
776
+ ])
777
+ api.tool({
778
+ name,
779
+ description: name === "gitlab_code_search" ? "Search blobs in a bound GitLab repository at a full commit. Follow nextPage until null, then read matching files for complete evidence. Search failure is not an empty result." : "Inspect a bound GitLab repository. Use the returned commit ID as ref for subsequent tree/file reads.",
780
+ parameters: name === "gitlab_code_search" ? projectParameters(
781
+ {
782
+ ref: { type: "string" },
783
+ search: { type: "string" },
784
+ page: { type: "integer", minimum: 1 },
785
+ perPage: { type: "integer", minimum: 1, maximum: 100 }
786
+ },
787
+ ["ref", "search"]
788
+ ) : projectParameters(
789
+ { ref: { type: "string" }, path: { type: "string" } },
790
+ name === "gitlab_inspect_project" ? [] : name === "gitlab_repository_tree" ? ["ref"] : ["ref", "path"]
791
+ ),
792
+ async execute(ctx, args) {
793
+ const binding = resolveGitLabRepositoryBinding(ctx, integration);
794
+ const client = integration.client(binding.profile);
795
+ if (name === "gitlab_inspect_project")
796
+ return {
797
+ project: await client.getProject(binding.projectId, ctx.signal),
798
+ branch: await client.getBranch(binding.projectId, ctx.project.baseBranch, ctx.signal)
799
+ };
800
+ const ref = stringArg(args, "ref");
801
+ if (!/^[a-f0-9]{40,64}$/i.test(ref))
802
+ throw new Error("Repository reads require a commit ID returned by inspection");
803
+ if (name === "gitlab_code_search") {
804
+ if (!client.searchRepositoryCode)
805
+ throw new Error("GitLab code search unavailable; no search was performed");
806
+ return client.searchRepositoryCode(
807
+ binding.projectId,
808
+ ref,
809
+ stringArg(args, "search"),
810
+ args.page === void 0 ? 1 : numberArg(args, "page"),
811
+ args.perPage === void 0 ? 20 : numberArg(args, "perPage"),
812
+ ctx.signal
813
+ );
814
+ }
815
+ if (name === "gitlab_repository_tree") {
816
+ if (!client.listRepositoryTree) throw new Error("Repository tree inspection unavailable");
817
+ return client.listRepositoryTree(
818
+ binding.projectId,
819
+ ref,
820
+ typeof args.path === "string" ? args.path : "",
821
+ ctx.signal
822
+ );
823
+ }
824
+ if (!client.getRepositoryFile) throw new Error("Repository file inspection unavailable");
825
+ const file = await client.getRepositoryFile(
826
+ binding.projectId,
827
+ ref,
828
+ stringArg(args, "path"),
829
+ ctx.signal
830
+ );
831
+ return {
832
+ ...file,
833
+ content: file.encoding === "base64" ? Buffer.from(file.content, "base64").toString("utf8") : file.content,
834
+ encoding: "utf8",
835
+ revision: ref
836
+ };
837
+ }
838
+ });
839
+ for (const [name, description, required] of [
840
+ ["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
841
+ ["gitlab_get_changes", "Read the MR changes", []],
842
+ ["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
843
+ ["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
844
+ [
845
+ "gitlab_get_job_trace",
846
+ "Read a bounded trace from a failed MR pipeline job",
847
+ ["pipelineId", "jobId"]
848
+ ],
849
+ ["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
850
+ ["gitlab_update_comment", "Update a retry-safe MR comment", ["body", "writeKey"]],
851
+ [
852
+ "gitlab_inline_comment",
853
+ "Post a retry-safe MR inline discussion",
854
+ ["body", "writeKey", "path", "line", "side", "baseSha", "startSha", "headSha"]
855
+ ],
856
+ [
857
+ "gitlab_reply",
858
+ "Post a retry-safe reply in an MR discussion",
859
+ ["body", "writeKey", "discussionId"]
860
+ ],
861
+ [
862
+ "gitlab_resolve_discussion",
863
+ "Resolve a retry-safe MR inline discussion",
864
+ ["writeKey", "discussionId"]
865
+ ]
866
+ ]) {
867
+ api.tool({
868
+ name,
869
+ description,
870
+ parameters: projectParameters(
871
+ {
872
+ pipelineId: { type: "integer" },
873
+ jobId: { type: "integer" },
874
+ maxBytes: { type: "integer" },
875
+ body: { type: "string" },
876
+ writeKey: { type: "string" },
877
+ discussionId: { type: "string" },
878
+ path: { type: "string" },
879
+ line: { type: "integer" },
880
+ side: { type: "string" },
881
+ baseSha: { type: "string" },
882
+ startSha: { type: "string" },
883
+ headSha: { type: "string" }
884
+ },
885
+ [...required]
886
+ ),
887
+ async execute(ctx, args) {
888
+ if (name === "gitlab_get_identity")
889
+ return integration.client(resolveGitLabRepositoryBinding(ctx, integration).profile).resolveGitIdentity(ctx.signal);
890
+ const b = resolveGitLabBinding(ctx, integration);
891
+ const client = integration.client(b.profile);
892
+ if (name === "gitlab_observe_merge_request")
893
+ return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
894
+ if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
895
+ const writeContext = {
896
+ client,
897
+ writes: ctx.externalWrites,
898
+ instanceId: ctx.process.id,
899
+ projectId: b.projectId,
900
+ iid: b.iid,
901
+ signal: ctx.signal
902
+ };
903
+ if (name === "gitlab_update_comment")
904
+ return updateGitLabComment({
905
+ ...writeContext,
906
+ beforeWrite: beforeWrite ? () => beforeWrite(ctx) : void 0,
907
+ writeKey: stringArg(args, "writeKey"),
908
+ body: stringArg(args, "body")
909
+ });
910
+ if (name === "gitlab_inline_comment") {
911
+ const side = stringArg(args, "side");
912
+ if (side !== "new" && side !== "old")
913
+ throw new Error("GitLab inline comment side must be new or old");
914
+ return ensureGitLabInlineComment({
915
+ ...writeContext,
916
+ writeKey: stringArg(args, "writeKey"),
917
+ body: stringArg(args, "body"),
918
+ path: stringArg(args, "path"),
919
+ line: numberArg(args, "line"),
920
+ side,
921
+ baseSha: stringArg(args, "baseSha"),
922
+ startSha: stringArg(args, "startSha"),
923
+ headSha: stringArg(args, "headSha")
924
+ });
925
+ }
926
+ if (name === "gitlab_comment" || name === "gitlab_reply")
927
+ return ensureGitLabComment({
928
+ ...writeContext,
929
+ writeKey: stringArg(args, "writeKey"),
930
+ body: stringArg(args, "body"),
931
+ ...name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {}
932
+ });
933
+ if (name === "gitlab_resolve_discussion")
934
+ return ensureGitLabResolveDiscussion({
935
+ ...writeContext,
936
+ writeKey: stringArg(args, "writeKey"),
937
+ discussionId: stringArg(args, "discussionId")
938
+ });
939
+ const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
940
+ if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
941
+ throw new Error("Pipeline is not current for the authorized MR");
942
+ const jobs = await client.listFailedJobs(
943
+ observation.pipeline.project_id,
944
+ observation.pipeline.id,
945
+ ctx.signal
946
+ );
947
+ if (name === "gitlab_list_failed_jobs") return jobs;
948
+ const job = jobs.find((job2) => job2.id === numberArg(args, "jobId"));
949
+ if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
950
+ return client.getJobTrace(
951
+ observation.pipeline.project_id,
952
+ job.id,
953
+ typeof args.maxBytes === "number" ? args.maxBytes : void 0,
954
+ ctx.signal
955
+ );
956
+ }
957
+ });
958
+ }
959
+ }
960
+
961
+ // src/selection.ts
962
+ function parseGitLabSelection(raw) {
963
+ const list = (value) => {
964
+ if (value === void 0) return [];
965
+ if (!Array.isArray(value) || value.some(
966
+ (v) => typeof v !== "string" || !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(v) || v.split("/").some((p) => p === "." || p === "..")
967
+ ))
968
+ throw new Error("GitLab selectors require exact namespace paths");
969
+ return [...new Set(value)];
970
+ };
971
+ const pair = (value) => {
972
+ if (value !== void 0 && (!value || typeof value !== "object" || Array.isArray(value)))
973
+ throw new Error("GitLab selectors must be objects");
974
+ const item = value;
975
+ return { include: list(item?.include), exclude: list(item?.exclude) };
976
+ };
977
+ if (raw.all_accessible !== void 0 && typeof raw.all_accessible !== "boolean")
978
+ throw new Error("all_accessible must be a boolean");
979
+ const parsed = {
980
+ projects: pair(raw.projects),
981
+ groups: pair(raw.groups),
982
+ allAccessible: raw.all_accessible === true
983
+ };
984
+ if (!parsed.allAccessible && !parsed.projects.include.length && !parsed.groups.include.length)
985
+ throw new Error("GitLab requires explicit project/group includes or all_accessible: true");
986
+ return parsed;
987
+ }
988
+ function projectExcluded(selection, name) {
989
+ return selection.projects.exclude.includes(name) || selection.groups.exclude.some((group) => name.startsWith(`${group}/`));
990
+ }
991
+ async function selectGitLabProjects(client, selection) {
992
+ const candidates = selection.allAccessible ? await client.listProjects() : [];
993
+ for (const name of selection.projects.include) candidates.push(await client.getProject(name));
994
+ for (const group of selection.groups.include)
995
+ candidates.push(...await client.listGroupProjects(group));
996
+ return [
997
+ ...new Map(
998
+ candidates.filter((p) => !p.archived && !projectExcluded(selection, p.path_with_namespace)).map((p) => [p.id, p])
999
+ ).values()
1000
+ ];
1001
+ }
1002
+
1003
+ // src/issue-watcher.ts
1004
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
1005
+ import {
1006
+ defineProcessWatcherSource,
1007
+ parseProcessWatcherLaunchModelConfig
1008
+ } from "@leitwerk-dev/process-sdk";
1009
+ import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
1010
+ var gitlabIssueExternalId = (origin, projectId, iid) => `gitlab:${origin}:${projectId}#${iid}`;
1011
+ var gitlabIssueWatcherSource = defineProcessWatcherSource({
1012
+ id: "@leitwerk-dev/gitlab.issue",
1013
+ label: "GitLab issue",
1014
+ parseConfig(raw) {
1015
+ const c = asUnknownRecord2(raw);
1016
+ if (!c || typeof c.enabled !== "boolean") throw new Error("GitLab watcher requires enabled");
1017
+ const text = (value, name) => {
1018
+ if (typeof value !== "string" || !value.trim())
1019
+ throw new Error(`GitLab watcher requires ${name}`);
1020
+ return value.trim();
1021
+ };
1022
+ const labels = asUnknownRecord2(c.labels) ?? {};
1023
+ const trigger = text(labels.trigger, "labels.trigger");
1024
+ const done = text(labels.done, "labels.done");
1025
+ if (trigger === done || trigger.includes(",") || done.includes(","))
1026
+ throw new Error("GitLab trigger/done labels must be distinct and contain no comma");
1027
+ const pollInterval = text(c.poll_interval ?? "30s", "poll_interval");
1028
+ if (parseDurationMs(pollInterval, -1) <= 0) throw new Error("Invalid GitLab polling interval");
1029
+ return {
1030
+ enabled: c.enabled,
1031
+ config: {
1032
+ ...parseGitLabSelection(c),
1033
+ profile: text(c.profile, "profile"),
1034
+ ...typeof c.git_ssh_profile === "string" ? { gitSshProfile: c.git_ssh_profile } : {},
1035
+ pollInterval,
1036
+ labels: { trigger, done }
1037
+ },
1038
+ launchModelConfig: parseProcessWatcherLaunchModelConfig(c.launch)
1039
+ };
1040
+ },
1041
+ presentConfig(c) {
1042
+ return {
1043
+ targetSummary: `Profile ${c.profile} \xB7 trigger ${c.labels.trigger}`,
1044
+ details: [
1045
+ { label: "Projects", value: c.projects.include.join(", ") || "selected groups" },
1046
+ { label: "Groups", value: c.groups.include.join(", ") || "none" }
1047
+ ]
1048
+ };
1049
+ }
1050
+ });
1051
+ function createGitLabIssueDiscovery(deps, integration, now) {
1052
+ const due = /* @__PURE__ */ new Map();
1053
+ return async (result) => {
1054
+ for (const watcher of deps.processWatchers?.listBySource(gitlabIssueWatcherSource) ?? []) {
1055
+ if (!watcher.enabled) continue;
1056
+ const key = `${watcher.processId}:${watcher.watcherId}`;
1057
+ const c = watcher.config;
1058
+ const eligible = (issue) => issue.state === "opened" && issue.labels.includes(c.labels.trigger) && !issue.labels.includes(c.labels.done);
1059
+ if ((due.get(key) ?? 0) > now()) continue;
1060
+ due.set(key, now() + parseDurationMs(c.pollInterval, 3e4));
1061
+ const client = integration.client(c.profile);
1062
+ for (const repository of await selectGitLabProjects(client, c))
1063
+ for (const issue of await client.listIssues(repository.id)) {
1064
+ if (!eligible(issue)) continue;
1065
+ const id = gitlabIssueExternalId(client.baseUrl, repository.id, issue.iid);
1066
+ if (deps.processes.listAll().some((p) => p.externalId === id)) {
1067
+ result.skipped.push(id);
1068
+ continue;
1069
+ }
1070
+ const guarded = {
1071
+ ...watcher,
1072
+ async resolveLaunchAttempt(...args) {
1073
+ const attempt = await watcher.resolveLaunchAttempt(...args);
1074
+ if (!attempt) return null;
1075
+ return {
1076
+ ...attempt,
1077
+ preparationChecks: [
1078
+ ...attempt.preparationChecks,
1079
+ {
1080
+ id: "gitlab-issue-eligibility",
1081
+ label: "Recheck GitLab source issue",
1082
+ async run() {
1083
+ const fresh = await client.getIssue(repository.id, issue.iid);
1084
+ if (!eligible(fresh))
1085
+ throw new Error("GitLab source issue eligibility changed before launch");
1086
+ }
1087
+ }
1088
+ ]
1089
+ };
1090
+ }
1091
+ };
1092
+ const launched = await deps.launchRuns.startWatcher(
1093
+ guarded,
1094
+ {
1095
+ profile: c.profile,
1096
+ gitSshProfile: c.gitSshProfile,
1097
+ repository,
1098
+ issue,
1099
+ labels: c.labels
1100
+ },
1101
+ { idempotencyKey: id }
1102
+ );
1103
+ if (launched.error) result.errors.push(`${id}:launch_failed`);
1104
+ else if (launched.process) result.created.push(id);
1105
+ else result.skipped.push(id);
1106
+ }
1107
+ }
1108
+ };
1109
+ }
1110
+
1111
+ // src/external.ts
1112
+ import { conflictKey } from "@leitwerk-dev/coding/repository-rebase";
1113
+ import {
1114
+ createExternalSourcePollReporter
1115
+ } from "@leitwerk-dev/process-sdk";
1116
+ import { emptyPollResult, parseDurationMs as parseDurationMs2 } from "@leitwerk-dev/watcher-utils";
1117
+ var GITLAB_ISSUE_CANCELLED_KIND = "@leitwerk-dev/gitlab.issue-cancelled";
1118
+ var GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
1119
+ function pendingGitLabFeedback(items, afterId, since) {
1120
+ const start = since ? Date.parse(since) : 0;
1121
+ return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
1122
+ }
1123
+ function gitLabFeedbackReadyAt(items, quietPeriodMs) {
1124
+ return items.length ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs : null;
1125
+ }
1126
+ var observationKey = ({ mr, pipeline, targetHead }) => JSON.stringify([
1127
+ mr.state,
1128
+ mr.sha,
1129
+ [...mr.labels].sort(),
1130
+ pipeline?.project_id,
1131
+ pipeline?.id,
1132
+ pipeline?.status,
1133
+ mr.source_project_id,
1134
+ mr.source_branch,
1135
+ mr.target_project_id,
1136
+ mr.target_branch,
1137
+ targetHead,
1138
+ mr.has_conflicts,
1139
+ mr.merge_status,
1140
+ mr.detailed_merge_status
1141
+ ]);
1142
+ var gitlabExternal = {
1143
+ /** Observe coordinated repositories with the same revision and feedback policy. @public */
1144
+ mergeRequests(resolve) {
1145
+ return {
1146
+ kind: GITLAB_MR_KIND,
1147
+ label: "GitLab merge requests",
1148
+ config: {},
1149
+ inputMode: "none",
1150
+ resolve
1151
+ };
1152
+ },
1153
+ /** @public */
1154
+ issueCancelled(resolve) {
1155
+ return {
1156
+ kind: GITLAB_ISSUE_CANCELLED_KIND,
1157
+ label: "GitLab source issue cancelled",
1158
+ config: {},
1159
+ inputMode: "none",
1160
+ resolve
1161
+ };
1162
+ },
1163
+ /** @public */
1164
+ mergeRequest(resolve) {
1165
+ return {
1166
+ kind: GITLAB_MR_KIND,
1167
+ label: "GitLab merge request",
1168
+ description: "Observe MR state, current source head and revision-correlated CI",
1169
+ config: {},
1170
+ inputMode: "none",
1171
+ resolve
1172
+ };
1173
+ }
1174
+ };
1175
+ function createGitLabProvider(deps, integration, options = {}) {
1176
+ const schedule = /* @__PURE__ */ new Map();
1177
+ const now = options.now ?? Date.now;
1178
+ const discover = createGitLabIssueDiscovery(deps, integration, now);
1179
+ return deps.polling.create({
1180
+ id: "gitlab",
1181
+ pollInterval: () => "5s",
1182
+ isEnabled: () => true,
1183
+ defaultIntervalMs: 5e3,
1184
+ async pollOnce() {
1185
+ const result = emptyPollResult();
1186
+ try {
1187
+ await discover(result);
1188
+ } catch (error) {
1189
+ result.errors.push(error instanceof Error ? error.message : "GitLab discovery failed");
1190
+ }
1191
+ const report = createExternalSourcePollReporter(deps.externalSources, result, {
1192
+ forwardGeneration: true,
1193
+ currentKinds: [GITLAB_MR_KIND, GITLAB_ISSUE_CANCELLED_KIND]
1194
+ });
1195
+ const pollRepository = async (armed, c) => {
1196
+ if (!c || typeof c.profile !== "string" || !Number.isInteger(c.projectId) || !Number.isInteger(c.iid))
1197
+ throw new Error("Invalid GitLab external source");
1198
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}:${c.projectKey ?? ""}`;
1199
+ const previous = schedule.get(key);
1200
+ if (previous && previous.at > now()) return;
1201
+ try {
1202
+ if (c.origin && integration.client(c.profile).baseUrl !== c.origin)
1203
+ throw new Error("GitLab observation installation changed");
1204
+ const observation = await observeMergeRequest(
1205
+ integration.client(c.profile),
1206
+ c.projectId,
1207
+ c.iid
1208
+ );
1209
+ let conflict;
1210
+ const client = integration.client(c.profile);
1211
+ if (c.delivery && observation.mr.state === "opened" && observation.mr.sha === c.delivery.headSha && (observation.mr.has_conflicts === true || observation.mr.detailed_merge_status === "conflict")) {
1212
+ const mr = observation.mr;
1213
+ const d = c.delivery;
1214
+ if (mr.source_project_id !== c.projectId || mr.target_project_id !== c.projectId || mr.source_branch !== d.headBranch || mr.target_branch !== d.baseBranch)
1215
+ throw new Error("GitLab merge request branches changed");
1216
+ const base = await client.getBranch(c.projectId, d.baseBranch);
1217
+ const evidence = {
1218
+ owner: d.owner,
1219
+ repo: d.repo,
1220
+ prNumber: c.iid,
1221
+ headBranch: d.headBranch,
1222
+ baseBranch: d.baseBranch,
1223
+ headSha: mr.sha,
1224
+ baseSha: base.commit.id,
1225
+ url: mr.web_url
1226
+ };
1227
+ if (conflictKey(evidence) !== d.lastConflictKey) conflict = evidence;
1228
+ }
1229
+ const observedKey = observationKey(observation) + (c.delivery ? `:${conflict ? conflictKey(conflict) : ""}` : "");
1230
+ const feedback = c.feedback && observation.mr.state === "opened" ? pendingGitLabFeedback(
1231
+ await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
1232
+ c.feedback.afterId,
1233
+ c.feedback.since
1234
+ ) : [];
1235
+ const feedbackReadyAt = gitLabFeedbackReadyAt(
1236
+ feedback,
1237
+ c.feedback?.quietPeriodMs ?? 12e4
1238
+ );
1239
+ const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
1240
+ if (c.delivery) {
1241
+ const fresh = await client.getMergeRequest(c.projectId, c.iid);
1242
+ if (fresh.sha !== observation.mr.sha || fresh.state !== observation.mr.state) return;
1243
+ }
1244
+ await report.observe(armed, {
1245
+ observation: {
1246
+ summary: `${observation.mr.state} \xB7 ${observation.pipeline?.status ?? "no current pipeline"}`,
1247
+ observedAt: new Date(now()).toISOString(),
1248
+ subject: observation.mr.web_url,
1249
+ revision: observation.mr.sha
1250
+ }
1251
+ });
1252
+ if (observedKey !== c.afterKey || feedbackReady || c.wakeAt !== void 0 && c.wakeAt <= now())
1253
+ await report.fire(
1254
+ armed,
1255
+ {
1256
+ ...observation,
1257
+ ...c.projectKey ? { projectKey: c.projectKey } : {},
1258
+ ...c.delivery ? {
1259
+ observationKey: observedKey,
1260
+ feedback: feedbackReady ? feedback : [],
1261
+ ...conflict ? { conflict } : {}
1262
+ } : {}
1263
+ },
1264
+ `${c.projectKey ?? ""}:${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`
1265
+ );
1266
+ schedule.set(key, {
1267
+ at: now() + parseDurationMs2(c.pollInterval ?? "30s", 3e4),
1268
+ failures: 0
1269
+ });
1270
+ } catch (error) {
1271
+ const failures = (previous?.failures ?? 0) + 1;
1272
+ schedule.set(key, {
1273
+ at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
1274
+ failures
1275
+ });
1276
+ await report.observe(armed, {
1277
+ refreshError: error instanceof Error ? error.message : "GitLab observation unavailable"
1278
+ });
1279
+ throw error;
1280
+ }
1281
+ };
1282
+ await report.poll(GITLAB_MR_KIND, async (armed) => {
1283
+ const config = armed.resolved;
1284
+ for (const source of config.repositories ?? [config]) {
1285
+ if (!report.isCurrent(GITLAB_MR_KIND, armed)) break;
1286
+ await pollRepository(armed, source);
1287
+ }
1288
+ });
1289
+ await report.poll(GITLAB_ISSUE_CANCELLED_KIND, async (armed) => {
1290
+ const c = armed.resolved;
1291
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
1292
+ if ((schedule.get(key)?.at ?? 0) > now()) return;
1293
+ const client = integration.client(c.profile);
1294
+ if (c.origin && client.baseUrl !== c.origin)
1295
+ throw new Error("GitLab source issue installation changed");
1296
+ const issue = await client.getIssue(c.projectId, c.issueIid);
1297
+ if (issue.state !== "opened" || !issue.labels.includes(c.triggerLabel)) {
1298
+ const mr = await client.getMergeRequest(c.projectId, c.iid);
1299
+ if (mr.state !== "opened") return;
1300
+ await report.fire(
1301
+ armed,
1302
+ { issue },
1303
+ `${issue.iid}:${issue.state}:${issue.labels.includes(c.triggerLabel)}`
1304
+ );
1305
+ }
1306
+ schedule.set(key, {
1307
+ at: now() + parseDurationMs2(c.pollInterval ?? "30s", 3e4),
1308
+ failures: 0
1309
+ });
1310
+ });
1311
+ return result;
1312
+ }
1313
+ });
1314
+ }
1315
+
1316
+ // src/maintenance-labels.ts
1317
+ var GITLAB_ACTIVE_LABEL = "leitwerk-active";
1318
+ var GITLAB_DONE_LABEL = "leitwerk-done";
1319
+ async function readGitLabLabels(client, projectId, iid, signal) {
1320
+ const events = await client.listMergeRequestLabelEvents(projectId, iid, signal);
1321
+ const mr = await client.getMergeRequest(projectId, iid, signal);
1322
+ return { mr, events: events.sort((a, b) => a.id - b.id) };
1323
+ }
1324
+ async function readMaintainedGitLabLabels(client, projectId, iid, signal) {
1325
+ try {
1326
+ return await readGitLabLabels(client, projectId, iid, signal);
1327
+ } catch (error) {
1328
+ if (!(error instanceof GitLabError) || error.status !== 404) throw error;
1329
+ try {
1330
+ await client.getMergeRequest(projectId, iid, signal);
1331
+ } catch (mrError) {
1332
+ if (!(mrError instanceof GitLabError) || mrError.status !== 404) throw mrError;
1333
+ await client.getProject(projectId, signal);
1334
+ return null;
1335
+ }
1336
+ throw error;
1337
+ }
1338
+ }
1339
+ function gitLabActivationStatus(after, labels) {
1340
+ const events = labels.events.filter(
1341
+ (event) => event.label?.name === GITLAB_ACTIVE_LABEL && event.id > after
1342
+ );
1343
+ if (events.some((event) => event.action === "remove")) return "removed";
1344
+ if (!events.length) return "pending";
1345
+ return labels.mr.labels.includes(GITLAB_ACTIVE_LABEL) ? "active" : "removed";
1346
+ }
1347
+ async function ensureGitLabMaintenanceLabels(input) {
1348
+ const { client, writes, projectId, iid, status, after, signal } = input;
1349
+ const settled = async () => {
1350
+ const labels = await readGitLabLabels(client, projectId, iid, signal);
1351
+ if (!await input.guard()) throw new Error("GitLab label write superseded");
1352
+ if (status === "active")
1353
+ return labels.mr.state !== "opened" || gitLabActivationStatus(after, labels) === "removed" || labels.mr.labels.includes(GITLAB_ACTIVE_LABEL) && !labels.mr.labels.includes(GITLAB_DONE_LABEL);
1354
+ const active = labels.events.filter(
1355
+ (event) => event.label?.name === GITLAB_ACTIVE_LABEL && event.id > after
1356
+ );
1357
+ if (active.some(
1358
+ (event, index) => event.action === "add" && active.slice(0, index).some((before) => before.action === "remove")
1359
+ ))
1360
+ return true;
1361
+ return !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL) && (status !== "merged" || labels.mr.labels.includes(GITLAB_DONE_LABEL) || labels.events.some(
1362
+ (event) => event.id > after && event.label?.name === GITLAB_DONE_LABEL && event.action === "add"
1363
+ ));
1364
+ };
1365
+ await writes.ensure(
1366
+ { writeType: "gitlab.mr_labels", dedupKey: input.writeKey },
1367
+ {
1368
+ reconcile: async (phase) => phase === "already_recorded" || await settled() ? true : null,
1369
+ execute: async () => {
1370
+ if (await settled()) return true;
1371
+ await client.updateMergeRequestLabels(
1372
+ projectId,
1373
+ iid,
1374
+ status === "active" ? { add_labels: GITLAB_ACTIVE_LABEL, remove_labels: GITLAB_DONE_LABEL } : {
1375
+ ...status === "merged" ? { add_labels: GITLAB_DONE_LABEL } : {},
1376
+ remove_labels: GITLAB_ACTIVE_LABEL
1377
+ },
1378
+ signal
1379
+ );
1380
+ return true;
1381
+ },
1382
+ toMetadata: () => ({ projectId, iid, status })
1383
+ }
1384
+ );
1385
+ }
1386
+
1387
+ // src/maintenance.ts
1388
+ import { asUnknownRecord as asUnknownRecord3 } from "@leitwerk-dev/domain";
1389
+ import {
1390
+ bindExternalWrites
1391
+ } from "@leitwerk-dev/external-writes/internal";
1392
+ import {
1393
+ createCapabilityToken as createCapabilityToken2
1394
+ } from "@leitwerk-dev/process-sdk";
1395
+ import { emptyPollResult as emptyPollResult2, parseDurationMs as parseDurationMs3 } from "@leitwerk-dev/watcher-utils";
1396
+ var GITLAB_MAINTAINED_KIND = "@leitwerk-dev/gitlab.maintained";
1397
+ function gitlabMaintenanceSource() {
1398
+ return {
1399
+ kind: GITLAB_MAINTAINED_KIND,
1400
+ label: "GitLab MR maintenance",
1401
+ config: {},
1402
+ inputMode: "none",
1403
+ resolve: ({ params, state, projects }) => ({ params, state, projects })
1404
+ };
1405
+ }
1406
+ var gitlabMaintenance = createCapabilityToken2(
1407
+ "@leitwerk-dev/gitlab.maintenance"
1408
+ );
1409
+ function registerGitLabMaintainedProcess(api, policy) {
1410
+ const service = api.require(gitlabMaintenance);
1411
+ if (Array.isArray(service)) throw new Error("GitLab maintenance must be singular");
1412
+ service.register(policy);
1413
+ }
1414
+ var maintenanceRecords = (process2) => asUnknownRecord3(process2.metadata?.gitlabMaintenance) ?? {};
1415
+ function createGitLabMaintenance(api, deps, integration, now = Date.now) {
1416
+ const policies = /* @__PURE__ */ new Map();
1417
+ const due = /* @__PURE__ */ new Map();
1418
+ const completionDue = /* @__PURE__ */ new Map();
1419
+ const workKey = (process2) => JSON.stringify([
1420
+ process2.paramsJson,
1421
+ process2.stateJson,
1422
+ process2.planRevision,
1423
+ process2.selectedTurnId,
1424
+ process2.lifecycleStatus,
1425
+ process2.currentExecution
1426
+ ]);
1427
+ const repo = deps.externalWrites;
1428
+ const observe = (expected, update) => deps.commands.applyProcessObservation(expected.id, { expected, ...update });
1429
+ const context = (process2, policy) => ({
1430
+ process: process2,
1431
+ projects: deps.projects.listByInstance(process2.id),
1432
+ params: policy.paramsCodec.parse(JSON.parse(process2.paramsJson ?? "null")),
1433
+ state: policy.stateCodec.parse(JSON.parse(process2.stateJson ?? "null")),
1434
+ now: now(),
1435
+ signal: AbortSignal.timeout(3e4),
1436
+ externalWrites: bindExternalWrites(repo, process2.id),
1437
+ callIntegrationTool: (name, args) => {
1438
+ if (!deps.callIntegrationTool)
1439
+ throw new Error("Server maintenance operations are unavailable");
1440
+ return deps.callIntegrationTool(
1441
+ process2,
1442
+ String(args.projectKey ?? "repo"),
1443
+ name,
1444
+ args,
1445
+ AbortSignal.timeout(3e4)
1446
+ );
1447
+ }
1448
+ });
1449
+ const bindings = (ctx, policy) => policy.bindings?.(ctx) ?? ctx.projects.flatMap((project) => {
1450
+ if (!asUnknownRecord3(project.metadata?.gitlab)?.iid) return [];
1451
+ return [
1452
+ {
1453
+ projectKey: project.key,
1454
+ ...resolveGitLabBinding({ process: ctx.process, project }, integration),
1455
+ origin: asUnknownRecord3(project.metadata?.gitlab)?.origin
1456
+ }
1457
+ ];
1458
+ });
1459
+ const completionStatus = (ctx, policy, records) => {
1460
+ if (Object.values(records).some((record) => record.status === "deleted"))
1461
+ return "aborted";
1462
+ if (policy.completion) return policy.completion(ctx, records);
1463
+ return bindings(ctx, policy).every(
1464
+ (binding) => records[binding.projectKey] && records[binding.projectKey].status !== "active"
1465
+ ) ? Object.values(records).some((record) => record.status === "merged") ? "completed" : "aborted" : void 0;
1466
+ };
1467
+ const live = (process2) => !["completed", "aborted"].includes(process2.lifecycleStatus);
1468
+ const unchangedWork = (fresh, expected) => workKey(fresh) === workKey(expected);
1469
+ const same = (expected) => {
1470
+ const fresh = deps.processes.getById(expected.id);
1471
+ return !!fresh && unchangedWork(fresh, expected) && JSON.stringify(fresh.metadata?.gitlabMaintenance) === JSON.stringify(expected.metadata?.gitlabMaintenance);
1472
+ };
1473
+ const scheduleNext = (key, process2, settings) => due.set(key, {
1474
+ at: now() + parseDurationMs3(settings.pollInterval ?? "30s", 3e4),
1475
+ failures: 0,
1476
+ inputs: workKey(deps.processes.getById(process2.id) ?? process2)
1477
+ });
1478
+ const service = {
1479
+ register(policy) {
1480
+ if (policy.retry && (!Number.isInteger(policy.retry.maxAttempts) || policy.retry.maxAttempts < 0))
1481
+ throw new Error("GitLab maintenance retries must be a nonnegative integer");
1482
+ if (policies.has(policy.processId))
1483
+ throw new Error(`Duplicate GitLab maintenance policy '${policy.processId}'`);
1484
+ policies.set(
1485
+ policy.processId,
1486
+ policy
1487
+ );
1488
+ },
1489
+ ownsProcess: (processId) => policies.has(processId),
1490
+ async assertOwnership(instanceId, projectKey, signal) {
1491
+ let process2 = deps.processes.getById(instanceId);
1492
+ if (!process2 || !live(process2)) throw new Error("GitLab maintenance ownership ended");
1493
+ const policy = policies.get(process2.processId);
1494
+ if (!policy) return;
1495
+ let ctx = context(process2, policy);
1496
+ const binding = bindings(ctx, policy).find((item) => item.projectKey === projectKey);
1497
+ if (!binding) return;
1498
+ let record = maintenanceRecords(process2)[projectKey];
1499
+ if (record && record.status !== "active")
1500
+ throw new Error("GitLab maintenance ownership ended");
1501
+ const client = integration.client(binding.profile);
1502
+ if (binding.origin && binding.origin !== client.baseUrl)
1503
+ throw new Error("GitLab installation changed");
1504
+ let labels = await readGitLabLabels(client, binding.projectId, binding.iid, signal);
1505
+ const settings = policy.settings?.(ctx, binding) ?? {};
1506
+ const activationKey = settings.activationWriteKey ?? `gitlab:active:${process2.id}:${projectKey}:${binding.iid}`;
1507
+ if (!record) {
1508
+ if (repo.hasDedupKey(activationKey) && !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL))
1509
+ throw new Error("GitLab maintenance ownership ended");
1510
+ record = {
1511
+ binding,
1512
+ after: settings.activationAfter ?? labels.events.at(-1)?.id ?? 0,
1513
+ status: "active",
1514
+ cursor: settings.cursor ?? 0,
1515
+ pendingFeedback: []
1516
+ };
1517
+ const saved = await observe(process2, {
1518
+ projectsJson: JSON.stringify(ctx.projects),
1519
+ metadata: { gitlabMaintenance: { ...maintenanceRecords(process2), [projectKey]: record } },
1520
+ preserveUpdatedAt: true
1521
+ });
1522
+ if (!saved.ok) throw new Error("GitLab maintenance ownership changed");
1523
+ process2 = deps.processes.getById(instanceId);
1524
+ if (!process2 || !live(process2)) throw new Error("GitLab maintenance ownership ended");
1525
+ const adopted = process2;
1526
+ await ensureGitLabMaintenanceLabels({
1527
+ client,
1528
+ writes: ctx.externalWrites,
1529
+ projectId: binding.projectId,
1530
+ iid: binding.iid,
1531
+ after: record.after,
1532
+ status: "active",
1533
+ writeKey: activationKey,
1534
+ guard: async () => same(adopted),
1535
+ signal
1536
+ });
1537
+ labels = await readGitLabLabels(client, binding.projectId, binding.iid, signal);
1538
+ ctx = context(process2, policy);
1539
+ }
1540
+ const after = record.after;
1541
+ if (!same(process2) || labels.mr.state !== "opened" || gitLabActivationStatus(after, labels) === "removed" || !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL))
1542
+ throw new Error("GitLab maintenance ownership ended");
1543
+ if (policy.canWrite && !await policy.canWrite(ctx, binding))
1544
+ throw new Error("GitLab maintenance writes are suspended by process policy");
1545
+ }
1546
+ };
1547
+ api.provide(gitlabMaintenance, service);
1548
+ const polling = deps.polling.create({
1549
+ id: "gitlab-maintenance",
1550
+ pollInterval: () => "5s",
1551
+ isEnabled: () => true,
1552
+ defaultIntervalMs: 5e3,
1553
+ async pollOnce() {
1554
+ const result = emptyPollResult2();
1555
+ for (const snapshot of deps.processes.listAll()) {
1556
+ const policy = policies.get(snapshot.processId);
1557
+ if (!policy) continue;
1558
+ let ctx = context(snapshot, policy);
1559
+ for (const binding of bindings(ctx, policy)) {
1560
+ const key = `${snapshot.id}:${binding.projectKey}`;
1561
+ const previous = due.get(key);
1562
+ if (previous && previous.at > now() && previous.inputs === workKey(snapshot)) continue;
1563
+ try {
1564
+ const process2 = deps.processes.getById(snapshot.id);
1565
+ if (!process2) continue;
1566
+ ctx = context(process2, policy);
1567
+ const settings = policy.settings?.(ctx, binding) ?? {};
1568
+ const known = maintenanceRecords(process2)[binding.projectKey];
1569
+ if (known?.status === "deleted") continue;
1570
+ if (known && known.status !== "active" && process2.metadata?.gitlabMaintenanceCompleted && repo.hasDedupKey(
1571
+ `gitlab:${known.status}:${process2.id}:${binding.projectKey}:${binding.iid}`
1572
+ ))
1573
+ continue;
1574
+ const client = integration.client(binding.profile);
1575
+ if (binding.origin && client.baseUrl !== binding.origin)
1576
+ throw new Error("GitLab installation changed");
1577
+ const labels = await readMaintainedGitLabLabels(
1578
+ client,
1579
+ binding.projectId,
1580
+ binding.iid,
1581
+ ctx.signal
1582
+ );
1583
+ const records = structuredClone(maintenanceRecords(process2));
1584
+ let record = records[binding.projectKey];
1585
+ if (record && JSON.stringify(record.binding) !== JSON.stringify(binding))
1586
+ throw new Error("Maintained MR binding changed");
1587
+ if (!record)
1588
+ record = records[binding.projectKey] = {
1589
+ binding,
1590
+ after: settings.activationAfter ?? labels?.events.at(-1)?.id ?? 0,
1591
+ status: "active",
1592
+ cursor: settings.cursor ?? 0,
1593
+ pendingFeedback: []
1594
+ };
1595
+ record.cursor = Math.max(record.cursor, settings.cursor ?? 0);
1596
+ const activationKey = settings.activationWriteKey ?? `gitlab:active:${process2.id}:${binding.projectKey}:${binding.iid}`;
1597
+ let stopped = false;
1598
+ let state = ctx.state;
1599
+ if (!labels) {
1600
+ record.status = "deleted";
1601
+ record.pendingFeedback = [];
1602
+ delete record.observation;
1603
+ state = policy.stopped?.(ctx, binding) ?? state;
1604
+ stopped = true;
1605
+ } else if (record.status === "active") {
1606
+ if (labels.mr.state !== "opened") {
1607
+ record.status = labels.mr.state === "merged" ? "merged" : "closed";
1608
+ state = policy.terminal?.(ctx, binding, { mr: labels.mr, pipeline: null }) ?? state;
1609
+ stopped = true;
1610
+ } else if (!live(process2) || gitLabActivationStatus(record.after, labels) === "removed" || repo.hasDedupKey(activationKey) && !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL)) {
1611
+ record.status = "stopped";
1612
+ state = policy.stopped?.(ctx, binding) ?? state;
1613
+ stopped = true;
1614
+ }
1615
+ }
1616
+ delete record.refreshError;
1617
+ const terminalStatus = stopped && live(process2) ? completionStatus({ ...ctx, state }, policy, records) : void 0;
1618
+ const saved = await observe(process2, {
1619
+ projectsJson: JSON.stringify(ctx.projects),
1620
+ metadata: { gitlabMaintenance: records },
1621
+ ...state !== ctx.state ? { state } : {},
1622
+ ...terminalStatus ? { lifecycleStatus: terminalStatus } : {},
1623
+ ...stopped && !terminalStatus && live(process2) && (process2.currentExecution || process2.selectedTurnId !== policy.idleTurnId && (!policy.currentBinding || policy.currentBinding(ctx) === binding.projectKey)) ? {
1624
+ interrupt: {
1625
+ turnId: policy.idleTurnId,
1626
+ reason: "MR maintenance ownership ended"
1627
+ }
1628
+ } : {},
1629
+ preserveUpdatedAt: !stopped
1630
+ });
1631
+ if (!saved.ok) continue;
1632
+ let fresh = deps.processes.getById(process2.id);
1633
+ if (!fresh) continue;
1634
+ if (record.status === "deleted") continue;
1635
+ const remoteWriteContext = (payload) => ({
1636
+ client,
1637
+ writes: ctx.externalWrites,
1638
+ instanceId: process2.id,
1639
+ projectId: binding.projectId,
1640
+ iid: binding.iid,
1641
+ ...payload,
1642
+ signal: ctx.signal,
1643
+ beforeWrite: () => service.assertOwnership(fresh?.id ?? "", binding.projectKey, ctx.signal)
1644
+ });
1645
+ await ensureGitLabMaintenanceLabels({
1646
+ client,
1647
+ writes: ctx.externalWrites,
1648
+ projectId: binding.projectId,
1649
+ iid: binding.iid,
1650
+ after: record.after,
1651
+ status: record.status,
1652
+ writeKey: record.status === "active" ? activationKey : `gitlab:${record.status}:${process2.id}:${binding.projectKey}:${binding.iid}`,
1653
+ guard: async () => same(fresh),
1654
+ signal: ctx.signal
1655
+ });
1656
+ if (!live(fresh) || record.status !== "active") {
1657
+ scheduleNext(key, process2, settings);
1658
+ continue;
1659
+ }
1660
+ ctx = context(fresh, policy);
1661
+ const observation = policy.assess ? await policy.assess(ctx, binding) : await observeMergeRequest(client, binding.projectId, binding.iid, ctx.signal);
1662
+ const eligible = policy.eligible?.(ctx, binding, observation) ?? true;
1663
+ const feedback = eligible ? pendingGitLabFeedback(
1664
+ "feedback" in observation ? observation.feedback ?? [] : await client.listMergeRequestFeedback(
1665
+ binding.projectId,
1666
+ binding.iid,
1667
+ ctx.signal
1668
+ ),
1669
+ Math.max(record.cursor, settings.cursor ?? 0),
1670
+ settings.since
1671
+ ) : [];
1672
+ for (const note of feedback) {
1673
+ await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
1674
+ await ensureGitLabSeenReaction(remoteWriteContext({ noteId: note.id }));
1675
+ }
1676
+ const ready = gitLabFeedbackReadyAt(feedback, settings.quietPeriodMs ?? 12e4);
1677
+ const targetIntegrated = observation.targetHead && client.getMergeBase && observation.mr.source_project_id === observation.mr.target_project_id && (observation.mr.has_conflicts || ["conflict", "need_rebase"].includes(observation.mr.detailed_merge_status ?? "")) ? (await client.getMergeBase(
1678
+ observation.mr.source_project_id,
1679
+ [observation.mr.sha, observation.targetHead],
1680
+ ctx.signal
1681
+ )).id === observation.targetHead : false;
1682
+ const observed = {
1683
+ ...observation,
1684
+ targetIntegrated,
1685
+ projectKey: binding.projectKey,
1686
+ observationKey: observationKey(observation),
1687
+ feedback: ready !== null && ready <= now() ? feedback : []
1688
+ };
1689
+ const decision = policy.observe(ctx, binding, observed);
1690
+ record.observation = observed;
1691
+ record.pendingFeedback = feedback;
1692
+ const observedRecords = { ...maintenanceRecords(fresh), [binding.projectKey]: record };
1693
+ const updated = await observe(fresh, {
1694
+ projectsJson: JSON.stringify(ctx.projects),
1695
+ metadata: { gitlabMaintenance: observedRecords },
1696
+ ...!fresh.currentExecution && decision.state !== ctx.state && !decision.action ? { state: decision.state } : {},
1697
+ preserveUpdatedAt: true
1698
+ });
1699
+ if (!updated.ok) continue;
1700
+ fresh = deps.processes.getById(process2.id);
1701
+ if (!fresh) continue;
1702
+ if (eligible && decision.action && fresh.lifecycleStatus === "waiting" && unchangedWork(fresh, ctx.process)) {
1703
+ const destination = policy.destinations[decision.action] ?? decision.action;
1704
+ const armed = deps.externalSources.listArmed(policy.sourceKind ?? GITLAB_MAINTAINED_KIND).find(
1705
+ (item) => item.instanceId === process2.id && item.externalActionId === destination
1706
+ );
1707
+ if (armed) {
1708
+ await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
1709
+ const fired = await deps.externalSources.fire({
1710
+ instanceId: fresh.id,
1711
+ armingId: armed.id,
1712
+ generation: armed.generation,
1713
+ event: { ...decision.event, state: decision.state },
1714
+ mergeKey: `${binding.projectKey}:${observed.observationKey}:${feedback.map((note) => note.id)}`
1715
+ });
1716
+ if (!fired.ok) continue;
1717
+ }
1718
+ }
1719
+ fresh = deps.processes.getById(process2.id);
1720
+ if (!fresh || !live(fresh)) continue;
1721
+ ctx = context(fresh, policy);
1722
+ for (const message of eligible ? policy.messages?.(ctx, binding) ?? [] : []) {
1723
+ await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
1724
+ await ensureGitLabComment(remoteWriteContext(message));
1725
+ }
1726
+ const settledState = eligible ? policy.settled?.(ctx, binding) ?? ctx.state : ctx.state;
1727
+ if (!fresh.currentExecution && settledState !== ctx.state)
1728
+ await observe(fresh, { state: settledState });
1729
+ fresh = deps.processes.getById(process2.id);
1730
+ if (fresh && eligible && policy.retry && fresh.lifecycleStatus === "error" && fresh.currentExecution) {
1731
+ const retry = asUnknownRecord3(fresh.metadata?.gitlabMaintenanceRetry) ?? {};
1732
+ const attempts = Number(retry.attempts ?? 0);
1733
+ if (retry.executionId !== fresh.currentExecution.id) {
1734
+ await observe(fresh, {
1735
+ metadata: {
1736
+ gitlabMaintenanceRetry: {
1737
+ attempts,
1738
+ executionId: fresh.currentExecution.id,
1739
+ nextAt: now() + Math.min(3e5, 3e4 * 2 ** attempts),
1740
+ attempted: false
1741
+ }
1742
+ },
1743
+ preserveUpdatedAt: true
1744
+ });
1745
+ } else if (!retry.attempted && attempts < policy.retry.maxAttempts && Number(retry.nextAt) <= now()) {
1746
+ await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
1747
+ const saved2 = await observe(fresh, {
1748
+ metadata: {
1749
+ gitlabMaintenanceRetry: { ...retry, attempts: attempts + 1, attempted: true }
1750
+ }
1751
+ });
1752
+ if (saved2.ok) await deps.commands.retryProcess(fresh.id);
1753
+ }
1754
+ } else if (fresh?.lifecycleStatus === "waiting" && !fresh.currentExecution && fresh.selectedTurnId === policy.idleTurnId && fresh.metadata?.gitlabMaintenanceRetry) {
1755
+ await observe(fresh, {
1756
+ metadata: { gitlabMaintenanceRetry: null },
1757
+ preserveUpdatedAt: true
1758
+ });
1759
+ }
1760
+ scheduleNext(key, process2, settings);
1761
+ } catch (error) {
1762
+ const message = error instanceof Error ? error.message : "GitLab maintenance unavailable";
1763
+ const failures = (previous?.failures ?? 0) + 1;
1764
+ due.set(key, {
1765
+ at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
1766
+ failures,
1767
+ inputs: workKey(deps.processes.getById(snapshot.id) ?? snapshot)
1768
+ });
1769
+ const fresh = deps.processes.getById(snapshot.id);
1770
+ if (fresh) {
1771
+ const records = structuredClone(maintenanceRecords(fresh));
1772
+ if (records[binding.projectKey]) {
1773
+ records[binding.projectKey].refreshError = message;
1774
+ await observe(fresh, { metadata: { gitlabMaintenance: records } });
1775
+ }
1776
+ }
1777
+ result.errors.push(`${key}:${message}`);
1778
+ }
1779
+ }
1780
+ let current = deps.processes.getById(snapshot.id);
1781
+ if (current && !current.metadata?.gitlabMaintenanceCompleted && bindings(context(current, policy), policy).length) {
1782
+ try {
1783
+ ctx = context(current, policy);
1784
+ const records = maintenanceRecords(current);
1785
+ const schedule = completionDue.get(current.id);
1786
+ const pureStatus = completionStatus(ctx, policy, records);
1787
+ if (schedule && schedule.at > now() && (schedule.failures > 0 || !pureStatus && live(current)))
1788
+ continue;
1789
+ const status = pureStatus ?? (live(current) && await policy.cancelled?.(ctx) ? "aborted" : void 0);
1790
+ if (status && live(current)) {
1791
+ const ended = await observe(current, { lifecycleStatus: status });
1792
+ if (!ended.ok) continue;
1793
+ current = deps.processes.getById(current.id);
1794
+ }
1795
+ if (current && (status || !live(current))) {
1796
+ await policy.complete?.(context(current, policy), maintenanceRecords(current));
1797
+ await observe(current, {
1798
+ metadata: { gitlabMaintenanceCompleted: true }
1799
+ });
1800
+ }
1801
+ completionDue.set(snapshot.id, { at: now() + 3e4, failures: 0 });
1802
+ } catch (error) {
1803
+ const failures = (completionDue.get(snapshot.id)?.failures ?? 0) + 1;
1804
+ completionDue.set(snapshot.id, {
1805
+ at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
1806
+ failures
1807
+ });
1808
+ result.errors.push(
1809
+ `${snapshot.id}:${error instanceof Error ? error.message : "Completion delivery unavailable"}`
1810
+ );
1811
+ }
1812
+ }
1813
+ }
1814
+ return result;
1815
+ }
1816
+ });
1817
+ return {
1818
+ ...service,
1819
+ /** @internal */
1820
+ poll: () => polling.poll()
1821
+ };
1822
+ }
1823
+
1824
+ // src/repository-catalog.ts
1825
+ function createGitLabRepositoryCatalog(integration) {
1826
+ const profiles = /* @__PURE__ */ new Map();
1827
+ function entry(profile) {
1828
+ const client = integration.client(profile);
1829
+ let cached = profiles.get(profile);
1830
+ if (!cached || cached.origin !== client.baseUrl) {
1831
+ cached = { origin: client.baseUrl, known: /* @__PURE__ */ new Map(), searches: /* @__PURE__ */ new Map() };
1832
+ profiles.set(profile, cached);
1833
+ }
1834
+ return { client, cached };
1835
+ }
1836
+ async function refresh(profile) {
1837
+ const { client, cached } = entry(profile);
1838
+ if (cached.pending) return cached.pending;
1839
+ const scan = Promise.resolve().then(() => client.listProjects()).then((projects) => {
1840
+ cached.projects = structuredClone(projects);
1841
+ cached.searches.clear();
1842
+ cached.known.clear();
1843
+ return cached.projects;
1844
+ });
1845
+ cached.pending = scan;
1846
+ try {
1847
+ return await scan;
1848
+ } finally {
1849
+ cached.pending = void 0;
1850
+ }
1851
+ }
1852
+ return {
1853
+ async search(profile, text) {
1854
+ const query = text.trim().toLowerCase();
1855
+ if (query.length < 2) return [];
1856
+ const { client, cached } = entry(profile);
1857
+ if (cached.projects)
1858
+ return cached.projects.filter((project) => project.path_with_namespace.toLowerCase().includes(query)).slice(0, 100);
1859
+ const result = cached.searches.get(query);
1860
+ if (result) return result;
1861
+ const scan = Promise.resolve().then(() => client.searchProjects(query)).then((projects) => {
1862
+ const snapshot = structuredClone(projects);
1863
+ if (cached.searches.get(query) === scan)
1864
+ for (const project of snapshot) cached.known.set(project.id, project);
1865
+ return snapshot;
1866
+ }).catch((error) => {
1867
+ if (cached.searches.get(query) === scan) cached.searches.delete(query);
1868
+ throw error;
1869
+ });
1870
+ cached.searches.set(query, scan);
1871
+ return scan;
1872
+ },
1873
+ peek(profile, projectId) {
1874
+ const { cached } = entry(profile);
1875
+ return cached.projects ? cached.projects.find((project) => project.id === projectId) : cached.known.get(projectId);
1876
+ },
1877
+ async list(profile) {
1878
+ return entry(profile).cached.projects ?? refresh(profile);
1879
+ },
1880
+ refresh
1881
+ };
1882
+ }
1883
+
1884
+ // src/setup.ts
1885
+ import {
1886
+ coreHostCapabilities,
1887
+ repositorySettingsIdentity,
1888
+ scopedSettingsCapability
1889
+ } from "@leitwerk-dev/process-sdk";
1890
+
1891
+ // src/delivery-tools.ts
1892
+ import { createHash as createHash2 } from "crypto";
1893
+ import {
1894
+ numberArg as numberArg2,
1895
+ projectParameters as projectParameters2,
1896
+ stringArg as stringArg2
1897
+ } from "@leitwerk-dev/process-sdk";
1898
+ function registerGitLabDeliveryTools(api, integration, projects) {
1899
+ api.tool({
1900
+ name: "gitlab_ensure_merge_request",
1901
+ description: "Create or reconcile and pin the process merge request",
1902
+ parameters: projectParameters2({ title: { type: "string" }, body: { type: "string" } }, [
1903
+ "title",
1904
+ "body"
1905
+ ]),
1906
+ async execute(ctx, args) {
1907
+ const binding = resolveGitLabRepositoryBinding(ctx, integration);
1908
+ const client = integration.client(binding.profile);
1909
+ const project = projects.getByInstanceAndKey(ctx.process.id, ctx.project?.key ?? "");
1910
+ if (!project?.workBranch || project.workBranch === project.baseBranch)
1911
+ throw new Error("A process feature branch is required");
1912
+ const workBranch = project.workBranch;
1913
+ const identity = {
1914
+ writeType: "gitlab.ensure_mr",
1915
+ dedupKey: `${binding.projectId}:${project.key}:${workBranch}:${project.baseBranch}`
1916
+ };
1917
+ const marker = `<!-- leitwerk:gitlab:merge-request:${ctx.process.id}:${project.key} -->`;
1918
+ const find = async () => (await client.listBranchMergeRequests(
1919
+ binding.projectId,
1920
+ workBranch,
1921
+ project.baseBranch,
1922
+ ctx.signal
1923
+ )).find(
1924
+ (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)
1925
+ );
1926
+ const request = await ctx.externalWrites.ensure(identity, {
1927
+ reconcile: async () => await find() ?? null,
1928
+ execute: () => client.createMergeRequest(
1929
+ binding.projectId,
1930
+ {
1931
+ title: stringArg2(args, "title"),
1932
+ description: `${stringArg2(args, "body")}
1933
+
1934
+ ${marker}`,
1935
+ source_branch: workBranch,
1936
+ target_branch: project.baseBranch
1937
+ },
1938
+ ctx.signal
1939
+ ),
1940
+ toMetadata: (mr) => ({ iid: mr.iid, url: mr.web_url })
1941
+ });
1942
+ const latest = projects.getByInstanceAndKey(ctx.process.id, project.key);
1943
+ if (!latest || latest.workBranch !== project.workBranch || latest.baseBranch !== project.baseBranch)
1944
+ throw new Error("Process repository binding changed during publication");
1945
+ const metadata = latest.metadata ?? {};
1946
+ const previous = metadata.gitlab;
1947
+ if (previous.iid && previous.iid !== request.iid)
1948
+ throw new Error("Process is already bound to another merge request");
1949
+ projects.update(latest.id, {
1950
+ metadata: { ...metadata, gitlab: { ...previous, ...binding, iid: request.iid } },
1951
+ externalId: String(request.iid),
1952
+ externalUrl: request.web_url
1953
+ });
1954
+ return request;
1955
+ }
1956
+ });
1957
+ api.tool({
1958
+ name: "gitlab_list_merge_request_feedback",
1959
+ description: "Read human discussion feedback on the bound merge request",
1960
+ parameters: projectParameters2(),
1961
+ async execute(ctx) {
1962
+ const b = resolveGitLabBinding(ctx, integration);
1963
+ return integration.client(b.profile).listMergeRequestFeedback(b.projectId, b.iid, ctx.signal);
1964
+ }
1965
+ });
1966
+ api.tool({
1967
+ name: "gitlab_acknowledge_feedback",
1968
+ description: "Reconcile the bot's seen reaction on bound merge request feedback",
1969
+ parameters: projectParameters2({ noteId: { type: "integer" } }, ["noteId"]),
1970
+ async execute(ctx, args) {
1971
+ const b = resolveGitLabBinding(ctx, integration);
1972
+ const client = integration.client(b.profile);
1973
+ const noteId = numberArg2(args, "noteId");
1974
+ if (!(await client.listMergeRequestFeedback(b.projectId, b.iid, ctx.signal)).some(
1975
+ (n) => n.id === noteId
1976
+ ))
1977
+ throw new Error("Note is not actionable feedback on the bound merge request");
1978
+ await ensureGitLabSeenReaction({
1979
+ client,
1980
+ writes: ctx.externalWrites,
1981
+ instanceId: ctx.process.id,
1982
+ projectId: b.projectId,
1983
+ iid: b.iid,
1984
+ noteId,
1985
+ signal: ctx.signal
1986
+ });
1987
+ return { ok: true };
1988
+ }
1989
+ });
1990
+ for (const name of [
1991
+ "gitlab_get_issue",
1992
+ "gitlab_add_issue_comment",
1993
+ "gitlab_finalize_source_issue"
1994
+ ]) {
1995
+ api.tool({
1996
+ name,
1997
+ description: "Read or reconcile the process source issue",
1998
+ parameters: projectParameters2(
1999
+ {
2000
+ issueNumber: { type: "integer" },
2001
+ body: { type: "string" },
2002
+ writeKey: { type: "string" },
2003
+ merged: { type: "boolean" },
2004
+ triggerLabel: { type: "string" },
2005
+ doneLabel: { type: "string" }
2006
+ },
2007
+ ["issueNumber"]
2008
+ ),
2009
+ async execute(ctx, args) {
2010
+ const b = resolveGitLabRepositoryBinding(ctx, integration);
2011
+ const client = integration.client(b.profile);
2012
+ const iid = numberArg2(args, "issueNumber");
2013
+ const bound = ctx.project?.metadata?.gitlab?.issueIid;
2014
+ if (bound !== iid) throw new Error("Issue does not match the process source issue");
2015
+ if (name === "gitlab_get_issue") return client.getIssue(b.projectId, iid, ctx.signal);
2016
+ const key = stringArg2(args, "writeKey");
2017
+ const digest = createHash2("sha256").update(JSON.stringify([client.baseUrl, b.projectId, iid, ctx.process.id, key])).digest("hex");
2018
+ if (name === "gitlab_add_issue_comment") {
2019
+ const marker = `<!-- leitwerk:gitlab:issue:${digest} -->`;
2020
+ const note = await ctx.externalWrites.ensure(
2021
+ { writeType: name, dedupKey: digest },
2022
+ {
2023
+ reconcile: async () => (await client.listIssueNotes(b.projectId, iid, ctx.signal)).find(
2024
+ (n) => n.body.includes(marker)
2025
+ ) ?? null,
2026
+ execute: () => client.addIssueNote(
2027
+ b.projectId,
2028
+ iid,
2029
+ `${stringArg2(args, "body")}
2030
+
2031
+ ${marker}`,
2032
+ ctx.signal
2033
+ ),
2034
+ toMetadata: (note2) => ({ noteId: note2.id })
2035
+ }
2036
+ );
2037
+ return { noteId: note.id };
2038
+ }
2039
+ const merged = args.merged === true;
2040
+ const trigger = stringArg2(args, "triggerLabel");
2041
+ const done = stringArg2(args, "doneLabel");
2042
+ if (merged) {
2043
+ await ctx.externalWrites.ensure(
2044
+ {
2045
+ writeType: "gitlab.ensure_label",
2046
+ dedupKey: JSON.stringify([client.baseUrl, b.projectId, done])
2047
+ },
2048
+ {
2049
+ reconcile: async () => (await client.listLabels(b.projectId, ctx.signal)).find((l) => l.name === done) ?? null,
2050
+ execute: () => client.createLabel(b.projectId, done, ctx.signal),
2051
+ toMetadata: (label) => ({ name: label.name })
2052
+ }
2053
+ );
2054
+ }
2055
+ await ctx.externalWrites.ensure(
2056
+ { writeType: name, dedupKey: digest },
2057
+ {
2058
+ reconcile: async () => {
2059
+ const fresh = await client.getIssue(b.projectId, iid, ctx.signal);
2060
+ return !fresh.labels.includes(trigger) && (!merged || fresh.state === "closed" && fresh.labels.includes(done)) ? fresh : null;
2061
+ },
2062
+ execute: async () => {
2063
+ const issue = await client.getIssue(b.projectId, iid, ctx.signal);
2064
+ const labels = [
2065
+ .../* @__PURE__ */ new Set([
2066
+ ...issue.labels.filter((l) => l !== trigger),
2067
+ ...merged ? [done] : []
2068
+ ])
2069
+ ];
2070
+ return client.updateIssue(
2071
+ b.projectId,
2072
+ iid,
2073
+ { labels: labels.join(","), ...merged ? { state_event: "close" } : {} },
2074
+ ctx.signal
2075
+ );
2076
+ },
2077
+ toMetadata: () => ({ issueIid: iid, merged })
2078
+ }
2079
+ );
2080
+ return { issueIid: iid, merged };
2081
+ }
2082
+ });
2083
+ }
2084
+ }
2085
+
2086
+ // src/ticket-creation.ts
2087
+ import {
2088
+ listTicketDestinations,
2089
+ markdownTicketCreationDefinition,
2090
+ numberArg as numberArg3,
2091
+ objectArg,
2092
+ parseTicketDestinationId,
2093
+ stringArg as stringArg3,
2094
+ ticketDestinationId,
2095
+ ticketLabelNames
2096
+ } from "@leitwerk-dev/process-sdk";
2097
+ function available(project) {
2098
+ return !project.archived && project.issues_enabled !== false && project.issues_access_level !== "disabled";
2099
+ }
2100
+ function destinationData(snapshot) {
2101
+ const data = objectArg(snapshot.data);
2102
+ return {
2103
+ profile: stringArg3(data, "profile"),
2104
+ baseUrl: stringArg3(data, "baseUrl"),
2105
+ projectId: numberArg3(data, "projectId"),
2106
+ path: stringArg3(data, "path"),
2107
+ defaultLabels: ticketLabelNames(data.defaultLabels)
2108
+ };
2109
+ }
2110
+ function registerGitLabTicketCreation(api, integration, config) {
2111
+ if (!config.enabled) return;
2112
+ const summary = (profile, project) => ({
2113
+ id: ticketDestinationId(profile, project.id),
2114
+ displayName: project.path_with_namespace,
2115
+ group: `${profile} \xB7 ${new URL(integration.client(profile).baseUrl).hostname}`,
2116
+ description: config.defaultLabels.length ? `Default labels: ${config.defaultLabels.join(", ")}` : "No default labels"
2117
+ });
2118
+ const destinations = {
2119
+ list() {
2120
+ return listTicketDestinations(
2121
+ "GitLab",
2122
+ integration.profiles(),
2123
+ async (profile) => (await integration.client(profile).listProjects()).filter(available).map((project) => summary(profile, project))
2124
+ );
2125
+ },
2126
+ async resolve({ destinationId }) {
2127
+ const { profile, resourceId } = parseTicketDestinationId(destinationId);
2128
+ const client = integration.client(profile);
2129
+ const project = await client.getProject(Number(resourceId));
2130
+ if (!available(project)) throw new Error("The selected GitLab project cannot accept issues");
2131
+ const labels = await client.listLabels(project.id);
2132
+ return {
2133
+ summary: summary(profile, project),
2134
+ data: {
2135
+ profile,
2136
+ baseUrl: client.baseUrl,
2137
+ projectId: project.id,
2138
+ path: project.path_with_namespace,
2139
+ defaultLabels: config.defaultLabels
2140
+ },
2141
+ agentContext: `Create an issue in ${project.path_with_namespace}. Existing optional labels: ${labels.map((label) => label.name).join(", ") || "none"}.`
2142
+ };
2143
+ },
2144
+ async validate(snapshot) {
2145
+ const data = destinationData(snapshot);
2146
+ const client = integration.client(data.profile);
2147
+ if (client.baseUrl !== data.baseUrl) throw new Error("GitLab profile installation changed");
2148
+ const project = await client.getProject(data.projectId);
2149
+ if (!available(project) || project.path_with_namespace !== data.path)
2150
+ throw new Error("The selected GitLab project changed; choose the destination again");
2151
+ }
2152
+ };
2153
+ api.tool({
2154
+ name: "gitlab_create_issue",
2155
+ description: "Create one issue in the selected GitLab project",
2156
+ ...markdownTicketCreationDefinition("GitLab", destinations, "description"),
2157
+ async execute(ctx, args) {
2158
+ if (!ctx.ticketDestination) throw new Error("A GitLab ticket destination is required");
2159
+ await destinations.validate(ctx.ticketDestination);
2160
+ const target = destinationData(ctx.ticketDestination);
2161
+ const client = integration.client(target.profile);
2162
+ const title = stringArg3(args, "title");
2163
+ const description = stringArg3(args, "description");
2164
+ const requestedLabels = ticketLabelNames(args.labels);
2165
+ const names = [.../* @__PURE__ */ new Set([...target.defaultLabels, ...requestedLabels])];
2166
+ if (names.some((name) => name.includes(",")))
2167
+ throw new Error("GitLab label names cannot contain commas");
2168
+ const labels = await client.listLabels(target.projectId, ctx.signal);
2169
+ const unknown = requestedLabels.filter(
2170
+ (name) => !target.defaultLabels.includes(name) && !labels.some((label) => label.name === name)
2171
+ );
2172
+ if (unknown.length) throw new Error(`Unknown GitLab labels: ${unknown.join(", ")}`);
2173
+ for (const name of target.defaultLabels) {
2174
+ await ctx.externalWrites.ensure(
2175
+ { writeType: "gitlab.ensure_label", dedupKey: `${ctx.idempotencyKey}:label:${name}` },
2176
+ {
2177
+ reconcile: async () => (await client.listLabels(target.projectId, ctx.signal)).find(
2178
+ (label) => label.name === name
2179
+ ) ?? null,
2180
+ execute: () => client.createLabel(target.projectId, name, ctx.signal),
2181
+ toMetadata: (label) => ({ name: label.name })
2182
+ }
2183
+ );
2184
+ }
2185
+ const marker = `<!-- leitwerk-ticket-write:${ctx.idempotencyKey} -->`;
2186
+ const issue = await ctx.externalWrites.ensure(
2187
+ { writeType: "gitlab.create_issue", dedupKey: ctx.idempotencyKey },
2188
+ {
2189
+ reconcile: async () => (await client.listIssues(target.projectId, ctx.signal, "all")).find(
2190
+ (issue2) => issue2.description?.includes(marker)
2191
+ ) ?? null,
2192
+ execute: () => client.createIssue(
2193
+ target.projectId,
2194
+ { title, description: `${description}
2195
+
2196
+ ${marker}`, labels: names.join(",") },
2197
+ ctx.signal
2198
+ ),
2199
+ toMetadata: (issue2) => ({
2200
+ projectId: issue2.project_id,
2201
+ iid: issue2.iid,
2202
+ url: issue2.web_url
2203
+ })
2204
+ }
2205
+ );
2206
+ return { externalId: `${target.path}#${issue.iid}`, url: issue.web_url, result: issue };
2207
+ }
2208
+ });
2209
+ }
2210
+
2211
+ // src/setup.ts
2212
+ function setupGitLabIntegration(api, integration, options = {}) {
2213
+ const catalog = integration.repositoryCatalog ?? createGitLabRepositoryCatalog(integration);
2214
+ api.provide(gitlabIntegration, {
2215
+ profiles: () => integration.profiles(),
2216
+ client: (profile) => integration.client(profile),
2217
+ repositoryCatalog: catalog
2218
+ });
2219
+ const settings = api.get(scopedSettingsCapability);
2220
+ if (settings && !Array.isArray(settings))
2221
+ settings.registerDiscovery("repository", async () => {
2222
+ const subjects = [];
2223
+ for (const profile of integration.profiles()) {
2224
+ const client = integration.client(profile);
2225
+ for (const project of await catalog.refresh(profile))
2226
+ subjects.push({
2227
+ scopeType: "repository",
2228
+ identity: repositorySettingsIdentity(client.baseUrl, project.id),
2229
+ label: project.path_with_namespace,
2230
+ aliases: [
2231
+ project.http_url_to_repo,
2232
+ ...project.ssh_url_to_repo ? [project.ssh_url_to_repo] : []
2233
+ ]
2234
+ });
2235
+ }
2236
+ return subjects;
2237
+ });
2238
+ const deps = api.get(coreHostCapabilities.serverSetup);
2239
+ if (!deps || Array.isArray(deps)) return;
2240
+ const maintenance = createGitLabMaintenance(api, deps, integration, options.now);
2241
+ const assertOwnership = async (ctx) => {
2242
+ if (maintenance.ownsProcess(ctx.process.processId))
2243
+ await maintenance.assertOwnership(ctx.process.id, ctx.project?.key ?? "repo", ctx.signal);
2244
+ };
2245
+ const guardedWrites = /* @__PURE__ */ new Set([
2246
+ "gitlab_ensure_merge_request",
2247
+ "gitlab_comment",
2248
+ "gitlab_reply",
2249
+ "gitlab_inline_comment",
2250
+ "gitlab_resolve_discussion",
2251
+ "gitlab_acknowledge_feedback"
2252
+ ]);
2253
+ const guardedApi = {
2254
+ ...api,
2255
+ tool(definition) {
2256
+ api.tool({
2257
+ ...definition,
2258
+ async execute(ctx, args) {
2259
+ const guarded = maintenance.ownsProcess(ctx.process.processId) && guardedWrites.has(definition.name);
2260
+ if (guarded || definition.name === "gitlab_update_comment") await assertOwnership(ctx);
2261
+ const result = await definition.execute(
2262
+ guarded ? {
2263
+ ...ctx,
2264
+ externalWrites: {
2265
+ ...ctx.externalWrites,
2266
+ ensure: (identity, operation) => ctx.externalWrites.ensure(identity, {
2267
+ ...operation,
2268
+ execute: async () => {
2269
+ await assertOwnership(ctx);
2270
+ return operation.execute();
2271
+ }
2272
+ })
2273
+ }
2274
+ } : ctx,
2275
+ args
2276
+ );
2277
+ if (definition.name === "gitlab_ensure_merge_request") await assertOwnership(ctx);
2278
+ return result;
2279
+ }
2280
+ });
2281
+ }
2282
+ };
2283
+ registerGitLabTools(guardedApi, integration, assertOwnership);
2284
+ registerGitLabTicketCreation(
2285
+ api,
2286
+ integration,
2287
+ options.ticketCreation ?? { enabled: false, defaultLabels: [] }
2288
+ );
2289
+ registerGitLabDeliveryTools(guardedApi, integration, deps.projects);
2290
+ api.tool({
2291
+ name: "gitlab_assert_maintenance",
2292
+ description: "Recheck MR maintenance ownership before Git publication",
2293
+ parameters: {
2294
+ type: "object",
2295
+ properties: { projectKey: { type: "string" } },
2296
+ required: ["projectKey"]
2297
+ },
2298
+ async execute(ctx) {
2299
+ await assertOwnership(ctx);
2300
+ return { ok: true };
2301
+ }
2302
+ });
2303
+ return {
2304
+ ...createGitLabProvider(deps, integration, options),
2305
+ /** @internal */
2306
+ maintenance
2307
+ };
2308
+ }
2309
+
2310
+ export {
2311
+ GitLabError,
2312
+ parseGitLabProfiles,
2313
+ GitLabClient,
2314
+ observeMergeRequest,
2315
+ gitlabIntegration,
2316
+ gitlabRepositoryCredentials,
2317
+ resolveGitLabRepositoryBinding,
2318
+ resolveGitLabBinding,
2319
+ gitLabCommentMarker,
2320
+ ensureGitLabComment,
2321
+ ensureGitLabSeenReaction,
2322
+ parseGitLabSelection,
2323
+ selectGitLabProjects,
2324
+ gitlabIssueExternalId,
2325
+ gitlabIssueWatcherSource,
2326
+ GITLAB_MR_KIND,
2327
+ pendingGitLabFeedback,
2328
+ gitLabFeedbackReadyAt,
2329
+ observationKey,
2330
+ gitlabExternal,
2331
+ GITLAB_ACTIVE_LABEL,
2332
+ GITLAB_DONE_LABEL,
2333
+ readGitLabLabels,
2334
+ gitLabActivationStatus,
2335
+ GITLAB_MAINTAINED_KIND,
2336
+ gitlabMaintenanceSource,
2337
+ gitlabMaintenance,
2338
+ registerGitLabMaintainedProcess,
2339
+ createGitLabMaintenance,
2340
+ createGitLabRepositoryCatalog,
2341
+ setupGitLabIntegration
2342
+ };
2343
+ //# sourceMappingURL=chunk-YPCOVBQS.js.map