@leitwerk-dev/jira-issue-split 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,577 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { PublicationStore } from "@leitwerk-dev/external-writes";
3
+ import type { GitSshIntegration } from "@leitwerk-dev/git-ssh";
4
+ import {
5
+ type GitLabIntegration,
6
+ parseGitLabSelection,
7
+ selectGitLabProjects,
8
+ } from "@leitwerk-dev/gitlab";
9
+ import {
10
+ assertJiraTicketText,
11
+ ensureIssueWiki,
12
+ type JiraCreateMetadata,
13
+ type JiraIntegration,
14
+ type JiraIssue,
15
+ type JiraIssueReceipt,
16
+ JiraRequestError,
17
+ jiraEpicRevision,
18
+ jiraIsEpic,
19
+ jiraIssueExternalId,
20
+ jiraSplitChildMatches,
21
+ jiraSubjectIdentity,
22
+ jiraTicketTextProblem,
23
+ markdownToJira,
24
+ } from "@leitwerk-dev/jira";
25
+ import { createJiraGitLabLauncher, type RepositoryMapping } from "@leitwerk-dev/jira-gitlab-change";
26
+ import {
27
+ type ProcessLaunchConfig,
28
+ type ScopedSettingsResolver,
29
+ type ServerExtensionAPI,
30
+ stringArg,
31
+ } from "@leitwerk-dev/process-sdk";
32
+ import type { TopicWikiStore } from "@leitwerk-dev/wiki";
33
+ import {
34
+ type SplitDraft,
35
+ type SplitParams,
36
+ type SplitRepository,
37
+ splitParamsCodec,
38
+ splitStateCodec,
39
+ splitTicketDescription,
40
+ } from "./model.js";
41
+
42
+ /** @internal */
43
+ export interface SplitServices {
44
+ /** @internal */ jira: JiraIntegration;
45
+ /** @internal */ gitlab: GitLabIntegration;
46
+ /** @internal */ ssh: GitSshIntegration;
47
+ /** @internal */ settings: ScopedSettingsResolver;
48
+ /** @internal */ wiki: TopicWikiStore;
49
+ /** @internal */ publications: PublicationStore;
50
+ }
51
+
52
+ const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
53
+
54
+ /** @internal */
55
+ export function splitPublicationKey(params: SplitParams, repository: SplitRepository): string {
56
+ return digest([params.jiraBaseUrl, params.epic.id, repository.origin, repository.projectId]);
57
+ }
58
+
59
+ /** @internal */
60
+ export function parseLabels(value: unknown): string[] {
61
+ if (value === undefined) return [];
62
+ if (typeof value !== "string") throw new Error("Ticket labels must be comma-separated text");
63
+ const labels = [...new Set(value.split(/[\s,]+/).filter(Boolean))];
64
+ if (
65
+ labels.some(
66
+ (label) =>
67
+ label === "leitwerk-issue-split" ||
68
+ label === "leitwerk-epic-split" ||
69
+ label === "leitwerk-done" ||
70
+ label.startsWith("leitwerk-split-"),
71
+ )
72
+ )
73
+ throw new Error(
74
+ "Split-trigger, done, and reconciliation labels cannot be selected for child tickets",
75
+ );
76
+ return labels;
77
+ }
78
+
79
+ /** @internal */
80
+ export function parseSplitOptions(input: Record<string, unknown>) {
81
+ const paths = (value: unknown) => {
82
+ if (value === undefined) return [];
83
+ if (typeof value !== "string")
84
+ throw new Error("GitLab selectors must be comma- or whitespace-separated paths");
85
+ return value.split(/[\s,]+/).filter(Boolean);
86
+ };
87
+ const issueType = input.issueType ?? "Story";
88
+ if (issueType !== "Story" && issueType !== "Task")
89
+ throw new Error("Select Story or Task for epic children");
90
+ if (
91
+ input.subtaskIssueType !== undefined &&
92
+ (typeof input.subtaskIssueType !== "string" ||
93
+ (input.subtaskIssueType !== "" && !/^\d+$/.test(input.subtaskIssueType)))
94
+ )
95
+ throw new Error("Subtask issue type must be a Jira type ID");
96
+ return {
97
+ /** @internal */
98
+ selection: parseGitLabSelection({
99
+ projects: { include: paths(input.projects), exclude: paths(input.excludeProjects) },
100
+ groups: { include: paths(input.groups), exclude: paths(input.excludeGroups) },
101
+ }),
102
+ /** @internal */
103
+ issueType: issueType as SplitParams["issueType"],
104
+ /** @internal */
105
+ subtaskIssueType: input.subtaskIssueType as string | undefined,
106
+ /** @internal */
107
+ labels: parseLabels(input.labels),
108
+ };
109
+ }
110
+
111
+ /** @internal */
112
+ export async function launchSplit(
113
+ services: SplitServices,
114
+ input: Record<string, unknown>,
115
+ ): Promise<ProcessLaunchConfig<SplitParams>> {
116
+ const jiraProfile = stringArg(input, "jiraProfile");
117
+ const gitlabProfile = stringArg(input, "gitlabProfile");
118
+ const sshProfile = stringArg(input, "sshProfile");
119
+ const options = parseSplitOptions(input);
120
+ if (!services.ssh.profiles().includes(sshProfile))
121
+ throw new Error("Select an available Git SSH profile");
122
+ const jira = services.jira.client(jiraProfile);
123
+ const epic = await jira.getIssue(stringArg({ issue: input.issue ?? input.epic }, "issue"));
124
+ if (!epic.fields.issuetype?.id || !epic.fields.issuetype.name)
125
+ throw new Error("Jira source issue type metadata is unavailable");
126
+ if (epic.fields.issuetype.subtask)
127
+ throw new Error("Jira subtasks cannot have nested subtasks; select their parent issue");
128
+ if (epic.fields.status.statusCategory.key === "done")
129
+ throw new Error("Select an open Jira issue");
130
+ if (!jira.createMetadata) throw new Error("Jira ticket creation metadata unavailable");
131
+ const metadata = await jira.createMetadata(epic.fields.project.id, jiraIsEpic(epic));
132
+ let subtaskType: SplitParams["subtaskType"];
133
+ if (!jiraIsEpic(epic)) {
134
+ const available = metadata.issueTypes.filter((type) => type.subtask === true);
135
+ const selected = options.subtaskIssueType
136
+ ? available.find((type) => type.id === options.subtaskIssueType)
137
+ : available.length === 1
138
+ ? available[0]
139
+ : undefined;
140
+ if (!selected)
141
+ throw new Error(
142
+ !available.length
143
+ ? "This Jira project offers no subtask issue types"
144
+ : `Select a subtask issue type ID: ${available.map((type) => `${type.name} (${type.id})`).join(", ")}`,
145
+ );
146
+ subtaskType = { id: selected.id, name: selected.name };
147
+ } else if (
148
+ !metadata.issueTypes.some(
149
+ (type) =>
150
+ type.subtask !== true && type.name.toLowerCase() === options.issueType.toLowerCase(),
151
+ )
152
+ ) {
153
+ throw new Error(`Jira does not offer ${options.issueType} in this project`);
154
+ }
155
+ const gitlab = services.gitlab.client(gitlabProfile);
156
+ const selected = await selectGitLabProjects(gitlab, options.selection);
157
+ if (!selected.length) throw new Error("No active repositories match the selected scope");
158
+ if (selected.length > 500)
159
+ throw new Error(
160
+ "This scope exceeds the mapped-turn limit of 500 repositories; narrow the selected groups/projects",
161
+ );
162
+ const repositories: SplitRepository[] = selected.map((repository) => ({
163
+ key: `repo_${repository.id}`,
164
+ name: repository.path_with_namespace,
165
+ projectId: repository.id,
166
+ origin: gitlab.baseUrl,
167
+ repoLocator: repository.ssh_url_to_repo ?? "",
168
+ baseBranch: repository.default_branch ?? "",
169
+ }));
170
+ const topic = ensureIssueWiki(services.wiki, jira, epic);
171
+ const project = services.settings.discover({
172
+ scopeType: "jira.project",
173
+ identity: jiraSubjectIdentity(jira.baseUrl, epic.fields.project.id),
174
+ label: epic.fields.project.key,
175
+ });
176
+ const params: SplitParams = {
177
+ jiraProfile,
178
+ jiraBaseUrl: jira.baseUrl,
179
+ gitlabProfile,
180
+ sshProfile,
181
+ epic,
182
+ topicId: topic.id,
183
+ repositories,
184
+ issueType: subtaskType ? "Sub-task" : options.issueType,
185
+ ...(subtaskType ? { subtaskType } : {}),
186
+ labels: options.labels,
187
+ };
188
+ return {
189
+ processId: "jira_epic_split_process",
190
+ startTurnId: "read_epic",
191
+ params,
192
+ title: `Split ${epic.key}: ${epic.fields.summary}`,
193
+ externalUrl: topic.url,
194
+ settingsContext: { "jira.project": project.id },
195
+ metadata: {
196
+ wiki: { topicId: topic.id, profile: jiraProfile, baseUrl: jira.baseUrl, issueId: epic.id },
197
+ },
198
+ projects: repositories
199
+ .filter((repository) => repository.repoLocator && repository.baseBranch)
200
+ .map((repository) => ({
201
+ key: repository.key,
202
+ repoLocator: repository.repoLocator,
203
+ baseBranch: repository.baseBranch,
204
+ workBranch: repository.baseBranch,
205
+ settingsRepository: { origin: repository.origin, repositoryId: repository.projectId },
206
+ metadata: {
207
+ gitlab: {
208
+ profile: gitlabProfile,
209
+ projectId: repository.projectId,
210
+ origin: repository.origin,
211
+ },
212
+ jira: { profile: jiraProfile, baseUrl: jira.baseUrl, issueId: epic.id },
213
+ },
214
+ })),
215
+ };
216
+ }
217
+
218
+ function sourceBlock(params: SplitParams, issue: JiraIssue): string | null {
219
+ if (issue.fields.project.id !== params.epic.fields.project.id)
220
+ return "Source issue moved to a different Jira project; launch a new split";
221
+ if (
222
+ !issue.fields.issuetype?.id ||
223
+ issue.fields.issuetype.id !== params.epic.fields.issuetype?.id ||
224
+ issue.fields.issuetype.subtask === true ||
225
+ jiraIsEpic(issue) !== jiraIsEpic(params.epic)
226
+ )
227
+ return "Source issue type changed; launch a new split";
228
+ return issue.fields.status.statusCategory.key === "done" ? "Source issue is closed" : null;
229
+ }
230
+
231
+ function resolveDraftType(metadata: JiraCreateMetadata, params: SplitParams, draft: SplitDraft) {
232
+ const subtask = !jiraIsEpic(params.epic);
233
+ if ((draft.issueType === "Sub-task") !== subtask)
234
+ throw new Error("Ticket type does not match the source issue's child relationship");
235
+ const type = metadata.issueTypes.find((candidate) =>
236
+ subtask
237
+ ? candidate.subtask === true && candidate.id === params.subtaskType?.id
238
+ : candidate.subtask !== true &&
239
+ candidate.name.toLowerCase() === draft.issueType.toLowerCase(),
240
+ );
241
+ if (!type)
242
+ throw new Error(
243
+ `Jira no longer offers the selected ${params.subtaskType?.name ?? draft.issueType} type`,
244
+ );
245
+ if (!subtask && !metadata.epicLinkField)
246
+ throw new Error("Splitting a Jira epic requires an Epic Link field");
247
+ return type;
248
+ }
249
+
250
+ /** @internal */
251
+ export async function componentMapping(
252
+ services: SplitServices,
253
+ params: SplitParams,
254
+ repository: SplitRepository,
255
+ ): Promise<{ componentIds: string[]; mappingRevision: string }> {
256
+ const client = services.jira.client(params.jiraProfile);
257
+ if (client.baseUrl !== params.jiraBaseUrl) throw new Error("Jira profile installation changed");
258
+ const project = services.settings.discover({
259
+ scopeType: "jira.project",
260
+ identity: jiraSubjectIdentity(client.baseUrl, params.epic.fields.project.id),
261
+ label: params.epic.fields.project.key,
262
+ });
263
+ const mapping = createJiraGitLabLauncher().mapping;
264
+ const matches = [];
265
+ for (const component of await client.listComponents(params.epic.fields.project.id)) {
266
+ const subject = services.settings.discover({
267
+ scopeType: "jira.component",
268
+ identity: jiraSubjectIdentity(client.baseUrl, component.id),
269
+ label: component.name,
270
+ context: { "jira.project": project.id },
271
+ });
272
+ const resolved = services.settings.resolve(mapping, {
273
+ "jira.project": project.id,
274
+ "jira.component": subject.id,
275
+ });
276
+ const entries = resolved.value.map((value) => JSON.parse(value) as RepositoryMapping);
277
+ if (
278
+ entries.some(
279
+ (entry) =>
280
+ entry.origin === repository.origin &&
281
+ entry.projectId === repository.projectId &&
282
+ entry.gitlabProfile === params.gitlabProfile &&
283
+ entry.sshProfile === params.sshProfile,
284
+ )
285
+ )
286
+ matches.push({ id: component.id, values: resolved.value, sources: resolved.sources });
287
+ }
288
+ return {
289
+ componentIds: matches.map((match) => match.id).sort(),
290
+ mappingRevision: digest(matches),
291
+ };
292
+ }
293
+
294
+ async function repositoryBlock(
295
+ services: SplitServices,
296
+ params: SplitParams,
297
+ repository: SplitRepository,
298
+ draft: SplitDraft,
299
+ ): Promise<string | null> {
300
+ const provider = services.gitlab.client(params.gitlabProfile);
301
+ if (provider.baseUrl !== repository.origin)
302
+ return "GitLab profile installation changed; launch a new split";
303
+ try {
304
+ const fresh = await provider.getProject(repository.projectId);
305
+ if (fresh.archived || !fresh.default_branch || !fresh.ssh_url_to_repo)
306
+ return "Repository is archived, empty, or lacks an SSH clone URL";
307
+ if (
308
+ fresh.ssh_url_to_repo !== repository.repoLocator ||
309
+ fresh.default_branch !== repository.baseBranch
310
+ )
311
+ return "Repository checkout binding changed; launch a new split";
312
+ if (
313
+ draft.verdict === "applicable" &&
314
+ (await provider.getBranch(repository.projectId, repository.baseBranch)).commit.id !==
315
+ draft.revision
316
+ )
317
+ return "Repository changed since assessment; request revision before approval";
318
+ return null;
319
+ } catch {
320
+ return "Repository cannot be inspected; restore access and refresh the batch";
321
+ }
322
+ }
323
+
324
+ /** @internal */
325
+ export function registerSplitTools(api: ServerExtensionAPI, services: SplitServices): void {
326
+ for (const name of ["jira_split_prepare", "jira_split_publish"] as const)
327
+ api.tool<Record<string, unknown>>({
328
+ name,
329
+ description: "Prepare the review batch or publish one operator-approved repository ticket",
330
+ parameters: {
331
+ type: "object",
332
+ properties: { repositoryKey: { type: "string" } },
333
+ additionalProperties: false,
334
+ },
335
+ async execute(ctx, args) {
336
+ if (ctx.process.processId !== "jira_epic_split_process")
337
+ throw new Error("Issue split process required");
338
+ const params = splitParamsCodec.parse(JSON.parse(ctx.process.paramsJson ?? "null"));
339
+ const state = splitStateCodec.parse(JSON.parse(ctx.process.stateJson ?? "null"));
340
+ const client = services.jira.client(params.jiraProfile);
341
+ if (client.baseUrl !== params.jiraBaseUrl)
342
+ throw new Error("Jira profile installation changed");
343
+ const epic = await client.getIssue(params.epic.id);
344
+ const revision = jiraEpicRevision(epic);
345
+ const sourceBlocked = sourceBlock(params, epic);
346
+ if (jiraIsEpic(epic) === jiraIsEpic(params.epic))
347
+ ensureIssueWiki(services.wiki, client, epic);
348
+ if (name === "jira_split_prepare") {
349
+ const metadata = state.drafts.some(
350
+ (draft) => !draft.receipt && draft.verdict === "applicable",
351
+ )
352
+ ? await client.createMetadata?.(params.epic.fields.project.id, jiraIsEpic(params.epic))
353
+ : undefined;
354
+ const drafts: SplitDraft[] = [];
355
+ for (const draft of state.drafts) {
356
+ if (draft.receipt) {
357
+ drafts.push(draft);
358
+ continue;
359
+ }
360
+ const repository = params.repositories.find(
361
+ (candidate) => candidate.key === draft.repositoryKey,
362
+ );
363
+ if (!repository) throw new Error("Draft refers to an unauthorized repository");
364
+ const mapping = await componentMapping(services, params, repository);
365
+ let typeBlocked: string | null = null;
366
+ if (draft.verdict === "applicable") {
367
+ try {
368
+ if (!metadata) throw new Error("Jira ticket creation metadata unavailable");
369
+ resolveDraftType(metadata, params, draft);
370
+ } catch (error) {
371
+ typeBlocked = error instanceof Error ? error.message : "Ticket type unavailable";
372
+ }
373
+ }
374
+ const blocked =
375
+ sourceBlocked ??
376
+ typeBlocked ??
377
+ (draft.verdict === "applicable"
378
+ ? jiraTicketTextProblem(draft.summary, draft.description)
379
+ : null) ??
380
+ (state.epicRevision && revision !== state.epicRevision
381
+ ? "Source issue changed: request revision before approval"
382
+ : draft.verdict === "applicable" && !mapping.componentIds.length
383
+ ? "Map this repository in Settings → Jira components, then refresh mappings"
384
+ : draft.verdict === "unresolved"
385
+ ? "Assessment unresolved: revise or explicitly exclude"
386
+ : draft.verdict === "applicable"
387
+ ? await repositoryBlock(services, params, repository, draft)
388
+ : null);
389
+ drafts.push({ ...draft, ...mapping, blocked });
390
+ }
391
+ return {
392
+ drafts,
393
+ epic,
394
+ epicRevision: revision,
395
+ };
396
+ }
397
+ const repositoryKey = stringArg(args, "repositoryKey");
398
+ if (ctx.turn.turnId !== "publish_tickets" || !state.approved.includes(repositoryKey))
399
+ throw new Error("Ticket has no current operator approval");
400
+ const draft = state.drafts.find((candidate) => candidate.repositoryKey === repositoryKey);
401
+ const repository = params.repositories.find((candidate) => candidate.key === repositoryKey);
402
+ if (
403
+ !draft ||
404
+ !repository ||
405
+ draft.excluded ||
406
+ draft.blocked ||
407
+ draft.verdict !== "applicable"
408
+ )
409
+ throw new Error("Ticket is not publishable");
410
+ if (!client.findSplitIssue) throw new Error("Jira issue reconciliation unavailable");
411
+ const findSplitIssue = client.findSplitIssue.bind(client);
412
+ const key = splitPublicationKey(params, repository);
413
+ const marker = `leitwerk-split-${key}`;
414
+ const binding = {
415
+ ...repository,
416
+ gitlabProfile: params.gitlabProfile,
417
+ sshProfile: params.sshProfile,
418
+ sourceIssueId: params.epic.id,
419
+ relationship: jiraIsEpic(params.epic) ? ("epic" as const) : ("subtask" as const),
420
+ };
421
+ const reservation = { key, topicId: params.topicId, binding, externalId: null, url: null };
422
+ const existing = services.publications.publication(key);
423
+ if (
424
+ existing &&
425
+ (existing.topicId !== params.topicId ||
426
+ (existing.binding.sourceIssueId ?? existing.binding.epicId) !== binding.sourceIssueId ||
427
+ (existing.binding.relationship ?? "epic") !== binding.relationship ||
428
+ [
429
+ "origin",
430
+ "projectId",
431
+ "gitlabProfile",
432
+ "sshProfile",
433
+ "repoLocator",
434
+ "baseBranch",
435
+ ].some(
436
+ (field) => existing.binding[field] !== (binding as Record<string, unknown>)[field],
437
+ ))
438
+ )
439
+ throw new Error(
440
+ "Existing ticket publication has a different repository binding; reconcile before continuing",
441
+ );
442
+ const readRemote = async () => {
443
+ const recorded = services.publications.publication(key);
444
+ const issue = recorded?.externalId
445
+ ? await client.getIssue(
446
+ String((JSON.parse(recorded.externalId.slice(5)) as string[])[1]),
447
+ )
448
+ : await findSplitIssue(params.epic.fields.project.id, marker);
449
+ if (!issue) return null;
450
+ if (
451
+ issue.fields.project.id !== params.epic.fields.project.id ||
452
+ !issue.fields.labels.includes(marker)
453
+ )
454
+ throw new Error("Uncorrelated Jira split receipt");
455
+ if (
456
+ !(await jiraSplitChildMatches(
457
+ client,
458
+ issue,
459
+ binding.sourceIssueId,
460
+ binding.relationship,
461
+ ))
462
+ )
463
+ throw new Error("Created issue no longer belongs to this source issue");
464
+ const url = `${client.baseUrl}/browse/${encodeURIComponent(issue.key)}`;
465
+ if (!recorded) services.publications.reservePublication(reservation);
466
+ services.publications.finishPublication(
467
+ key,
468
+ jiraIssueExternalId(client.baseUrl, issue.id),
469
+ url,
470
+ );
471
+ return { id: issue.id, key: issue.key, url };
472
+ };
473
+ const uncertainPublication = (): never => {
474
+ throw new Error(
475
+ `Jira creation outcome is uncertain. Find the ticket with label ${marker} and retry after it is searchable; another POST is blocked`,
476
+ );
477
+ };
478
+ const ensureTicket = (execute: () => Promise<NonNullable<SplitDraft["receipt"]>>) =>
479
+ ctx.externalWrites.ensure(
480
+ { writeType: "jira.create_issue", dedupKey: `jira-split:${key}` },
481
+ { reconcile: readRemote, execute, toMetadata: (value) => value },
482
+ );
483
+ const wantsTrigger = state.labels.includes("use-leitwerk");
484
+ const triggerPending = () =>
485
+ wantsTrigger && !services.publications.publication(key)?.triggered;
486
+ const reconcileTrigger = async (id: string, recorded = false) => {
487
+ const { labels } = (await client.getIssue(id)).fields;
488
+ const triggered =
489
+ services.publications.publication(key)?.triggered ||
490
+ recorded ||
491
+ labels.includes("use-leitwerk") ||
492
+ labels.includes("leitwerk-done");
493
+ if (triggered) services.publications.markPublicationTriggered(key);
494
+ return triggered;
495
+ };
496
+ let receipt: NonNullable<SplitDraft["receipt"]> | null = null;
497
+ if (existing) {
498
+ receipt = await ensureTicket(async () => uncertainPublication());
499
+ if (triggerPending()) await reconcileTrigger(receipt.id);
500
+ }
501
+ if (!receipt || triggerPending()) {
502
+ if (sourceBlocked) return { reviewRequired: sourceBlocked };
503
+ const mapping = await componentMapping(services, params, repository);
504
+ if (revision !== state.epicRevision || mapping.mappingRevision !== draft.mappingRevision)
505
+ return {
506
+ reviewRequired: "Source issue or component mapping changed; review the batch again",
507
+ };
508
+ const blocked = await repositoryBlock(services, params, repository, draft);
509
+ if (blocked) return { reviewRequired: blocked };
510
+ }
511
+ if (!receipt) {
512
+ assertJiraTicketText(draft.summary, draft.description);
513
+ parseLabels(state.labels.join(","));
514
+ if (!client.createIssueReceipt || !client.createMetadata)
515
+ throw new Error("Jira issue creation unavailable");
516
+ const createIssue = client.createIssueReceipt.bind(client);
517
+ const metadata = await client.createMetadata(
518
+ epic.fields.project.id,
519
+ jiraIsEpic(params.epic),
520
+ );
521
+ const type = resolveDraftType(metadata, params, draft);
522
+ const fields: Record<string, unknown> = {
523
+ project: { id: epic.fields.project.id },
524
+ issuetype: { id: type.id },
525
+ summary: draft.summary,
526
+ description: markdownToJira(splitTicketDescription(params, repository, draft)),
527
+ components: draft.componentIds.map((id) => ({ id })),
528
+ labels: [...state.labels.filter((label) => label !== "use-leitwerk"), marker],
529
+ ...(binding.relationship === "subtask"
530
+ ? { parent: { id: epic.id } }
531
+ : { [metadata.epicLinkField!]: epic.key }),
532
+ };
533
+ for (const [field, spec] of Object.entries(type.fields))
534
+ if (spec.required && !spec.hasDefaultValue && !(field in fields))
535
+ throw new Error(
536
+ `Jira requires field ${field}; configure its default before publishing`,
537
+ );
538
+ receipt = await ensureTicket(async () => {
539
+ if (!services.publications.reservePublication(reservation)) uncertainPublication();
540
+ let created: JiraIssueReceipt;
541
+ try {
542
+ created = await createIssue(fields);
543
+ } catch (error) {
544
+ if (
545
+ error instanceof JiraRequestError &&
546
+ [400, 401, 403, 404, 422].includes(error.status)
547
+ )
548
+ services.publications.releaseRejectedPublication(key);
549
+ throw error;
550
+ }
551
+ const url = `${client.baseUrl}/browse/${encodeURIComponent(created.key)}`;
552
+ services.publications.finishPublication(
553
+ key,
554
+ jiraIssueExternalId(client.baseUrl, created.id),
555
+ url,
556
+ );
557
+ return { ...created, url };
558
+ });
559
+ }
560
+ if (wantsTrigger)
561
+ await ctx.externalWrites.ensure(
562
+ { writeType: "jira.split_trigger", dedupKey: `jira-split-trigger:${key}` },
563
+ {
564
+ reconcile: async (phase) =>
565
+ (await reconcileTrigger(receipt.id, phase === "already_recorded")) ? receipt : null,
566
+ execute: async () => {
567
+ await client.updateLabels(receipt.id, [], ["use-leitwerk"]);
568
+ services.publications.markPublicationTriggered(key);
569
+ return receipt;
570
+ },
571
+ toMetadata: (receipt) => receipt,
572
+ },
573
+ );
574
+ return { receipt };
575
+ },
576
+ });
577
+ }
@@ -0,0 +1,30 @@
1
+ import { LocalGitLabAdapter } from "@leitwerk-dev/gitlab/testing";
2
+ import type { JiraIssue } from "@leitwerk-dev/jira";
3
+ import { LocalJiraSplitAdapter as LocalJiraAdapter } from "@leitwerk-dev/jira/testing";
4
+ import { LocalGit, type LocalGitSeedCache } from "@leitwerk-dev/test-support/local-git";
5
+
6
+ /** @internal */
7
+ export function createSplitSources(root: string, sourceType = "Epic", seeds?: LocalGitSeedCache) {
8
+ const git = new LocalGit(root);
9
+ const gitlab = new LocalGitLabAdapter(root);
10
+ for (const name of ["one", "two"]) {
11
+ const seed = { owner: "team", name, files: { "README.md": "Old standard" } };
12
+ gitlab.addProject(`team/${name}`, seeds ? seeds.copy(git, seed) : git.seed(seed).bare);
13
+ }
14
+ const jira = new LocalJiraAdapter();
15
+ const epic: JiraIssue = {
16
+ id: "10",
17
+ key: "APP-10",
18
+ fields: {
19
+ summary: "Standardize readmes",
20
+ description: "Use the shared sections",
21
+ issuetype: { id: sourceType.toLowerCase(), name: sourceType, subtask: false },
22
+ project: { id: "100", key: "APP", name: "App" },
23
+ components: [],
24
+ labels: [],
25
+ status: { statusCategory: { key: "new" } },
26
+ },
27
+ };
28
+ jira.seedIssue(epic);
29
+ return { git, gitlab, jira, epic };
30
+ }