@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.
package/dist/index.js ADDED
@@ -0,0 +1,1128 @@
1
+ // src/index.ts
2
+ import { asUnknownRecord as asUnknownRecord3 } from "@leitwerk-dev/domain";
3
+ import { gitSshIntegration } from "@leitwerk-dev/git-ssh";
4
+ import { gitlabIntegration } from "@leitwerk-dev/gitlab";
5
+ import {
6
+ jiraIntegration,
7
+ jiraIssueExternalId as jiraIssueExternalId2,
8
+ jiraSplitEligible,
9
+ jiraWikiSource
10
+ } from "@leitwerk-dev/jira";
11
+ import {
12
+ coreHostCapabilities,
13
+ defineProcessWatcherSource,
14
+ scopedSettingsCapability,
15
+ stringArg as stringArg3
16
+ } from "@leitwerk-dev/process-sdk";
17
+ import { createPollSchedule, emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
18
+ import { topicWikiCapability } from "@leitwerk-dev/wiki/integration";
19
+
20
+ // src/process.ts
21
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
22
+ import {
23
+ assertJiraTicketText as assertJiraTicketText2,
24
+ jiraTicketWritingInstructions
25
+ } from "@leitwerk-dev/jira";
26
+ import {
27
+ flow
28
+ } from "@leitwerk-dev/process-sdk";
29
+ import { wikiInstructions } from "@leitwerk-dev/wiki";
30
+
31
+ // src/model.ts
32
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
33
+ import { jiraIsEpic, ticketDescriptionMarkdown } from "@leitwerk-dev/jira";
34
+ import {
35
+ createEmptyStructuralProcessState,
36
+ stringArg
37
+ } from "@leitwerk-dev/process-sdk";
38
+ function initialSplitState(params) {
39
+ return {
40
+ ...createEmptyStructuralProcessState(),
41
+ candidates: [],
42
+ drafts: [],
43
+ approved: [],
44
+ labels: params.labels,
45
+ feedback: "",
46
+ epicRevision: "",
47
+ epic: null
48
+ };
49
+ }
50
+ function parseDraft(value, params) {
51
+ const record = asUnknownRecord(value);
52
+ if (!record || !["applicable", "not_applicable", "already_compliant", "unresolved"].includes(
53
+ String(record.verdict)
54
+ ) || !["Story", "Task", "Sub-task"].includes(String(record.issueType)))
55
+ throw new Error("Invalid repository assessment");
56
+ const draft = {
57
+ repositoryKey: stringArg(record, "repositoryKey"),
58
+ verdict: record.verdict,
59
+ reason: stringArg(record, "reason"),
60
+ evidence: stringArg(record, "evidence"),
61
+ revision: typeof record.revision === "string" ? record.revision : "",
62
+ summary: typeof record.summary === "string" ? record.summary : "",
63
+ description: typeof record.description === "string" ? record.description : "",
64
+ issueType: record.issueType,
65
+ componentIds: [],
66
+ mappingRevision: "",
67
+ blocked: null,
68
+ excluded: false
69
+ };
70
+ if (draft.verdict === "applicable" && (!draft.summary.trim() || !draft.description.trim() || !/^[a-f0-9]{40,64}$/i.test(draft.revision)))
71
+ throw new Error("Applicable repositories require a ticket draft and inspected commit ID");
72
+ if (params && draft.issueType === "Sub-task" !== Boolean(params.subtaskType))
73
+ throw new Error("Ticket type does not match the source issue's child relationship");
74
+ return draft;
75
+ }
76
+ var splitParamsCodec = {
77
+ parse(value) {
78
+ const record = asUnknownRecord(value);
79
+ if (!record || !Array.isArray(record.repositories) || !asUnknownRecord(record.epic) || !["Story", "Task", "Sub-task"].includes(String(record.issueType)) || !Array.isArray(record.labels) || record.labels.some((label) => typeof label !== "string"))
80
+ throw new Error("Invalid issue split snapshot");
81
+ if (!jiraIsEpic(record.epic)) {
82
+ const subtaskType = asUnknownRecord(record.subtaskType);
83
+ if (!subtaskType || record.issueType !== "Sub-task")
84
+ throw new Error("Issue split requires a retained subtask type");
85
+ stringArg(subtaskType, "id");
86
+ stringArg(subtaskType, "name");
87
+ } else if (record.issueType === "Sub-task") {
88
+ throw new Error("Epic children must be Stories or Tasks");
89
+ }
90
+ for (const key of ["jiraProfile", "jiraBaseUrl", "gitlabProfile", "sshProfile", "topicId"])
91
+ stringArg(record, key);
92
+ for (const candidate of record.repositories) {
93
+ const repository = asUnknownRecord(candidate);
94
+ if (!repository || !Number.isSafeInteger(repository.projectId) || Number(repository.projectId) < 1)
95
+ throw new Error("Invalid split repository");
96
+ for (const key of ["key", "name", "origin"]) stringArg(repository, key);
97
+ if (typeof repository.repoLocator !== "string" || typeof repository.baseBranch !== "string")
98
+ throw new Error("Invalid repository checkout binding");
99
+ }
100
+ if (new Set(record.repositories.map((repository) => repository.key)).size !== record.repositories.length)
101
+ throw new Error("Duplicate split repository");
102
+ return record;
103
+ },
104
+ serialize: (value) => value
105
+ };
106
+ var splitStateCodec = {
107
+ parse(value) {
108
+ const record = asUnknownRecord(value);
109
+ if (!record || !Array.isArray(record.drafts) || !Array.isArray(record.candidates) || !Array.isArray(record.approved) || !Array.isArray(record.labels) || typeof record.epicRevision !== "string")
110
+ throw new Error("Invalid issue split state");
111
+ for (const values of [record.candidates, record.approved, record.labels])
112
+ if (values.some((value2) => typeof value2 !== "string") || new Set(values).size !== values.length)
113
+ throw new Error("Invalid split selection");
114
+ for (const value2 of record.drafts) {
115
+ parseDraft(value2);
116
+ if (!Array.isArray(value2.componentIds) || value2.componentIds.some((id) => typeof id !== "string") || typeof value2.mappingRevision !== "string" || typeof value2.excluded !== "boolean" || value2.blocked !== null && typeof value2.blocked !== "string")
117
+ throw new Error("Invalid persisted split draft");
118
+ if (value2.receipt) for (const key of ["id", "key", "url"]) stringArg(value2.receipt, key);
119
+ }
120
+ const drafts = record.drafts;
121
+ if (new Set(drafts.map((draft) => draft.repositoryKey)).size !== drafts.length || record.approved.some((key) => !drafts.some((draft) => draft.repositoryKey === key)))
122
+ throw new Error("Invalid approved split drafts");
123
+ return record;
124
+ },
125
+ serialize: (value) => value
126
+ };
127
+ function splitTicketDescription(params, repository, draft) {
128
+ return ticketDescriptionMarkdown(draft.description, {
129
+ repositoryName: repository.name,
130
+ repositoryUrl: `${repository.origin.replace(/\/$/, "")}/${repository.name.split("/").map(encodeURIComponent).join("/")}`,
131
+ sourceKey: params.epic.key,
132
+ sourceUrl: `${params.jiraBaseUrl.replace(/\/$/, "")}/browse/${encodeURIComponent(params.epic.key)}`
133
+ });
134
+ }
135
+ function batchMarkdown(params, state) {
136
+ return `# ${params.epic.key}: repository tickets
137
+
138
+ [Shared solution wiki](/wiki/${params.topicId})
139
+
140
+ ${params.subtaskType ? `Subtask type: ${params.subtaskType.name} (${params.subtaskType.id}).
141
+
142
+ ` : ""}Labels selected for new tickets: ${state.labels.join(", ") || "none"}.
143
+
144
+ ${state.drafts.map((draft) => {
145
+ const repository = params.repositories.find(
146
+ (candidate) => candidate.key === draft.repositoryKey
147
+ );
148
+ return `## ${repository?.name ?? draft.repositoryKey}
149
+
150
+ ${draft.receipt ? `[${draft.receipt.key}](${draft.receipt.url}) \u2014 published` : draft.excluded ? "Excluded by operator" : `${draft.verdict}${draft.blocked ? ` \u2014 BLOCKED: ${draft.blocked}` : ""}`}
151
+
152
+ ${draft.reason}
153
+
154
+ ${draft.summary ? `### ${draft.issueType}: ${draft.summary}
155
+
156
+ ${repository ? splitTicketDescription(params, repository, draft) : draft.description}
157
+
158
+ Components: ${draft.componentIds.join(", ") || "mapping required"}
159
+
160
+ ` : ""}### Inspection evidence
161
+
162
+ ${draft.evidence}
163
+
164
+ Inspected revision: ${draft.revision || "unavailable"}`;
165
+ }).join("\n\n")}`;
166
+ }
167
+
168
+ // src/services.ts
169
+ import { createHash } from "crypto";
170
+ import {
171
+ parseGitLabSelection,
172
+ selectGitLabProjects
173
+ } from "@leitwerk-dev/gitlab";
174
+ import {
175
+ assertJiraTicketText,
176
+ ensureIssueWiki,
177
+ JiraRequestError,
178
+ jiraEpicRevision,
179
+ jiraIsEpic as jiraIsEpic2,
180
+ jiraIssueExternalId,
181
+ jiraSplitChildMatches,
182
+ jiraSubjectIdentity,
183
+ jiraTicketTextProblem,
184
+ markdownToJira
185
+ } from "@leitwerk-dev/jira";
186
+ import { createJiraGitLabLauncher } from "@leitwerk-dev/jira-gitlab-change";
187
+ import {
188
+ stringArg as stringArg2
189
+ } from "@leitwerk-dev/process-sdk";
190
+ var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
191
+ function splitPublicationKey(params, repository) {
192
+ return digest([params.jiraBaseUrl, params.epic.id, repository.origin, repository.projectId]);
193
+ }
194
+ function parseLabels(value) {
195
+ if (value === void 0) return [];
196
+ if (typeof value !== "string") throw new Error("Ticket labels must be comma-separated text");
197
+ const labels = [...new Set(value.split(/[\s,]+/).filter(Boolean))];
198
+ if (labels.some(
199
+ (label) => label === "leitwerk-issue-split" || label === "leitwerk-epic-split" || label === "leitwerk-done" || label.startsWith("leitwerk-split-")
200
+ ))
201
+ throw new Error(
202
+ "Split-trigger, done, and reconciliation labels cannot be selected for child tickets"
203
+ );
204
+ return labels;
205
+ }
206
+ function parseSplitOptions(input) {
207
+ const paths = (value) => {
208
+ if (value === void 0) return [];
209
+ if (typeof value !== "string")
210
+ throw new Error("GitLab selectors must be comma- or whitespace-separated paths");
211
+ return value.split(/[\s,]+/).filter(Boolean);
212
+ };
213
+ const issueType = input.issueType ?? "Story";
214
+ if (issueType !== "Story" && issueType !== "Task")
215
+ throw new Error("Select Story or Task for epic children");
216
+ if (input.subtaskIssueType !== void 0 && (typeof input.subtaskIssueType !== "string" || input.subtaskIssueType !== "" && !/^\d+$/.test(input.subtaskIssueType)))
217
+ throw new Error("Subtask issue type must be a Jira type ID");
218
+ return {
219
+ /** @internal */
220
+ selection: parseGitLabSelection({
221
+ projects: { include: paths(input.projects), exclude: paths(input.excludeProjects) },
222
+ groups: { include: paths(input.groups), exclude: paths(input.excludeGroups) }
223
+ }),
224
+ /** @internal */
225
+ issueType,
226
+ /** @internal */
227
+ subtaskIssueType: input.subtaskIssueType,
228
+ /** @internal */
229
+ labels: parseLabels(input.labels)
230
+ };
231
+ }
232
+ async function launchSplit(services2, input) {
233
+ const jiraProfile = stringArg2(input, "jiraProfile");
234
+ const gitlabProfile = stringArg2(input, "gitlabProfile");
235
+ const sshProfile = stringArg2(input, "sshProfile");
236
+ const options = parseSplitOptions(input);
237
+ if (!services2.ssh.profiles().includes(sshProfile))
238
+ throw new Error("Select an available Git SSH profile");
239
+ const jira = services2.jira.client(jiraProfile);
240
+ const epic = await jira.getIssue(stringArg2({ issue: input.issue ?? input.epic }, "issue"));
241
+ if (!epic.fields.issuetype?.id || !epic.fields.issuetype.name)
242
+ throw new Error("Jira source issue type metadata is unavailable");
243
+ if (epic.fields.issuetype.subtask)
244
+ throw new Error("Jira subtasks cannot have nested subtasks; select their parent issue");
245
+ if (epic.fields.status.statusCategory.key === "done")
246
+ throw new Error("Select an open Jira issue");
247
+ if (!jira.createMetadata) throw new Error("Jira ticket creation metadata unavailable");
248
+ const metadata = await jira.createMetadata(epic.fields.project.id, jiraIsEpic2(epic));
249
+ let subtaskType;
250
+ if (!jiraIsEpic2(epic)) {
251
+ const available = metadata.issueTypes.filter((type) => type.subtask === true);
252
+ const selected2 = options.subtaskIssueType ? available.find((type) => type.id === options.subtaskIssueType) : available.length === 1 ? available[0] : void 0;
253
+ if (!selected2)
254
+ throw new Error(
255
+ !available.length ? "This Jira project offers no subtask issue types" : `Select a subtask issue type ID: ${available.map((type) => `${type.name} (${type.id})`).join(", ")}`
256
+ );
257
+ subtaskType = { id: selected2.id, name: selected2.name };
258
+ } else if (!metadata.issueTypes.some(
259
+ (type) => type.subtask !== true && type.name.toLowerCase() === options.issueType.toLowerCase()
260
+ )) {
261
+ throw new Error(`Jira does not offer ${options.issueType} in this project`);
262
+ }
263
+ const gitlab = services2.gitlab.client(gitlabProfile);
264
+ const selected = await selectGitLabProjects(gitlab, options.selection);
265
+ if (!selected.length) throw new Error("No active repositories match the selected scope");
266
+ if (selected.length > 500)
267
+ throw new Error(
268
+ "This scope exceeds the mapped-turn limit of 500 repositories; narrow the selected groups/projects"
269
+ );
270
+ const repositories = selected.map((repository) => ({
271
+ key: `repo_${repository.id}`,
272
+ name: repository.path_with_namespace,
273
+ projectId: repository.id,
274
+ origin: gitlab.baseUrl,
275
+ repoLocator: repository.ssh_url_to_repo ?? "",
276
+ baseBranch: repository.default_branch ?? ""
277
+ }));
278
+ const topic = ensureIssueWiki(services2.wiki, jira, epic);
279
+ const project = services2.settings.discover({
280
+ scopeType: "jira.project",
281
+ identity: jiraSubjectIdentity(jira.baseUrl, epic.fields.project.id),
282
+ label: epic.fields.project.key
283
+ });
284
+ const params = {
285
+ jiraProfile,
286
+ jiraBaseUrl: jira.baseUrl,
287
+ gitlabProfile,
288
+ sshProfile,
289
+ epic,
290
+ topicId: topic.id,
291
+ repositories,
292
+ issueType: subtaskType ? "Sub-task" : options.issueType,
293
+ ...subtaskType ? { subtaskType } : {},
294
+ labels: options.labels
295
+ };
296
+ return {
297
+ processId: "jira_epic_split_process",
298
+ startTurnId: "read_epic",
299
+ params,
300
+ title: `Split ${epic.key}: ${epic.fields.summary}`,
301
+ externalUrl: topic.url,
302
+ settingsContext: { "jira.project": project.id },
303
+ metadata: {
304
+ wiki: { topicId: topic.id, profile: jiraProfile, baseUrl: jira.baseUrl, issueId: epic.id }
305
+ },
306
+ projects: repositories.filter((repository) => repository.repoLocator && repository.baseBranch).map((repository) => ({
307
+ key: repository.key,
308
+ repoLocator: repository.repoLocator,
309
+ baseBranch: repository.baseBranch,
310
+ workBranch: repository.baseBranch,
311
+ settingsRepository: { origin: repository.origin, repositoryId: repository.projectId },
312
+ metadata: {
313
+ gitlab: {
314
+ profile: gitlabProfile,
315
+ projectId: repository.projectId,
316
+ origin: repository.origin
317
+ },
318
+ jira: { profile: jiraProfile, baseUrl: jira.baseUrl, issueId: epic.id }
319
+ }
320
+ }))
321
+ };
322
+ }
323
+ function sourceBlock(params, issue) {
324
+ if (issue.fields.project.id !== params.epic.fields.project.id)
325
+ return "Source issue moved to a different Jira project; launch a new split";
326
+ if (!issue.fields.issuetype?.id || issue.fields.issuetype.id !== params.epic.fields.issuetype?.id || issue.fields.issuetype.subtask === true || jiraIsEpic2(issue) !== jiraIsEpic2(params.epic))
327
+ return "Source issue type changed; launch a new split";
328
+ return issue.fields.status.statusCategory.key === "done" ? "Source issue is closed" : null;
329
+ }
330
+ function resolveDraftType(metadata, params, draft) {
331
+ const subtask = !jiraIsEpic2(params.epic);
332
+ if (draft.issueType === "Sub-task" !== subtask)
333
+ throw new Error("Ticket type does not match the source issue's child relationship");
334
+ const type = metadata.issueTypes.find(
335
+ (candidate) => subtask ? candidate.subtask === true && candidate.id === params.subtaskType?.id : candidate.subtask !== true && candidate.name.toLowerCase() === draft.issueType.toLowerCase()
336
+ );
337
+ if (!type)
338
+ throw new Error(
339
+ `Jira no longer offers the selected ${params.subtaskType?.name ?? draft.issueType} type`
340
+ );
341
+ if (!subtask && !metadata.epicLinkField)
342
+ throw new Error("Splitting a Jira epic requires an Epic Link field");
343
+ return type;
344
+ }
345
+ async function componentMapping(services2, params, repository) {
346
+ const client = services2.jira.client(params.jiraProfile);
347
+ if (client.baseUrl !== params.jiraBaseUrl) throw new Error("Jira profile installation changed");
348
+ const project = services2.settings.discover({
349
+ scopeType: "jira.project",
350
+ identity: jiraSubjectIdentity(client.baseUrl, params.epic.fields.project.id),
351
+ label: params.epic.fields.project.key
352
+ });
353
+ const mapping = createJiraGitLabLauncher().mapping;
354
+ const matches = [];
355
+ for (const component of await client.listComponents(params.epic.fields.project.id)) {
356
+ const subject = services2.settings.discover({
357
+ scopeType: "jira.component",
358
+ identity: jiraSubjectIdentity(client.baseUrl, component.id),
359
+ label: component.name,
360
+ context: { "jira.project": project.id }
361
+ });
362
+ const resolved = services2.settings.resolve(mapping, {
363
+ "jira.project": project.id,
364
+ "jira.component": subject.id
365
+ });
366
+ const entries = resolved.value.map((value) => JSON.parse(value));
367
+ if (entries.some(
368
+ (entry) => entry.origin === repository.origin && entry.projectId === repository.projectId && entry.gitlabProfile === params.gitlabProfile && entry.sshProfile === params.sshProfile
369
+ ))
370
+ matches.push({ id: component.id, values: resolved.value, sources: resolved.sources });
371
+ }
372
+ return {
373
+ componentIds: matches.map((match) => match.id).sort(),
374
+ mappingRevision: digest(matches)
375
+ };
376
+ }
377
+ async function repositoryBlock(services2, params, repository, draft) {
378
+ const provider = services2.gitlab.client(params.gitlabProfile);
379
+ if (provider.baseUrl !== repository.origin)
380
+ return "GitLab profile installation changed; launch a new split";
381
+ try {
382
+ const fresh = await provider.getProject(repository.projectId);
383
+ if (fresh.archived || !fresh.default_branch || !fresh.ssh_url_to_repo)
384
+ return "Repository is archived, empty, or lacks an SSH clone URL";
385
+ if (fresh.ssh_url_to_repo !== repository.repoLocator || fresh.default_branch !== repository.baseBranch)
386
+ return "Repository checkout binding changed; launch a new split";
387
+ if (draft.verdict === "applicable" && (await provider.getBranch(repository.projectId, repository.baseBranch)).commit.id !== draft.revision)
388
+ return "Repository changed since assessment; request revision before approval";
389
+ return null;
390
+ } catch {
391
+ return "Repository cannot be inspected; restore access and refresh the batch";
392
+ }
393
+ }
394
+ function registerSplitTools(api, services2) {
395
+ for (const name of ["jira_split_prepare", "jira_split_publish"])
396
+ api.tool({
397
+ name,
398
+ description: "Prepare the review batch or publish one operator-approved repository ticket",
399
+ parameters: {
400
+ type: "object",
401
+ properties: { repositoryKey: { type: "string" } },
402
+ additionalProperties: false
403
+ },
404
+ async execute(ctx, args) {
405
+ if (ctx.process.processId !== "jira_epic_split_process")
406
+ throw new Error("Issue split process required");
407
+ const params = splitParamsCodec.parse(JSON.parse(ctx.process.paramsJson ?? "null"));
408
+ const state = splitStateCodec.parse(JSON.parse(ctx.process.stateJson ?? "null"));
409
+ const client = services2.jira.client(params.jiraProfile);
410
+ if (client.baseUrl !== params.jiraBaseUrl)
411
+ throw new Error("Jira profile installation changed");
412
+ const epic = await client.getIssue(params.epic.id);
413
+ const revision = jiraEpicRevision(epic);
414
+ const sourceBlocked = sourceBlock(params, epic);
415
+ if (jiraIsEpic2(epic) === jiraIsEpic2(params.epic))
416
+ ensureIssueWiki(services2.wiki, client, epic);
417
+ if (name === "jira_split_prepare") {
418
+ const metadata = state.drafts.some(
419
+ (draft2) => !draft2.receipt && draft2.verdict === "applicable"
420
+ ) ? await client.createMetadata?.(params.epic.fields.project.id, jiraIsEpic2(params.epic)) : void 0;
421
+ const drafts = [];
422
+ for (const draft2 of state.drafts) {
423
+ if (draft2.receipt) {
424
+ drafts.push(draft2);
425
+ continue;
426
+ }
427
+ const repository2 = params.repositories.find(
428
+ (candidate) => candidate.key === draft2.repositoryKey
429
+ );
430
+ if (!repository2) throw new Error("Draft refers to an unauthorized repository");
431
+ const mapping = await componentMapping(services2, params, repository2);
432
+ let typeBlocked = null;
433
+ if (draft2.verdict === "applicable") {
434
+ try {
435
+ if (!metadata) throw new Error("Jira ticket creation metadata unavailable");
436
+ resolveDraftType(metadata, params, draft2);
437
+ } catch (error) {
438
+ typeBlocked = error instanceof Error ? error.message : "Ticket type unavailable";
439
+ }
440
+ }
441
+ const blocked = sourceBlocked ?? typeBlocked ?? (draft2.verdict === "applicable" ? jiraTicketTextProblem(draft2.summary, draft2.description) : null) ?? (state.epicRevision && revision !== state.epicRevision ? "Source issue changed: request revision before approval" : draft2.verdict === "applicable" && !mapping.componentIds.length ? "Map this repository in Settings \u2192 Jira components, then refresh mappings" : draft2.verdict === "unresolved" ? "Assessment unresolved: revise or explicitly exclude" : draft2.verdict === "applicable" ? await repositoryBlock(services2, params, repository2, draft2) : null);
442
+ drafts.push({ ...draft2, ...mapping, blocked });
443
+ }
444
+ return {
445
+ drafts,
446
+ epic,
447
+ epicRevision: revision
448
+ };
449
+ }
450
+ const repositoryKey = stringArg2(args, "repositoryKey");
451
+ if (ctx.turn.turnId !== "publish_tickets" || !state.approved.includes(repositoryKey))
452
+ throw new Error("Ticket has no current operator approval");
453
+ const draft = state.drafts.find((candidate) => candidate.repositoryKey === repositoryKey);
454
+ const repository = params.repositories.find((candidate) => candidate.key === repositoryKey);
455
+ if (!draft || !repository || draft.excluded || draft.blocked || draft.verdict !== "applicable")
456
+ throw new Error("Ticket is not publishable");
457
+ if (!client.findSplitIssue) throw new Error("Jira issue reconciliation unavailable");
458
+ const findSplitIssue = client.findSplitIssue.bind(client);
459
+ const key = splitPublicationKey(params, repository);
460
+ const marker = `leitwerk-split-${key}`;
461
+ const binding = {
462
+ ...repository,
463
+ gitlabProfile: params.gitlabProfile,
464
+ sshProfile: params.sshProfile,
465
+ sourceIssueId: params.epic.id,
466
+ relationship: jiraIsEpic2(params.epic) ? "epic" : "subtask"
467
+ };
468
+ const reservation = { key, topicId: params.topicId, binding, externalId: null, url: null };
469
+ const existing = services2.publications.publication(key);
470
+ if (existing && (existing.topicId !== params.topicId || (existing.binding.sourceIssueId ?? existing.binding.epicId) !== binding.sourceIssueId || (existing.binding.relationship ?? "epic") !== binding.relationship || [
471
+ "origin",
472
+ "projectId",
473
+ "gitlabProfile",
474
+ "sshProfile",
475
+ "repoLocator",
476
+ "baseBranch"
477
+ ].some(
478
+ (field) => existing.binding[field] !== binding[field]
479
+ )))
480
+ throw new Error(
481
+ "Existing ticket publication has a different repository binding; reconcile before continuing"
482
+ );
483
+ const readRemote = async () => {
484
+ const recorded = services2.publications.publication(key);
485
+ const issue = recorded?.externalId ? await client.getIssue(
486
+ String(JSON.parse(recorded.externalId.slice(5))[1])
487
+ ) : await findSplitIssue(params.epic.fields.project.id, marker);
488
+ if (!issue) return null;
489
+ if (issue.fields.project.id !== params.epic.fields.project.id || !issue.fields.labels.includes(marker))
490
+ throw new Error("Uncorrelated Jira split receipt");
491
+ if (!await jiraSplitChildMatches(
492
+ client,
493
+ issue,
494
+ binding.sourceIssueId,
495
+ binding.relationship
496
+ ))
497
+ throw new Error("Created issue no longer belongs to this source issue");
498
+ const url = `${client.baseUrl}/browse/${encodeURIComponent(issue.key)}`;
499
+ if (!recorded) services2.publications.reservePublication(reservation);
500
+ services2.publications.finishPublication(
501
+ key,
502
+ jiraIssueExternalId(client.baseUrl, issue.id),
503
+ url
504
+ );
505
+ return { id: issue.id, key: issue.key, url };
506
+ };
507
+ const uncertainPublication = () => {
508
+ throw new Error(
509
+ `Jira creation outcome is uncertain. Find the ticket with label ${marker} and retry after it is searchable; another POST is blocked`
510
+ );
511
+ };
512
+ const ensureTicket = (execute) => ctx.externalWrites.ensure(
513
+ { writeType: "jira.create_issue", dedupKey: `jira-split:${key}` },
514
+ { reconcile: readRemote, execute, toMetadata: (value) => value }
515
+ );
516
+ const wantsTrigger = state.labels.includes("use-leitwerk");
517
+ const triggerPending = () => wantsTrigger && !services2.publications.publication(key)?.triggered;
518
+ const reconcileTrigger = async (id, recorded = false) => {
519
+ const { labels } = (await client.getIssue(id)).fields;
520
+ const triggered = services2.publications.publication(key)?.triggered || recorded || labels.includes("use-leitwerk") || labels.includes("leitwerk-done");
521
+ if (triggered) services2.publications.markPublicationTriggered(key);
522
+ return triggered;
523
+ };
524
+ let receipt = null;
525
+ if (existing) {
526
+ receipt = await ensureTicket(async () => uncertainPublication());
527
+ if (triggerPending()) await reconcileTrigger(receipt.id);
528
+ }
529
+ if (!receipt || triggerPending()) {
530
+ if (sourceBlocked) return { reviewRequired: sourceBlocked };
531
+ const mapping = await componentMapping(services2, params, repository);
532
+ if (revision !== state.epicRevision || mapping.mappingRevision !== draft.mappingRevision)
533
+ return {
534
+ reviewRequired: "Source issue or component mapping changed; review the batch again"
535
+ };
536
+ const blocked = await repositoryBlock(services2, params, repository, draft);
537
+ if (blocked) return { reviewRequired: blocked };
538
+ }
539
+ if (!receipt) {
540
+ assertJiraTicketText(draft.summary, draft.description);
541
+ parseLabels(state.labels.join(","));
542
+ if (!client.createIssueReceipt || !client.createMetadata)
543
+ throw new Error("Jira issue creation unavailable");
544
+ const createIssue = client.createIssueReceipt.bind(client);
545
+ const metadata = await client.createMetadata(
546
+ epic.fields.project.id,
547
+ jiraIsEpic2(params.epic)
548
+ );
549
+ const type = resolveDraftType(metadata, params, draft);
550
+ const fields = {
551
+ project: { id: epic.fields.project.id },
552
+ issuetype: { id: type.id },
553
+ summary: draft.summary,
554
+ description: markdownToJira(splitTicketDescription(params, repository, draft)),
555
+ components: draft.componentIds.map((id) => ({ id })),
556
+ labels: [...state.labels.filter((label) => label !== "use-leitwerk"), marker],
557
+ ...binding.relationship === "subtask" ? { parent: { id: epic.id } } : { [metadata.epicLinkField]: epic.key }
558
+ };
559
+ for (const [field, spec] of Object.entries(type.fields))
560
+ if (spec.required && !spec.hasDefaultValue && !(field in fields))
561
+ throw new Error(
562
+ `Jira requires field ${field}; configure its default before publishing`
563
+ );
564
+ receipt = await ensureTicket(async () => {
565
+ if (!services2.publications.reservePublication(reservation)) uncertainPublication();
566
+ let created;
567
+ try {
568
+ created = await createIssue(fields);
569
+ } catch (error) {
570
+ if (error instanceof JiraRequestError && [400, 401, 403, 404, 422].includes(error.status))
571
+ services2.publications.releaseRejectedPublication(key);
572
+ throw error;
573
+ }
574
+ const url = `${client.baseUrl}/browse/${encodeURIComponent(created.key)}`;
575
+ services2.publications.finishPublication(
576
+ key,
577
+ jiraIssueExternalId(client.baseUrl, created.id),
578
+ url
579
+ );
580
+ return { ...created, url };
581
+ });
582
+ }
583
+ if (wantsTrigger)
584
+ await ctx.externalWrites.ensure(
585
+ { writeType: "jira.split_trigger", dedupKey: `jira-split-trigger:${key}` },
586
+ {
587
+ reconcile: async (phase) => await reconcileTrigger(receipt.id, phase === "already_recorded") ? receipt : null,
588
+ execute: async () => {
589
+ await client.updateLabels(receipt.id, [], ["use-leitwerk"]);
590
+ services2.publications.markPublicationTriggered(key);
591
+ return receipt;
592
+ },
593
+ toMetadata: (receipt2) => receipt2
594
+ }
595
+ );
596
+ return { receipt };
597
+ }
598
+ });
599
+ }
600
+
601
+ // src/process.ts
602
+ var inspectionTools = [
603
+ "gitlab_inspect_project",
604
+ "gitlab_repository_tree",
605
+ "gitlab_repository_file",
606
+ "wiki_index",
607
+ "wiki_read",
608
+ "wiki_share"
609
+ ];
610
+ var draftShape = "{repositoryKey, verdict: applicable|not_applicable|already_compliant|unresolved, reason, evidence, revision: inspected commit SHA, summary, description: detailed change and acceptance criteria, issueType: Story|Task|Sub-task}";
611
+ var repositoryCodec = {
612
+ parse: (value) => value,
613
+ serialize: (value) => value
614
+ };
615
+ var draftCodec = { parse: parseDraft, serialize: (value) => value };
616
+ function requireCleanDraft(draft) {
617
+ if (draft.verdict === "applicable" && !draft.receipt && !draft.excluded)
618
+ assertJiraTicketText2(draft.summary, draft.description);
619
+ return draft;
620
+ }
621
+ function publicationState(state, input) {
622
+ const results = input;
623
+ return {
624
+ ...state,
625
+ approved: [],
626
+ drafts: state.drafts.map((draft) => {
627
+ const result = results.find((candidate) => candidate.repositoryKey === draft.repositoryKey);
628
+ return result?.receipt ? { ...draft, receipt: result.receipt } : result?.reviewRequired ? { ...draft, blocked: result.reviewRequired } : draft;
629
+ })
630
+ };
631
+ }
632
+ function recordPublication(outcome) {
633
+ return outcome.parameter("results", {
634
+ type: "array",
635
+ description: "Publication receipts",
636
+ items: { type: "object" }
637
+ }).effect(({ ctx, event }) => ({ state: publicationState(ctx.state, event.params.results) }));
638
+ }
639
+ function createSplitProcess(launcher2, watcher) {
640
+ return flow.process("jira_epic_split_process").displayName("Jira Issue Split").entry("read_epic").runtime({ repositoryCheckout: "on_demand" }).codecs({ params: splitParamsCodec, state: splitStateCodec }).initialState(initialSplitState).launcher(launcher2).watcher({
641
+ id: "epic_split",
642
+ label: "Jira issue splitting",
643
+ description: "Split issues labeled leitwerk-issue-split or leitwerk-epic-split into repository tickets",
644
+ source: watcher.source,
645
+ resolveLaunchConfig: watcher.resolve
646
+ }).repositoryCredentials(
647
+ ({ params, projects }) => projects.map((project) => ({
648
+ projectKey: project.key,
649
+ kind: "git_ssh",
650
+ credentialRef: params.sshProfile
651
+ }))
652
+ ).happyPath(
653
+ "read_epic",
654
+ "discover_candidates",
655
+ "assess_repository",
656
+ "prepare_review",
657
+ "batch_review",
658
+ "publish_tickets",
659
+ "complete_split"
660
+ ).turn(
661
+ flow.automatic("read_epic").description("Read source issue").integrationTools("jira_split_prepare").run(async (ctx) => ({
662
+ outcome: "read",
663
+ params: { prepared: await ctx.callIntegrationTool("jira_split_prepare", {}) }
664
+ })).outcome(
665
+ "read",
666
+ (outcome) => outcome.description("Source issue captured").parameter("prepared", { type: "object", description: "Captured source issue" }).effect(({ ctx, event }) => {
667
+ const prepared = event.params.prepared;
668
+ return {
669
+ state: { ...ctx.state, epic: prepared.epic, epicRevision: prepared.epicRevision }
670
+ };
671
+ }).to("discover_candidates")
672
+ )
673
+ ).turn(
674
+ flow.llm("discover_candidates").description("Discover repository candidates").freshPrimary().tools("read", "bash").integrationTools(...inspectionTools).askQuestions().buildPrompt(
675
+ (ctx) => `Read the source issue and identify repository candidates for its requirements. Inspect GitLab metadata/files; checkout_repository is available when needed. Every scoped repository needs a reasoned decision. Inaccessible or ambiguous repositories remain candidates for investigation; never silently exclude them. Inspection only: no code changes or pushes.
676
+ ${wikiInstructions}
677
+ Source issue: ${JSON.stringify(ctx.state.epic)}
678
+ Repositories: ${JSON.stringify(ctx.params.repositories)}`
679
+ ).outcomeTool(
680
+ "candidates_identified",
681
+ (outcome) => outcome.description("Record all discovery decisions").requiredString(
682
+ "decisions",
683
+ "JSON array: one {repositoryKey,candidate:boolean,reason} per scoped repository"
684
+ ).effect(({ ctx, event }) => {
685
+ const decisions = JSON.parse(String(event.params.decisions));
686
+ if (!Array.isArray(decisions) || decisions.length !== ctx.params.repositories.length || new Set(decisions.map((decision) => decision.repositoryKey)).size !== decisions.length || decisions.some(
687
+ (decision) => !ctx.params.repositories.some(
688
+ (repository) => repository.key === decision.repositoryKey
689
+ ) || typeof decision.candidate !== "boolean" || typeof decision.reason !== "string" || !decision.reason.trim()
690
+ ))
691
+ throw new Error("Provide one evidence-based decision for every scoped repository");
692
+ return {
693
+ state: {
694
+ ...ctx.state,
695
+ candidates: decisions.filter((decision) => decision.candidate).map((decision) => decision.repositoryKey),
696
+ drafts: decisions.filter((decision) => !decision.candidate).map(
697
+ (decision) => parseDraft({
698
+ ...decision,
699
+ verdict: "not_applicable",
700
+ evidence: decision.reason,
701
+ issueType: ctx.params.issueType
702
+ })
703
+ )
704
+ }
705
+ };
706
+ }).to("assess_repository")
707
+ )
708
+ ).turn(
709
+ flow.mappedLlm("assess_repository", {
710
+ items: ({ params, state }) => params.repositories.filter((repository) => state.candidates.includes(repository.key)),
711
+ itemCodec: repositoryCodec,
712
+ resultCodec: draftCodec,
713
+ key: ({ item }) => item.key,
714
+ label: ({ item }) => item.name
715
+ }).description("Assess repository applicability").freshPrimary().tools("read", "bash").integrationTools(...inspectionTools).askQuestions().buildPrompt(
716
+ (ctx) => `Determine whether this repository needs changes for the source issue's requirements. Use GitLab file reads and checkout_repository as needed. Do not change code or publish anything. Distinguish already compliant, not applicable, and unresolved; lack of access is unresolved. For an applicable repository prepare one ticket with concrete acceptance criteria, evidence and inspected commit. ${ctx.params.subtaskType ? `Use issueType Sub-task (${ctx.params.subtaskType.name}); Story and Task are not allowed.` : `Default issue type: ${ctx.params.issueType}; only Story or Task are allowed.`}
717
+ ${jiraTicketWritingInstructions}
718
+ ${wikiInstructions}
719
+ Source issue: ${JSON.stringify(ctx.state.epic)}
720
+ Repository: ${JSON.stringify(ctx.item)}
721
+ Return assessment JSON: ${draftShape}`
722
+ ).outcomeTool(
723
+ "repository_assessed",
724
+ (outcome) => outcome.description("Save repository assessment and draft").requiredString("assessment", `JSON ${draftShape}`).yield(({ ctx, event }) => {
725
+ const draft = parseDraft(JSON.parse(String(event.params.assessment)), ctx.params);
726
+ if (draft.repositoryKey !== ctx.item.key)
727
+ throw new Error("Assessment repository mismatch");
728
+ return requireCleanDraft(draft);
729
+ })
730
+ ).collect(({ state }, results) => ({
731
+ ...state,
732
+ drafts: [...state.drafts, ...results],
733
+ candidates: []
734
+ })).to("prepare_review")
735
+ ).turn(
736
+ flow.automatic("prepare_review").description("Prepare ticket batch").integrationTools("jira_split_prepare").run(async (ctx) => {
737
+ const prepared = await ctx.callIntegrationTool(
738
+ "jira_split_prepare",
739
+ {}
740
+ );
741
+ return {
742
+ outcome: "ready",
743
+ params: {
744
+ prepared,
745
+ batch: batchMarkdown(ctx.params, { ...ctx.state, drafts: prepared.drafts })
746
+ }
747
+ };
748
+ }).outcome(
749
+ "ready",
750
+ (outcome) => outcome.description("Batch ready for review").parameter("prepared", {
751
+ type: "object",
752
+ description: "Current mappings and source issue"
753
+ }).markdown("batch", { publish: true }).effect(({ ctx, event }) => {
754
+ const prepared = event.params.prepared;
755
+ return {
756
+ state: {
757
+ ...ctx.state,
758
+ drafts: prepared.drafts,
759
+ epic: prepared.epic,
760
+ approved: []
761
+ }
762
+ };
763
+ }).to("batch_review")
764
+ )
765
+ ).turn(
766
+ flow.human("batch_review").description("Review repository tickets").reviewProduct("batch").action(
767
+ "approve_batch",
768
+ (action) => action.label("Create approved tickets").form({
769
+ id: "split_approval",
770
+ title: "Publish repository tickets",
771
+ submitLabel: "Create tickets",
772
+ fields: [
773
+ {
774
+ id: "exclude",
775
+ label: "Repositories to exclude",
776
+ kind: "textarea",
777
+ description: "One repository path per line. Unresolved rows stay pending unless explicitly excluded."
778
+ },
779
+ {
780
+ id: "tasks",
781
+ label: "Create as Tasks",
782
+ kind: "textarea",
783
+ description: "Epic splits only: optional repository paths, one per line. Leave blank for subtask splits."
784
+ },
785
+ {
786
+ id: "labels",
787
+ label: "Ticket labels",
788
+ kind: "text",
789
+ primaryPrompt: true,
790
+ description: "Comma-separated labels. Include use-leitwerk only to start code changes. Blank keeps the displayed labels."
791
+ },
792
+ {
793
+ id: "clearLabels",
794
+ label: "Remove all selected ticket labels",
795
+ kind: "boolean"
796
+ }
797
+ ]
798
+ }).effect(({ ctx, input }) => {
799
+ const keys = (value) => {
800
+ const names = typeof value === "string" ? value.split(/[\s,]+/).filter(Boolean) : [];
801
+ return names.map((name) => {
802
+ const repository = ctx.params.repositories.find(
803
+ (candidate) => candidate.name === name
804
+ );
805
+ if (!repository) throw new Error(`Unknown repository: ${name}`);
806
+ return repository.key;
807
+ });
808
+ };
809
+ const excluded = keys(input.exclude), tasks = keys(input.tasks);
810
+ if (ctx.params.subtaskType && tasks.length)
811
+ throw new Error(
812
+ "Subtask splits cannot create Tasks; leave the Task overrides blank"
813
+ );
814
+ const drafts = ctx.state.drafts.map(
815
+ (draft) => draft.receipt ? draft : {
816
+ ...draft,
817
+ excluded: draft.excluded || excluded.includes(draft.repositoryKey),
818
+ issueType: tasks.includes(draft.repositoryKey) ? "Task" : draft.issueType
819
+ }
820
+ );
821
+ const labels = input.clearLabels === true ? [] : typeof input.labels === "string" && input.labels.trim() ? parseLabels(input.labels) : ctx.state.labels;
822
+ for (const draft of drafts) {
823
+ if (!draft.blocked) requireCleanDraft(draft);
824
+ }
825
+ return {
826
+ state: {
827
+ ...ctx.state,
828
+ drafts,
829
+ labels,
830
+ approved: drafts.filter(
831
+ (draft) => draft.verdict === "applicable" && !draft.blocked && !draft.excluded && !draft.receipt
832
+ ).map((draft) => draft.repositoryKey)
833
+ }
834
+ };
835
+ }).to("publish_tickets")
836
+ ).action(
837
+ "revise_batch",
838
+ (action) => action.label("Revise tickets or assessments").form({
839
+ id: "split_revision",
840
+ title: "Revise batch",
841
+ fields: [
842
+ {
843
+ id: "message",
844
+ label: "Instructions",
845
+ kind: "textarea",
846
+ required: true,
847
+ primaryPrompt: true
848
+ }
849
+ ]
850
+ }).effect(({ ctx, input }) => ({
851
+ state: { ...ctx.state, feedback: String(input.message ?? ""), approved: [] }
852
+ })).to("revise_drafts")
853
+ ).action(
854
+ "refresh_mappings",
855
+ (action) => action.label("Refresh component mappings").to("prepare_review")
856
+ ).action(
857
+ "exclude_remaining",
858
+ (action) => action.label("Finish without remaining tickets").effect(({ ctx }) => ({
859
+ state: {
860
+ ...ctx.state,
861
+ approved: [],
862
+ drafts: ctx.state.drafts.map(
863
+ (draft) => draft.receipt ? draft : { ...draft, excluded: true }
864
+ )
865
+ }
866
+ })).to("complete_split")
867
+ )
868
+ ).turn(
869
+ flow.llm("revise_drafts").description("Revise the ticket batch").tools("read", "bash").integrationTools(...inspectionTools, "jira_split_prepare").prepare(
870
+ async (ctx) => await ctx.callIntegrationTool("jira_split_prepare", {})
871
+ ).buildPrompt(
872
+ (ctx) => `Revise the unpublished repository assessments and ticket drafts using the operator feedback. Reinspect when the source issue or evidence changed. Preserve published rows and repository identities. Return every unpublished row in drafts JSON. ${ctx.params.subtaskType ? "Use issueType Sub-task for every row." : "Use issueType Story or Task for every row."} Do not create issues. ${jiraTicketWritingInstructions}
873
+ ${wikiInstructions}
874
+ Source issue: ${JSON.stringify(ctx.prepared.epic)}
875
+ Feedback: ${ctx.state.feedback}
876
+ Repositories: ${JSON.stringify(ctx.params.repositories)}
877
+ Current drafts: ${JSON.stringify(ctx.state.drafts)}
878
+ Each draft has shape ${draftShape}`
879
+ ).outcomeTool(
880
+ "drafts_revised",
881
+ (outcome) => outcome.description("Replace unpublished drafts").requiredString("drafts", "JSON array of all unpublished repository drafts").effect(({ ctx, event }) => {
882
+ const value = JSON.parse(String(event.params.drafts));
883
+ if (!Array.isArray(value)) throw new Error("Expected draft array");
884
+ const drafts = value.map((draft) => requireCleanDraft(parseDraft(draft, ctx.params)));
885
+ const pending = ctx.state.drafts.filter((draft) => !draft.receipt);
886
+ if (drafts.length !== pending.length || new Set(drafts.map((draft) => draft.repositoryKey)).size !== drafts.length || drafts.some(
887
+ (draft) => !pending.some((old) => old.repositoryKey === draft.repositoryKey)
888
+ ))
889
+ throw new Error("Preserve all unpublished repository identities");
890
+ const prepared = event.prepared;
891
+ return {
892
+ state: {
893
+ ...ctx.state,
894
+ drafts: [...ctx.state.drafts.filter((draft) => draft.receipt), ...drafts],
895
+ approved: [],
896
+ epic: prepared.epic,
897
+ epicRevision: prepared.epicRevision
898
+ }
899
+ };
900
+ }).to("prepare_review")
901
+ )
902
+ ).turn(
903
+ flow.automatic("publish_tickets").description("Create approved Jira tickets").integrationTools("jira_split_publish").run(async (ctx) => {
904
+ const results = [];
905
+ for (const repositoryKey of ctx.state.approved)
906
+ results.push({
907
+ repositoryKey,
908
+ ...asUnknownRecord2(
909
+ await ctx.callIntegrationTool("jira_split_publish", { repositoryKey })
910
+ )
911
+ });
912
+ const pending = publicationState(ctx.state, results).drafts.some(
913
+ (draft) => !draft.receipt && !draft.excluded && (draft.verdict === "applicable" || draft.verdict === "unresolved")
914
+ );
915
+ return { outcome: pending ? "published" : "finished", params: { results } };
916
+ }).outcome(
917
+ "published",
918
+ (outcome) => recordPublication(outcome).description("Partial ticket publication recorded").to("prepare_review")
919
+ ).outcome(
920
+ "finished",
921
+ (outcome) => recordPublication(outcome).description("All ticket dispositions recorded").to("complete_split")
922
+ )
923
+ ).turn(
924
+ flow.automatic("complete_split").description("Issue split result").run((ctx) => ({
925
+ outcome: "done",
926
+ params: { result: batchMarkdown(ctx.params, ctx.state) }
927
+ })).outcome(
928
+ "done",
929
+ (outcome) => outcome.description("Ticket batch finished").markdown("result", { publish: true }).complete()
930
+ )
931
+ ).define();
932
+ }
933
+
934
+ // src/index.ts
935
+ var services = null;
936
+ function configured() {
937
+ if (!services) throw new Error("Jira issue splitting is not configured");
938
+ return services;
939
+ }
940
+ var issueSplitSource = defineProcessWatcherSource({
941
+ // Retain the source identity used by existing watcher configurations.
942
+ id: "@leitwerk-dev/jira-epic-split.epic",
943
+ label: "Jira issue split label",
944
+ parseConfig(raw) {
945
+ const config = asUnknownRecord3(raw);
946
+ if (!config || typeof config.enabled !== "boolean" || !Array.isArray(config.jiraProjects) || !config.jiraProjects.length || config.jiraProjects.some((project) => typeof project !== "string" || !/^\d+$/.test(project)))
947
+ throw new Error("Issue split watcher requires enabled and explicit jiraProjects IDs");
948
+ for (const key of ["jiraProfile", "gitlabProfile", "sshProfile"]) stringArg3(config, key);
949
+ const pollInterval = config.pollInterval ?? "30s";
950
+ if (typeof pollInterval !== "string" || parseDurationMs(pollInterval, -1) <= 0)
951
+ throw new Error("Invalid issue split pollInterval");
952
+ parseSplitOptions(config);
953
+ return { enabled: config.enabled, config: { ...config, pollInterval } };
954
+ },
955
+ presentConfig: (config) => ({
956
+ targetSummary: `Jira ${config.jiraProfile} \xB7 ${config.jiraProjects.join(", ")}`,
957
+ details: [{ label: "Trigger", value: "leitwerk-issue-split (or leitwerk-epic-split)" }]
958
+ })
959
+ });
960
+ var launcher = {
961
+ id: "jira_epic_split_process.ui_launcher",
962
+ label: "Jira Issue Split",
963
+ description: "Prepare one repository ticket for each applicable GitLab repository",
964
+ visibility: "ui",
965
+ ui: {
966
+ card: {
967
+ title: "Jira Issue Split",
968
+ description: "Standardize changes across repositories with reviewed Jira tickets and a shared solution wiki."
969
+ },
970
+ launchConfigSchema: {
971
+ id: "jira_epic_split",
972
+ title: "Split a Jira issue",
973
+ submitLabel: "Analyze issue",
974
+ fields: [
975
+ { id: "jiraProfile", label: "Jira profile", kind: "select", required: true },
976
+ { id: "issue", label: "Issue key", kind: "text", required: true },
977
+ { id: "gitlabProfile", label: "GitLab profile", kind: "select", required: true },
978
+ { id: "sshProfile", label: "Git SSH profile", kind: "select", required: true },
979
+ {
980
+ id: "groups",
981
+ label: "GitLab groups",
982
+ kind: "textarea",
983
+ description: "Exact group paths, one per line; includes subgroups."
984
+ },
985
+ {
986
+ id: "projects",
987
+ label: "Additional GitLab projects",
988
+ kind: "textarea",
989
+ description: "Exact project paths, one per line."
990
+ },
991
+ { id: "excludeGroups", label: "Excluded groups", kind: "textarea" },
992
+ { id: "excludeProjects", label: "Excluded projects", kind: "textarea" },
993
+ {
994
+ id: "issueType",
995
+ label: "Epic child type",
996
+ description: "Applies to epics. Other issues create subtasks.",
997
+ kind: "select",
998
+ options: [
999
+ { value: "Story", label: "Story" },
1000
+ { value: "Task", label: "Task" }
1001
+ ]
1002
+ },
1003
+ {
1004
+ id: "subtaskIssueType",
1005
+ label: "Subtask issue type ID",
1006
+ kind: "text",
1007
+ description: "Optional when the project has one subtask type. Used for non-epic issues."
1008
+ },
1009
+ {
1010
+ id: "labels",
1011
+ label: "Labels for created tickets",
1012
+ kind: "text",
1013
+ description: "Optional comma-separated labels. Add use-leitwerk explicitly to make tickets eligible for code changes after review."
1014
+ }
1015
+ ]
1016
+ },
1017
+ resolveDefaults: () => ({
1018
+ issueType: "Story",
1019
+ labels: "",
1020
+ jiraProfile: configured().jira.profiles()[0] ?? "",
1021
+ gitlabProfile: configured().gitlab.profiles()[0] ?? "",
1022
+ sshProfile: configured().ssh.profiles()[0] ?? ""
1023
+ }),
1024
+ resolveOptions: () => ({
1025
+ jiraProfile: configured().jira.profiles().map((value) => ({ value, label: value })),
1026
+ gitlabProfile: configured().gitlab.profiles().map((value) => ({ value, label: value })),
1027
+ sshProfile: configured().ssh.profiles().map((value) => ({ value, label: value }))
1028
+ }),
1029
+ resolveRelaunchInput: (previousInput) => ({
1030
+ ...previousInput,
1031
+ issue: previousInput.issue ?? previousInput.epic
1032
+ }),
1033
+ async resolveLaunchConfig(input) {
1034
+ try {
1035
+ return { ok: true, launchConfig: await launchSplit(configured(), input) };
1036
+ } catch (error) {
1037
+ return {
1038
+ ok: false,
1039
+ errors: [
1040
+ {
1041
+ fieldId: "issue",
1042
+ code: "issue_split_invalid",
1043
+ message: error instanceof Error ? error.message : "Issue split launch unavailable"
1044
+ }
1045
+ ]
1046
+ };
1047
+ }
1048
+ }
1049
+ }
1050
+ };
1051
+ var jiraIssueSplitProcess = createSplitProcess(launcher, {
1052
+ source: issueSplitSource,
1053
+ async resolve(event) {
1054
+ const issue = event.issue;
1055
+ const launch = await launchSplit(configured(), { ...event, issue: issue.id });
1056
+ if (!jiraSplitEligible(launch.params.epic) || !event.jiraProjects.includes(launch.params.epic.fields.project.id))
1057
+ throw new Error("Issue is no longer eligible for splitting");
1058
+ return {
1059
+ ...launch,
1060
+ externalId: `epic-split:${jiraIssueExternalId2(launch.params.jiraBaseUrl, issue.id)}`
1061
+ };
1062
+ }
1063
+ });
1064
+ var extension = {
1065
+ manifest: {
1066
+ id: "jira-issue-split",
1067
+ version: "0.3.1",
1068
+ requires: ["jira", "gitlab", "git-ssh", "jira-gitlab-change"]
1069
+ },
1070
+ setupCatalog(api) {
1071
+ api.registerProcess(jiraIssueSplitProcess);
1072
+ },
1073
+ setupServer(api) {
1074
+ const jira = api.require(jiraIntegration), gitlab = api.require(gitlabIntegration), ssh = api.require(gitSshIntegration), settings = api.require(scopedSettingsCapability), wiki = api.require(topicWikiCapability), host = api.require(coreHostCapabilities.serverSetup);
1075
+ if (Array.isArray(jira) || Array.isArray(gitlab) || Array.isArray(ssh) || Array.isArray(settings) || Array.isArray(wiki) || Array.isArray(host))
1076
+ throw new Error("Issue split integration capabilities must be singular");
1077
+ services = { jira, gitlab, ssh, settings, wiki, publications: host.publications };
1078
+ wiki.registerProcessSource(jiraIssueSplitProcess.id, jiraWikiSource(wiki, jira));
1079
+ registerSplitTools(api, services);
1080
+ const shouldPoll = createPollSchedule();
1081
+ host.polling.create({
1082
+ id: "jira-issue-split",
1083
+ pollInterval: () => "5s",
1084
+ defaultIntervalMs: 5e3,
1085
+ isEnabled: () => true,
1086
+ async pollOnce() {
1087
+ const result = emptyPollResult();
1088
+ for (const watcher of host.processWatchers?.listBySource(issueSplitSource) ?? []) {
1089
+ const key = `${watcher.processId}:${watcher.watcherId}`;
1090
+ if (!watcher.enabled || !shouldPoll(key, String(watcher.config.pollInterval))) continue;
1091
+ try {
1092
+ const client = jira.client(String(watcher.config.jiraProfile));
1093
+ if (!client.searchSplitIssues)
1094
+ throw new Error("Jira issue split discovery unavailable");
1095
+ for (const issue of await client.searchSplitIssues(
1096
+ watcher.config.jiraProjects
1097
+ )) {
1098
+ const id = `epic-split:${jiraIssueExternalId2(client.baseUrl, issue.id)}`;
1099
+ const launched = await host.launchRuns.startWatcher(
1100
+ watcher,
1101
+ { ...watcher.config, issue },
1102
+ { idempotencyKey: id }
1103
+ );
1104
+ if (launched.error) result.errors.push(`${issue.key}: issue split admission failed`);
1105
+ else if (launched.process) result.created.push(id);
1106
+ else result.skipped.push(id);
1107
+ }
1108
+ } catch (error) {
1109
+ result.errors.push(
1110
+ error instanceof Error ? error.message : "Issue split discovery unavailable"
1111
+ );
1112
+ }
1113
+ }
1114
+ return result;
1115
+ }
1116
+ });
1117
+ api.onStop(() => {
1118
+ services = null;
1119
+ });
1120
+ }
1121
+ };
1122
+ var index_default = extension;
1123
+ export {
1124
+ index_default as default,
1125
+ issueSplitSource,
1126
+ jiraIssueSplitProcess
1127
+ };
1128
+ //# sourceMappingURL=index.js.map