@leitwerk-dev/jira-gitlab-change 0.0.0-bootstrap.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.
package/dist/index.js ADDED
@@ -0,0 +1,819 @@
1
+ // src/index.ts
2
+ import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
3
+ import {
4
+ createRepositoryChangePublication,
5
+ readPublicationState
6
+ } from "@leitwerk-dev/coding/repository-change-publication";
7
+ import { asUnknownRecord as asUnknownRecord3 } from "@leitwerk-dev/domain";
8
+ import { gitSshIntegration } from "@leitwerk-dev/git-ssh";
9
+ import {
10
+ createGitLabPublicationAdapter,
11
+ gitlabIntegration,
12
+ gitlabPublicationRequest,
13
+ gitlabRepositoryCredentials
14
+ } from "@leitwerk-dev/gitlab";
15
+ import {
16
+ jiraEligible as jiraEligible2,
17
+ jiraIntegration,
18
+ jiraIssuePolicy,
19
+ jiraIssueWatcherSource,
20
+ jiraWikiSource
21
+ } from "@leitwerk-dev/jira";
22
+ import {
23
+ coreHostCapabilities,
24
+ scopedSettingsCapability
25
+ } from "@leitwerk-dev/process-sdk";
26
+ import { wikiInstructions } from "@leitwerk-dev/wiki";
27
+ import { topicWikiCapability } from "@leitwerk-dev/wiki/integration";
28
+
29
+ // src/launch.ts
30
+ import { createHash } from "crypto";
31
+ import { isDeepStrictEqual } from "util";
32
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
33
+ import { createGitSshPreparationCheck } from "@leitwerk-dev/git-ssh";
34
+ import {
35
+ createGitLabRepositoryCatalog,
36
+ GitLabError,
37
+ resolveGitLabLaunchProject
38
+ } from "@leitwerk-dev/gitlab";
39
+ import {
40
+ ensureIssueWiki,
41
+ JiraRequestError,
42
+ jiraEligible,
43
+ jiraIsEpic,
44
+ jiraIssueExternalId,
45
+ jiraSplitChildMatches,
46
+ jiraSubjectIdentity,
47
+ jiraToMarkdown,
48
+ jiraTriggerLabel
49
+ } from "@leitwerk-dev/jira";
50
+ import {
51
+ RetryableWaitError,
52
+ repositorySettingsIdentity,
53
+ SafeLaunchPreparationError
54
+ } from "@leitwerk-dev/process-sdk";
55
+
56
+ // src/models.ts
57
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
58
+ function parseJiraModelLabels(config) {
59
+ const raw = asUnknownRecord(config)?.model_labels;
60
+ if (raw === void 0) return {};
61
+ const labels = asUnknownRecord(raw);
62
+ if (!labels) throw new Error("Jira model_labels must map labels to model profile IDs");
63
+ const result = {};
64
+ for (const [label, profile] of Object.entries(labels)) {
65
+ if (!/^leitwerk-model-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(label) || typeof profile !== "string" || !profile.trim())
66
+ throw new Error("Jira model_labels requires leitwerk-model-* labels and model profile IDs");
67
+ result[label] = profile.trim();
68
+ }
69
+ return result;
70
+ }
71
+ function selectJiraModel(labels, profiles) {
72
+ const selected = [...new Set(labels.filter((label2) => label2.startsWith("leitwerk-model-")))];
73
+ if (selected.length > 1)
74
+ throw new Error("Select only one leitwerk-model-* label before starting the change");
75
+ const label = selected[0];
76
+ if (!label) return void 0;
77
+ const profileId = profiles[label];
78
+ if (!profileId) throw new Error(`Unknown Jira model label ${label}; correct the label and retry`);
79
+ return { label, profileId };
80
+ }
81
+
82
+ // src/launch.ts
83
+ var JiraSourceIneligibleError = class extends Error {
84
+ constructor() {
85
+ super("Jira source issue is no longer eligible");
86
+ }
87
+ };
88
+ function eligibleSource(issue, event) {
89
+ return issue.id === event.issue.id && jiraEligible(issue, event.triggerLabel) && event.projects.includes(issue.fields.project.id);
90
+ }
91
+ function jiraChangePrompt(issue) {
92
+ return `${issue.key}: ${issue.fields.summary}
93
+
94
+ ${jiraToMarkdown(issue.fields.description)}`;
95
+ }
96
+ function admissionParams(params) {
97
+ const { id, key, fields } = params.issue;
98
+ return {
99
+ ...params,
100
+ issue: {
101
+ id,
102
+ key,
103
+ fields: {
104
+ updated: fields.updated,
105
+ summary: fields.summary,
106
+ description: fields.description,
107
+ labels: [...fields.labels].sort(),
108
+ project: { id: fields.project.id, key: fields.project.key, name: fields.project.name },
109
+ components: fields.components.map(({ id: id2, name }) => ({ id: id2, name })),
110
+ statusCategory: fields.status.statusCategory.key,
111
+ issuetype: fields.issuetype && {
112
+ id: fields.issuetype.id,
113
+ name: fields.issuetype.name,
114
+ subtask: fields.issuetype.subtask
115
+ },
116
+ parent: fields.parent && { id: fields.parent.id, key: fields.parent.key }
117
+ }
118
+ }
119
+ };
120
+ }
121
+ function decodeJiraGitLabRepositoryMapping(value) {
122
+ if (typeof value !== "string") throw new Error("Select a repository and its GitLab profile");
123
+ let r;
124
+ try {
125
+ r = asUnknownRecord2(JSON.parse(value));
126
+ } catch {
127
+ throw new Error("Invalid repository mapping; reselect it in Settings");
128
+ }
129
+ return validateMapping(r);
130
+ }
131
+ function validateMapping(r) {
132
+ if (!r || typeof r.origin !== "string" || new URL(r.origin).origin !== r.origin || typeof r.projectId !== "number" || !Number.isSafeInteger(r.projectId) || r.projectId <= 0 || typeof r.gitlabProfile !== "string" || !r.gitlabProfile || r.sshProfile !== void 0 && (typeof r.sshProfile !== "string" || !r.sshProfile))
133
+ throw new Error("Invalid repository mapping; reselect it in Settings");
134
+ return r;
135
+ }
136
+ var jiraGitLabParamsCodec = {
137
+ parse(value) {
138
+ const r = asUnknownRecord2(value);
139
+ jiraTriggerLabel(r?.jiraTriggerLabel);
140
+ if (r?.origin !== "jira" || !Array.isArray(r.repositories) || !r.repositories.length && !asUnknownRecord2(r.startup) || !Array.isArray(r.mappings) || !asUnknownRecord2(r.issue))
141
+ throw new Error("Invalid Jira GitLab launch snapshot");
142
+ for (const key of ["jiraProfile", "jiraBaseUrl", "issueId", "issueKey", "issueUrl", "prompt"])
143
+ if (typeof r[key] !== "string" || !r[key]) throw new Error(`Missing ${key}`);
144
+ if (r.startup !== void 0) {
145
+ const startup = asUnknownRecord2(r.startup);
146
+ if (r.repositories.length || !Array.isArray(startup?.projectIds) || !startup.projectIds.length || startup.projectIds.some((id) => typeof id !== "string" || !id) || [
147
+ "owner",
148
+ "repo",
149
+ "gitlabProfile",
150
+ "projectId",
151
+ "repoLocator",
152
+ "baseBranch",
153
+ "workBranch"
154
+ ].some((key) => r[key] !== void 0))
155
+ throw new Error("Invalid pending Jira repository binding");
156
+ }
157
+ for (const item of r.repositories) {
158
+ const repo = asUnknownRecord2(item);
159
+ if (!repo || typeof repo.key !== "string" || !/^[a-zA-Z0-9_-]+$/.test(repo.key))
160
+ throw new Error("Invalid repository key");
161
+ validateMapping({ ...repo, origin: repo.gitlabOrigin });
162
+ for (const key of ["repoLocator", "owner", "repo", "baseBranch", "workBranch"])
163
+ if (typeof repo[key] !== "string" || !repo[key])
164
+ throw new Error(`Missing repository ${key}`);
165
+ }
166
+ if (new Set(r.repositories.map((repo) => repo.key)).size !== r.repositories.length)
167
+ throw new Error("Duplicate repository key");
168
+ return r;
169
+ },
170
+ serialize: (value) => value
171
+ };
172
+ var jiraGitLabRepositories = {
173
+ key: "jira-gitlab-change.repositories",
174
+ schemaVersion: 1,
175
+ scopes: ["jira.component"],
176
+ merge: "replace",
177
+ defaultValue: [],
178
+ form: {
179
+ label: "GitLab repositories",
180
+ group: "Repository mapping",
181
+ control: "multiselect",
182
+ overview: "repository-mapping",
183
+ search: { minimumLength: 2, placeholder: "Search GitLab repositories" },
184
+ description: "Use the GitLab profile's token over HTTPS, or select a configured SSH profile."
185
+ },
186
+ schema: {
187
+ parse(value) {
188
+ if (!Array.isArray(value)) throw new Error("Choose repositories");
189
+ for (const entry of value) decodeJiraGitLabRepositoryMapping(entry);
190
+ return [...new Set(value)];
191
+ }
192
+ }
193
+ };
194
+ function createJiraGitLabLauncher() {
195
+ let services = null;
196
+ let repositoryCatalog = null;
197
+ const requireServices = () => {
198
+ if (!services) throw new Error("Jira GitLab integration is not configured");
199
+ return services;
200
+ };
201
+ const mapping = {
202
+ ...jiraGitLabRepositories,
203
+ choiceLabel(value) {
204
+ const mapping2 = decodeJiraGitLabRepositoryMapping(value);
205
+ const { gitlab, settings } = requireServices();
206
+ const retained = settings.findSubject(
207
+ "repository",
208
+ repositorySettingsIdentity(mapping2.origin, mapping2.projectId)
209
+ );
210
+ let path = retained?.label;
211
+ if (!path) {
212
+ const known = gitlab.profiles().includes(mapping2.gitlabProfile) ? repositoryCatalog?.peek(mapping2.gitlabProfile, mapping2.projectId) : void 0;
213
+ path = known && gitlab.client(mapping2.gitlabProfile).baseUrl === mapping2.origin ? known.path_with_namespace : `Repository ${mapping2.projectId}`;
214
+ }
215
+ return `${path} \xB7 ${mapping2.gitlabProfile} / ${mapping2.sshProfile ?? "HTTPS"}`;
216
+ },
217
+ async choices(_context, request = {}) {
218
+ const { gitlab, ssh, settings } = requireServices();
219
+ if (!repositoryCatalog) throw new Error("GitLab repository catalog is not configured");
220
+ const query = (request.search ?? "").trim();
221
+ if (query.length < 2) return [];
222
+ const choices = [];
223
+ for (const gitlabProfile of gitlab.profiles()) {
224
+ const client = gitlab.client(gitlabProfile);
225
+ const projects = [...await repositoryCatalog.search(gitlabProfile, query)];
226
+ for (const value of request.values ?? []) {
227
+ const selected = decodeJiraGitLabRepositoryMapping(value);
228
+ if (selected.gitlabProfile !== gitlabProfile || selected.origin !== client.baseUrl || projects.some((repo) => repo.id === selected.projectId))
229
+ continue;
230
+ const project = repositoryCatalog.peek(gitlabProfile, selected.projectId);
231
+ if (project) projects.push(project);
232
+ }
233
+ for (const repo of projects) {
234
+ if (repo.archived || !repo.default_branch) continue;
235
+ settings.discover({
236
+ scopeType: "repository",
237
+ identity: repositorySettingsIdentity(client.baseUrl, repo.id),
238
+ label: repo.path_with_namespace
239
+ });
240
+ if (repo.http_url_to_repo)
241
+ choices.push({
242
+ value: JSON.stringify({ origin: client.baseUrl, projectId: repo.id, gitlabProfile }),
243
+ label: `${repo.path_with_namespace} \xB7 ${gitlabProfile} / HTTPS`
244
+ });
245
+ if (!repo.ssh_url_to_repo) continue;
246
+ for (const sshProfile of ssh?.profiles() ?? [])
247
+ choices.push({
248
+ value: JSON.stringify({
249
+ origin: client.baseUrl,
250
+ projectId: repo.id,
251
+ gitlabProfile,
252
+ sshProfile
253
+ }),
254
+ label: `${repo.path_with_namespace} \xB7 ${gitlabProfile} / ${sshProfile}`
255
+ });
256
+ }
257
+ }
258
+ for (const value of request.values ?? [])
259
+ if (!choices.some((choice) => choice.value === value))
260
+ choices.push({ value, label: mapping.choiceLabel?.(value) ?? value });
261
+ return choices;
262
+ }
263
+ };
264
+ async function resolve(event, ctx = {}, retained, signal) {
265
+ const { jira, gitlab, ssh, settings, wiki, publications } = requireServices();
266
+ const client = jira.client(event.profile);
267
+ const issue = await client.getIssue(event.issue.id, signal);
268
+ if (!eligibleSource(issue, event)) throw new JiraSourceIneligibleError();
269
+ const triggerLabel = jiraTriggerLabel(event.triggerLabel);
270
+ const modelSelection = retained ? retained.modelSelection : selectJiraModel(issue.fields.labels, requireServices().modelLabels ?? {});
271
+ if (modelSelection && ctx.modelProfiles && !ctx.modelProfiles.some((p) => p.id === modelSelection.profileId))
272
+ throw new Error(
273
+ `Jira model profile ${modelSelection.profileId} is unavailable for this process`
274
+ );
275
+ const project = settings.discover({
276
+ scopeType: "jira.project",
277
+ identity: jiraSubjectIdentity(client.baseUrl, issue.fields.project.id),
278
+ label: issue.fields.project.key
279
+ });
280
+ const source = {
281
+ origin: "jira",
282
+ jiraTriggerLabel: triggerLabel,
283
+ ...modelSelection ? { modelSelection } : {},
284
+ jiraProfile: event.profile,
285
+ jiraBaseUrl: client.baseUrl,
286
+ issueId: issue.id,
287
+ issueKey: issue.key,
288
+ issueUrl: `${client.baseUrl}/browse/${encodeURIComponent(issue.key)}`,
289
+ prompt: jiraChangePrompt(issue),
290
+ issue
291
+ };
292
+ const launch = {
293
+ processId: "jira_gitlab_change_process",
294
+ defaultModelProfileId: modelSelection?.profileId,
295
+ title: `${issue.key}: ${issue.fields.summary}`,
296
+ startTurnId: "generate_plan",
297
+ externalId: jiraIssueExternalId(client.baseUrl, issue.id),
298
+ externalUrl: source.issueUrl,
299
+ settingsContext: { "jira.project": project.id }
300
+ };
301
+ const mappings = [];
302
+ const selected = /* @__PURE__ */ new Map();
303
+ const publication = publications?.publicationByExternalId(
304
+ jiraIssueExternalId(client.baseUrl, issue.id)
305
+ );
306
+ const componentPublication = publication && typeof publication.binding.componentId === "string";
307
+ if (componentPublication && (issue.fields.components.length !== 1 || issue.fields.components[0].id !== publication.binding.componentId))
308
+ throw new Error("Generated ticket's component identity changed");
309
+ for (const component of issue.fields.components) {
310
+ const subject = settings.discover({
311
+ scopeType: "jira.component",
312
+ identity: jiraSubjectIdentity(client.baseUrl, component.id),
313
+ label: `${issue.fields.project.key} / ${component.name}`,
314
+ context: { "jira.project": project.id }
315
+ });
316
+ const resolved = settings.resolve(mapping, {
317
+ "jira.project": project.id,
318
+ "jira.component": subject.id
319
+ });
320
+ mappings.push({
321
+ componentId: component.id,
322
+ values: resolved.value,
323
+ sources: resolved.sources
324
+ });
325
+ }
326
+ if (!mappings.length || mappings.some((mapping2) => !mapping2.values.length)) {
327
+ return {
328
+ ...launch,
329
+ projects: [],
330
+ params: {
331
+ ...source,
332
+ mappings,
333
+ repositories: [],
334
+ startup: { projectIds: [...event.projects] }
335
+ }
336
+ };
337
+ }
338
+ for (const mapping2 of mappings) {
339
+ for (const value of mapping2.values) {
340
+ const entry = decodeJiraGitLabRepositoryMapping(value);
341
+ if (publication && !componentPublication && (entry.origin !== publication.binding.origin || entry.projectId !== publication.binding.projectId))
342
+ continue;
343
+ const key = repositorySettingsIdentity(entry.origin, entry.projectId);
344
+ const prior = selected.get(key);
345
+ if (prior && (prior.gitlabProfile !== entry.gitlabProfile || prior.sshProfile !== entry.sshProfile))
346
+ throw new Error(
347
+ `Conflicting profiles for project ${entry.projectId}; correct the component mappings in Settings`
348
+ );
349
+ selected.set(key, entry);
350
+ }
351
+ }
352
+ if (publication && !componentPublication) {
353
+ const binding = publication.binding;
354
+ const exact = [...selected.entries()].find(
355
+ ([, entry]) => entry.origin === binding.origin && entry.projectId === binding.projectId && entry.gitlabProfile === binding.gitlabProfile && (binding.sshProfile === void 0 || entry.sshProfile === binding.sshProfile)
356
+ );
357
+ if (!exact)
358
+ throw new Error(
359
+ "Generated ticket's repository binding no longer matches its component mappings"
360
+ );
361
+ selected.clear();
362
+ selected.set(...exact);
363
+ }
364
+ if (!selected.size)
365
+ throw new Error(
366
+ `No repositories mapped for ${issue.key}. Map at least one component in Settings \u2192 Jira components.`
367
+ );
368
+ const repositories = [];
369
+ const projects = [];
370
+ for (const entry of selected.values()) {
371
+ const provider = gitlab.client(entry.gitlabProfile);
372
+ if (provider.baseUrl !== entry.origin || entry.sshProfile !== void 0 && !ssh?.profiles().includes(entry.sshProfile))
373
+ throw new Error(
374
+ `Unavailable mapping for GitLab project ${entry.projectId}; update its profiles in Settings`
375
+ );
376
+ const repo = await provider.getProject(entry.projectId, signal);
377
+ if (repo.id !== entry.projectId) throw new Error("GitLab repository identity changed");
378
+ const repoLocator = entry.sshProfile ? repo.ssh_url_to_repo : repo.http_url_to_repo;
379
+ if (repo.archived || !repo.default_branch || !repoLocator)
380
+ throw new Error(
381
+ `GitLab project ${entry.projectId} must be active and provide the selected clone URL`
382
+ );
383
+ if (publication && !componentPublication && (publication.binding.repoLocator !== void 0 && repoLocator !== publication.binding.repoLocator || publication.binding.repository !== void 0 && repo.path_with_namespace !== publication.binding.repository || repo.default_branch !== publication.binding.baseBranch))
384
+ throw new Error("Generated ticket's repository checkout binding changed");
385
+ const key = `repo_${repositories.length + 1}`;
386
+ const { params: binding, project: project2 } = await resolveGitLabLaunchProject(
387
+ provider,
388
+ entry.gitlabProfile,
389
+ { ...repo, id: entry.projectId },
390
+ `leitwerk/jira-${createHash("sha256").update(client.baseUrl).digest("hex").slice(0, 10)}-${issue.id}`,
391
+ key,
392
+ entry.sshProfile ? "ssh" : "https"
393
+ );
394
+ if (publication?.binding.workBranch !== void 0 && publication.binding.workBranch !== binding.workBranch)
395
+ throw new Error("Generated ticket's repository work branch binding changed");
396
+ repositories.push({ ...binding, key, origin: "jira", sshProfile: entry.sshProfile });
397
+ projects.push({
398
+ ...project2,
399
+ metadata: {
400
+ ...project2.metadata,
401
+ jira: {
402
+ profile: event.profile,
403
+ baseUrl: client.baseUrl,
404
+ issueId: issue.id,
405
+ triggerLabel
406
+ }
407
+ }
408
+ });
409
+ }
410
+ const first = repositories[0];
411
+ let sourceIssue = null;
412
+ if (publication) {
413
+ const sourceIssueId = publication.binding.sourceIssueId ?? publication.binding.epicId;
414
+ const relationship = publication.binding.relationship ?? "epic";
415
+ if (typeof sourceIssueId !== "string" || relationship !== "epic" && relationship !== "subtask" || !await jiraSplitChildMatches(client, issue, sourceIssueId, relationship))
416
+ throw new Error("Generated ticket's source issue binding changed");
417
+ sourceIssue = await client.getIssue(sourceIssueId);
418
+ if (sourceIssue.id !== sourceIssueId || sourceIssue.fields.project.id !== issue.fields.project.id || sourceIssue.fields.issuetype?.subtask === true || jiraIsEpic(sourceIssue) !== (relationship === "epic"))
419
+ throw new Error("Generated ticket's source issue binding changed");
420
+ } else if (wiki && issue.fields.issuetype?.subtask === true) {
421
+ if (!issue.fields.parent?.id) throw new Error("Jira subtask parent is unavailable");
422
+ sourceIssue = await client.getIssue(issue.fields.parent.id);
423
+ } else if (wiki && client.getEpic) {
424
+ sourceIssue = await client.getEpic(issue);
425
+ }
426
+ const topic = wiki && sourceIssue ? ensureIssueWiki(wiki, client, sourceIssue, publication?.topicId) : null;
427
+ if (publication && topic?.id !== publication.topicId)
428
+ throw new Error("Generated ticket's source issue wiki binding changed");
429
+ const params = {
430
+ ...topic ? { wikiTopicId: topic.id } : {},
431
+ ...first,
432
+ ...source,
433
+ mappings,
434
+ repositories
435
+ };
436
+ return {
437
+ ...launch,
438
+ ...topic && sourceIssue ? {
439
+ metadata: {
440
+ wiki: {
441
+ topicId: topic.id,
442
+ profile: event.profile,
443
+ baseUrl: client.baseUrl,
444
+ issueId: sourceIssue.id
445
+ }
446
+ }
447
+ } : {},
448
+ params,
449
+ projects
450
+ };
451
+ }
452
+ const checks = (event, launch, retained) => [
453
+ ...launch.params.repositories.map((repo) => ({
454
+ id: `${repo.sshProfile ? "ssh" : "https"}_${repo.key}`,
455
+ label: `Verify ${repo.owner}/${repo.repo} ${repo.sshProfile ? "SSH" : "HTTPS"} read/write access`,
456
+ async run(ctx) {
457
+ const { gitlab, ssh } = requireServices();
458
+ const client = gitlab.client(repo.gitlabProfile);
459
+ const fresh = await client.getProject(repo.projectId, ctx.signal);
460
+ if (client.baseUrl !== repo.gitlabOrigin || fresh.id !== repo.projectId || fresh.archived || (repo.sshProfile ? fresh.ssh_url_to_repo : fresh.http_url_to_repo) !== repo.repoLocator || fresh.default_branch !== repo.baseBranch)
461
+ throw new SafeLaunchPreparationError(
462
+ "Repository changed",
463
+ "Refresh the component mapping and retry launch."
464
+ );
465
+ if (!repo.sshProfile) {
466
+ await client.preflightRepository(
467
+ repo.projectId,
468
+ repo.baseBranch,
469
+ repo.workBranch,
470
+ ctx.signal
471
+ );
472
+ return;
473
+ }
474
+ if (!ssh) throw new Error("Git SSH profile is unavailable");
475
+ await createGitSshPreparationCheck(
476
+ "write",
477
+ { ...repo, sshCredentialRef: repo.sshProfile },
478
+ () => ssh
479
+ ).run(ctx);
480
+ }
481
+ })),
482
+ {
483
+ id: "jira_eligibility",
484
+ label: "Recheck Jira issue and component mappings",
485
+ async run({ signal }) {
486
+ if (launch.params.startup) {
487
+ const issue = await requireServices().jira.client(event.profile).getIssue(event.issue.id, signal);
488
+ if (!eligibleSource(issue, event))
489
+ throw new SafeLaunchPreparationError(
490
+ "Jira source issue is no longer eligible",
491
+ "Restore the watcher label and project eligibility before launching."
492
+ );
493
+ return;
494
+ }
495
+ const fresh = await resolve(event, {}, retained, signal);
496
+ if (!isDeepStrictEqual(admissionParams(fresh.params), admissionParams(launch.params)))
497
+ throw new SafeLaunchPreparationError(
498
+ "Jira issue or mappings changed before admission",
499
+ "Retry launch to capture the latest issue and mappings."
500
+ );
501
+ }
502
+ }
503
+ ];
504
+ async function ready(context) {
505
+ const { params, signal } = context;
506
+ if (!params.startup) return true;
507
+ try {
508
+ const client = requireServices().jira.client(params.jiraProfile);
509
+ if (client.baseUrl !== params.jiraBaseUrl) throw new Error("Jira installation changed");
510
+ const issue = await client.getIssue(params.issueId, signal);
511
+ if (issue.id !== params.issueId) throw new Error("Jira issue identity changed");
512
+ const event = {
513
+ profile: params.jiraProfile,
514
+ triggerLabel: params.jiraTriggerLabel,
515
+ projects: params.startup.projectIds,
516
+ issue
517
+ };
518
+ if (!eligibleSource(issue, event))
519
+ return context.abort("Jira source is no longer eligible; startup cancelled");
520
+ const launch = await resolve(event, {}, params, signal);
521
+ if (launch.params.startup) {
522
+ const missing = launch.params.issue.fields.components.filter(
523
+ (component) => !launch.params.mappings.find((mapping2) => mapping2.componentId === component.id)?.values.length
524
+ );
525
+ const reason = missing.length ? `no GitLab repository mapping for ${missing.map((component) => component.name).join(", ")}. Configure GitLab repositories in Settings \u2192 Jira components.` : "no Jira components. Assign at least one component to the issue and configure its GitLab repositories in Settings \u2192 Jira components.";
526
+ return context.waiting(
527
+ `Startup blocked: ${launch.params.issueKey} has ${reason} Startup will resume automatically.`
528
+ );
529
+ }
530
+ for (const check of checks(event, launch, params)) {
531
+ signal.throwIfAborted();
532
+ await check.run({ signal, launchConfig: launch, logger: { info() {
533
+ }, warn() {
534
+ } } });
535
+ }
536
+ return context.bindInitialProjects({
537
+ params: launch.params,
538
+ projects: launch.projects ?? [],
539
+ metadata: launch.metadata,
540
+ settingsContext: launch.settingsContext
541
+ });
542
+ } catch (error) {
543
+ if (error instanceof JiraSourceIneligibleError)
544
+ return context.abort("Jira source is no longer eligible; startup cancelled");
545
+ if (error instanceof GitLabError && error.retryable || error instanceof JiraRequestError && (error.status === 408 || error.status === 429 || error.status >= 500) || error instanceof TypeError && /fetch|network/i.test(error.message))
546
+ throw new RetryableWaitError(
547
+ "Jira or GitLab is temporarily unavailable; startup will be checked again."
548
+ );
549
+ if (error instanceof SafeLaunchPreparationError && error.message.includes("changed before admission"))
550
+ return context.waiting(
551
+ "Jira issue or mappings changed during startup checks. Checking the latest configuration again."
552
+ );
553
+ if (error instanceof SafeLaunchPreparationError)
554
+ throw new Error(`${error.message}. ${error.safeSummary}`);
555
+ throw error;
556
+ }
557
+ }
558
+ return {
559
+ /** @internal */
560
+ ready,
561
+ /** @internal */
562
+ mapping,
563
+ /** @internal */
564
+ resolve,
565
+ /** @internal */
566
+ checks,
567
+ /** @internal */
568
+ configure(value) {
569
+ if (value?.gitlab !== services?.gitlab)
570
+ repositoryCatalog = value ? value.gitlab.repositoryCatalog ?? createGitLabRepositoryCatalog(value.gitlab) : null;
571
+ services = value;
572
+ },
573
+ /** @internal */
574
+ async readIssue(params) {
575
+ const client = requireServices().jira.client(params.jiraProfile);
576
+ if (client.baseUrl !== params.jiraBaseUrl) throw new Error("Jira installation changed");
577
+ return client.getIssue(params.issueId);
578
+ }
579
+ };
580
+ }
581
+
582
+ // src/index.ts
583
+ var namespace = "jiraGitLabChange";
584
+ var remote = (state, key) => readPublicationState(state, `${namespace}:${key}`);
585
+ function createJiraGitLabChange(options) {
586
+ let verificationOnMerge = options.verificationOnMerge ?? false;
587
+ const launcher = createJiraGitLabLauncher();
588
+ const adapter = createGitLabPublicationAdapter([], namespace);
589
+ adapter.ensureRequest = async (ctx) => {
590
+ const { url } = await ctx.callIntegrationTool("jira_ensure_remote_link", {
591
+ projectKey: "repo",
592
+ kind: "process"
593
+ });
594
+ const mr = await ctx.callIntegrationTool("gitlab_ensure_merge_request", {
595
+ projectKey: "repo",
596
+ title: `${ctx.params.issueKey}: ${ctx.params.issue.fields.summary}`,
597
+ body: `Implements [${ctx.params.issueKey}](${ctx.params.issueUrl})
598
+
599
+ [Leitwerk process](${url})`
600
+ });
601
+ return gitlabPublicationRequest(mr);
602
+ };
603
+ adapter.repositories = (params) => params.repositories.map((repo) => ({
604
+ key: repo.key,
605
+ params: { ...params, ...repo, issueUrl: params.issueUrl }
606
+ }));
607
+ adapter.tools.delivery = [
608
+ ...adapter.tools.delivery,
609
+ "jira_get_source_issue",
610
+ "jira_ensure_remote_link",
611
+ "jira_transition_source_issue",
612
+ "jira_finalize_source_issue"
613
+ ];
614
+ adapter.sourceCancelled = async (ctx) => !jiraEligible2(
615
+ await ctx.callIntegrationTool("jira_get_source_issue", {
616
+ projectKey: ctx.params.repositories[0].key
617
+ }),
618
+ ctx.params.jiraTriggerLabel
619
+ );
620
+ adapter.linkIssue = async (ctx) => {
621
+ await ctx.callIntegrationTool("jira_ensure_remote_link", {
622
+ projectKey: "repo",
623
+ kind: "merge_request"
624
+ });
625
+ };
626
+ adapter.reconcileTerminal = async () => {
627
+ };
628
+ adapter.reconcileAll = async (ctx, results, cancelled) => {
629
+ const created = results.filter(({ current }) => !current.noChanges);
630
+ const merged = created.filter(({ current }) => current.delivery.terminalPullRequest?.merged);
631
+ const done = !cancelled && created.length > 0 && merged.length === created.length;
632
+ const projectKey = ctx.params.repositories[0].key;
633
+ if (done && verificationOnMerge)
634
+ await ctx.callIntegrationTool("jira_transition_source_issue", {
635
+ projectKey,
636
+ targetStatus: "In Verification"
637
+ });
638
+ if (!cancelled)
639
+ await ctx.callIntegrationTool("jira_finalize_source_issue", {
640
+ projectKey,
641
+ done,
642
+ writeKey: "delivery-labels"
643
+ });
644
+ };
645
+ const publication = createRepositoryChangePublication(adapter);
646
+ publication.fragment.watcher({
647
+ id: "use_leitwerk",
648
+ label: "Jira use-leitwerk issues",
649
+ description: "Coordinate changes across component-mapped GitLab repositories",
650
+ source: jiraIssueWatcherSource,
651
+ resolveLaunchConfig: launcher.resolve,
652
+ preparationChecks: launcher.checks
653
+ });
654
+ const { process } = createRepositoryChangeProcess({
655
+ processId: "jira_gitlab_change_process",
656
+ displayName: "Jira GitLab Change",
657
+ paramsCodec: jiraGitLabParamsCodec,
658
+ publication,
659
+ workflow: {
660
+ multiRepository: true,
661
+ async planDecision(params) {
662
+ const issue = await launcher.readIssue(params);
663
+ return {
664
+ skip: jiraEligible2(issue, params.jiraTriggerLabel) && issue.fields.labels.includes("leitwerk-skip-plan-decision"),
665
+ reason: "Jira label"
666
+ };
667
+ },
668
+ async simplification(params) {
669
+ const issue = await launcher.readIssue(params);
670
+ return {
671
+ skip: issue.fields.labels.includes("leitwerk-skip-simplification"),
672
+ reason: "Jira source labels"
673
+ };
674
+ },
675
+ planBypassSource: jiraIssuePolicy(({ params, state }) => ({
676
+ profile: params.jiraProfile,
677
+ baseUrl: params.jiraBaseUrl,
678
+ issueId: params.issueId,
679
+ triggerLabel: params.jiraTriggerLabel,
680
+ planRevision: state.routing?.plan?.planRevision,
681
+ mode: "plan_bypass"
682
+ }))
683
+ },
684
+ repositoryCredentials: ({ params }) => params.repositories.flatMap(
685
+ (repo) => repo.sshProfile ? [{ projectKey: repo.key, kind: "git_ssh", credentialRef: repo.sshProfile }] : gitlabRepositoryCredentials(repo.gitlabProfile, [repo])
686
+ )
687
+ });
688
+ process.runtime = { ...process.runtime, developmentTools: true, docker: options.docker };
689
+ const plan = process.turns.get("generate_plan")?.definition;
690
+ const delivery = process.turns.get("deliver_change")?.definition;
691
+ if (plan?.kind !== "llm" || delivery?.kind !== "automatic")
692
+ throw new Error("Jira change requires planning and delivery turns");
693
+ plan.waitFor = launcher.ready;
694
+ plan.resolveAskQuestions = ({ prepared }) => asUnknownRecord3(prepared)?.skipPlanDecision !== true;
695
+ plan.integrationTools = [
696
+ ...plan.integrationTools ?? [],
697
+ "jira_get_source_issue",
698
+ "jira_ensure_remote_link",
699
+ "jira_transition_source_issue"
700
+ ];
701
+ const originalPrepare = plan.prepare;
702
+ plan.prepare = async (ctx) => {
703
+ const projectKey = ctx.params.repositories[0].key;
704
+ const issue = await ctx.callIntegrationTool("jira_get_source_issue", { projectKey }).catch(() => null);
705
+ await ctx.callIntegrationTool("jira_ensure_remote_link", { projectKey, kind: "process" });
706
+ await ctx.callIntegrationTool("jira_transition_source_issue", {
707
+ projectKey,
708
+ targetStatus: "In Progress"
709
+ });
710
+ return {
711
+ ...asUnknownRecord3(await originalPrepare?.(ctx)) ?? {},
712
+ skipPlanDecision: issue?.fields.labels.includes("leitwerk-skip-plan-decision") ?? false
713
+ };
714
+ };
715
+ const originalDelivery = delivery.run;
716
+ delivery.run = async (ctx) => {
717
+ const result = await originalDelivery(ctx);
718
+ if (result.outcome === "aborted") return result;
719
+ const state = process.stateCodec.parse(result.params?.nextState);
720
+ const published = ctx.params.repositories.map((repo) => remote(state, repo.key));
721
+ if (published.some((current) => current.prNumber)) {
722
+ if (!ctx.callIntegrationTool) throw new Error("Jira integration tools are unavailable");
723
+ await ctx.callIntegrationTool("jira_ensure_remote_link", {
724
+ projectKey: ctx.params.repositories[0].key,
725
+ kind: "process"
726
+ });
727
+ for (const [index, current] of published.entries())
728
+ if (current.prNumber && current.prUrl)
729
+ await ctx.callIntegrationTool("jira_ensure_remote_link", {
730
+ projectKey: ctx.params.repositories[index].key,
731
+ kind: "merge_request"
732
+ });
733
+ if (published.every((current) => current.noChanges || current.prNumber && current.prUrl))
734
+ await ctx.callIntegrationTool("jira_transition_source_issue", {
735
+ projectKey: ctx.params.repositories[0].key,
736
+ targetStatus: "In Review"
737
+ });
738
+ }
739
+ return result;
740
+ };
741
+ for (const binding of process.turns.values()) {
742
+ const turn = binding.definition;
743
+ if (turn.kind !== "llm") continue;
744
+ const originalPrompt = turn.prompt;
745
+ const originalTools = turn.resolveIntegrationTools;
746
+ turn.resolveIntegrationTools = (params, state) => [
747
+ ...originalTools?.(params, state) ?? turn.integrationTools ?? [],
748
+ "jira_get_source_issue",
749
+ "jira_get_issue",
750
+ ...params.wikiTopicId ? ["wiki_index", "wiki_read", "wiki_share", "wiki_edit", "wiki_delete", "wiki_delete_group"] : []
751
+ ];
752
+ turn.prompt = async (ctx) => `${await originalPrompt({ ...ctx, params: { ...ctx.params, prompt: jiraChangePrompt(ctx.params.issue) } })}${ctx.params.wikiTopicId ? `
753
+
754
+ ${wikiInstructions}
755
+ Wiki: /wiki/${ctx.params.wikiTopicId}` : ""}`;
756
+ }
757
+ const extension = {
758
+ manifest: {
759
+ id: "jira-gitlab-change",
760
+ version: "0.3.0",
761
+ requires: ["jira", "gitlab", "coding"]
762
+ },
763
+ scopedSettings: { settings: [launcher.mapping] },
764
+ setupCatalog(api) {
765
+ api.registerProcess(process);
766
+ },
767
+ setupServer(api, config) {
768
+ const verification = asUnknownRecord3(config)?.verification_on_merge;
769
+ if (verification !== void 0 && typeof verification !== "boolean")
770
+ throw new Error("Jira verification_on_merge must be a boolean");
771
+ verificationOnMerge = verification ?? options.verificationOnMerge ?? false;
772
+ adapter.maintenance?.register(api, process);
773
+ const jira = api.require(jiraIntegration), gitlab = api.require(gitlabIntegration), settings = api.require(scopedSettingsCapability);
774
+ if (Array.isArray(jira) || Array.isArray(gitlab) || Array.isArray(settings))
775
+ throw new Error("Integration capabilities must be singular");
776
+ const wiki = api.require(topicWikiCapability);
777
+ const host = api.require(coreHostCapabilities.serverSetup);
778
+ if (Array.isArray(wiki) || Array.isArray(host))
779
+ throw new Error("Integration capabilities must be singular");
780
+ wiki.registerProcessSource(process.id, jiraWikiSource(wiki, jira));
781
+ launcher.configure({
782
+ modelLabels: parseJiraModelLabels(config),
783
+ jira,
784
+ gitlab,
785
+ get ssh() {
786
+ const ssh = api.get(gitSshIntegration);
787
+ if (Array.isArray(ssh)) throw new Error("Integration capabilities must be singular");
788
+ return ssh;
789
+ },
790
+ settings,
791
+ wiki,
792
+ publications: host.publications
793
+ });
794
+ api.onStop(() => launcher.configure(null));
795
+ }
796
+ };
797
+ return {
798
+ /** @internal */
799
+ extension,
800
+ /** @internal */
801
+ process,
802
+ /** @internal */
803
+ launcher
804
+ };
805
+ }
806
+ var { extension: defaultExtension, process: jiraGitLabChangeProcess } = createJiraGitLabChange({ docker: true });
807
+ var index_default = defaultExtension;
808
+ export {
809
+ createJiraGitLabChange,
810
+ createJiraGitLabLauncher,
811
+ decodeJiraGitLabRepositoryMapping,
812
+ index_default as default,
813
+ defaultExtension,
814
+ jiraChangePrompt,
815
+ jiraGitLabChangeProcess,
816
+ jiraGitLabParamsCodec,
817
+ jiraGitLabRepositories
818
+ };
819
+ //# sourceMappingURL=index.js.map