@leitwerk-dev/jira-issue-split 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/src/index.ts ADDED
@@ -0,0 +1,256 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import { gitSshIntegration } from "@leitwerk-dev/git-ssh";
3
+ import { gitlabIntegration } from "@leitwerk-dev/gitlab";
4
+ import {
5
+ type JiraIssue,
6
+ jiraIntegration,
7
+ jiraIssueExternalId,
8
+ jiraSplitEligible,
9
+ jiraWikiSource,
10
+ } from "@leitwerk-dev/jira";
11
+ import {
12
+ coreHostCapabilities,
13
+ defineProcessWatcherSource,
14
+ type LeitwerkExtensionModule,
15
+ type ProcessLauncherDefinition,
16
+ scopedSettingsCapability,
17
+ stringArg,
18
+ } from "@leitwerk-dev/process-sdk";
19
+ import { createPollSchedule, emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
20
+ import { topicWikiCapability } from "@leitwerk-dev/wiki/integration";
21
+ import type { SplitParams } from "./model.js";
22
+ import { createSplitProcess } from "./process.js";
23
+ import {
24
+ launchSplit,
25
+ parseSplitOptions,
26
+ registerSplitTools,
27
+ type SplitServices,
28
+ } from "./services.js";
29
+
30
+ let services: SplitServices | null = null;
31
+ function configured(): SplitServices {
32
+ if (!services) throw new Error("Jira issue splitting is not configured");
33
+ return services;
34
+ }
35
+
36
+ /** @internal */
37
+ export const issueSplitSource = defineProcessWatcherSource<
38
+ Record<string, unknown>,
39
+ Record<string, unknown>
40
+ >({
41
+ // Retain the source identity used by existing watcher configurations.
42
+ id: "@leitwerk-dev/jira-epic-split.epic",
43
+ label: "Jira issue split label",
44
+ parseConfig(raw) {
45
+ const config = asUnknownRecord(raw);
46
+ if (
47
+ !config ||
48
+ typeof config.enabled !== "boolean" ||
49
+ !Array.isArray(config.jiraProjects) ||
50
+ !config.jiraProjects.length ||
51
+ config.jiraProjects.some((project) => typeof project !== "string" || !/^\d+$/.test(project))
52
+ )
53
+ throw new Error("Issue split watcher requires enabled and explicit jiraProjects IDs");
54
+ for (const key of ["jiraProfile", "gitlabProfile", "sshProfile"]) stringArg(config, key);
55
+ const pollInterval = config.pollInterval ?? "30s";
56
+ if (typeof pollInterval !== "string" || parseDurationMs(pollInterval, -1) <= 0)
57
+ throw new Error("Invalid issue split pollInterval");
58
+ parseSplitOptions(config);
59
+ return { enabled: config.enabled, config: { ...config, pollInterval } };
60
+ },
61
+ presentConfig: (config) => ({
62
+ targetSummary: `Jira ${config.jiraProfile} · ${(config.jiraProjects as string[]).join(", ")}`,
63
+ details: [{ label: "Trigger", value: "leitwerk-issue-split (or leitwerk-epic-split)" }],
64
+ }),
65
+ });
66
+
67
+ const launcher: ProcessLauncherDefinition<SplitParams> = {
68
+ id: "jira_epic_split_process.ui_launcher",
69
+ label: "Jira Issue Split",
70
+ description: "Prepare one repository ticket for each applicable GitLab repository",
71
+ visibility: "ui",
72
+ ui: {
73
+ card: {
74
+ title: "Jira Issue Split",
75
+ description:
76
+ "Standardize changes across repositories with reviewed Jira tickets and a shared solution wiki.",
77
+ },
78
+ launchConfigSchema: {
79
+ id: "jira_epic_split",
80
+ title: "Split a Jira issue",
81
+ submitLabel: "Analyze issue",
82
+ fields: [
83
+ { id: "jiraProfile", label: "Jira profile", kind: "select", required: true },
84
+ { id: "issue", label: "Issue key", kind: "text", required: true },
85
+ { id: "gitlabProfile", label: "GitLab profile", kind: "select", required: true },
86
+ { id: "sshProfile", label: "Git SSH profile", kind: "select", required: true },
87
+ {
88
+ id: "groups",
89
+ label: "GitLab groups",
90
+ kind: "textarea",
91
+ description: "Exact group paths, one per line; includes subgroups.",
92
+ },
93
+ {
94
+ id: "projects",
95
+ label: "Additional GitLab projects",
96
+ kind: "textarea",
97
+ description: "Exact project paths, one per line.",
98
+ },
99
+ { id: "excludeGroups", label: "Excluded groups", kind: "textarea" },
100
+ { id: "excludeProjects", label: "Excluded projects", kind: "textarea" },
101
+ {
102
+ id: "issueType",
103
+ label: "Epic child type",
104
+ description: "Applies to epics. Other issues create subtasks.",
105
+ kind: "select",
106
+ options: [
107
+ { value: "Story", label: "Story" },
108
+ { value: "Task", label: "Task" },
109
+ ],
110
+ },
111
+ {
112
+ id: "subtaskIssueType",
113
+ label: "Subtask issue type ID",
114
+ kind: "text",
115
+ description: "Optional when the project has one subtask type. Used for non-epic issues.",
116
+ },
117
+ {
118
+ id: "labels",
119
+ label: "Labels for created tickets",
120
+ kind: "text",
121
+ description:
122
+ "Optional comma-separated labels. Add use-leitwerk explicitly to make tickets eligible for code changes after review.",
123
+ },
124
+ ],
125
+ },
126
+ resolveDefaults: () => ({
127
+ issueType: "Story",
128
+ labels: "",
129
+ jiraProfile: configured().jira.profiles()[0] ?? "",
130
+ gitlabProfile: configured().gitlab.profiles()[0] ?? "",
131
+ sshProfile: configured().ssh.profiles()[0] ?? "",
132
+ }),
133
+ resolveOptions: () => ({
134
+ jiraProfile: configured()
135
+ .jira.profiles()
136
+ .map((value) => ({ value, label: value })),
137
+ gitlabProfile: configured()
138
+ .gitlab.profiles()
139
+ .map((value) => ({ value, label: value })),
140
+ sshProfile: configured()
141
+ .ssh.profiles()
142
+ .map((value) => ({ value, label: value })),
143
+ }),
144
+ resolveRelaunchInput: (previousInput) => ({
145
+ ...previousInput,
146
+ issue: previousInput.issue ?? previousInput.epic,
147
+ }),
148
+ async resolveLaunchConfig(input) {
149
+ try {
150
+ return { ok: true, launchConfig: await launchSplit(configured(), input) };
151
+ } catch (error) {
152
+ return {
153
+ ok: false,
154
+ errors: [
155
+ {
156
+ fieldId: "issue",
157
+ code: "issue_split_invalid",
158
+ message: error instanceof Error ? error.message : "Issue split launch unavailable",
159
+ },
160
+ ],
161
+ };
162
+ }
163
+ },
164
+ },
165
+ };
166
+
167
+ /** @internal */
168
+ export const jiraIssueSplitProcess = createSplitProcess(launcher, {
169
+ source: issueSplitSource,
170
+ async resolve(event) {
171
+ const issue = event.issue as JiraIssue;
172
+ const launch = await launchSplit(configured(), { ...event, issue: issue.id });
173
+ if (
174
+ !jiraSplitEligible(launch.params.epic) ||
175
+ !(event.jiraProjects as string[]).includes(launch.params.epic.fields.project.id)
176
+ )
177
+ throw new Error("Issue is no longer eligible for splitting");
178
+ return {
179
+ ...launch,
180
+ externalId: `epic-split:${jiraIssueExternalId(launch.params.jiraBaseUrl, issue.id)}`,
181
+ };
182
+ },
183
+ });
184
+
185
+ /** @internal */
186
+ const extension: LeitwerkExtensionModule = {
187
+ manifest: {
188
+ id: "jira-issue-split",
189
+ version: "0.3.1",
190
+ requires: ["jira", "gitlab", "git-ssh", "jira-gitlab-change"],
191
+ },
192
+ setupCatalog(api) {
193
+ api.registerProcess(jiraIssueSplitProcess);
194
+ },
195
+ setupServer(api) {
196
+ const jira = api.require(jiraIntegration),
197
+ gitlab = api.require(gitlabIntegration),
198
+ ssh = api.require(gitSshIntegration),
199
+ settings = api.require(scopedSettingsCapability),
200
+ wiki = api.require(topicWikiCapability),
201
+ host = api.require(coreHostCapabilities.serverSetup);
202
+ if (
203
+ Array.isArray(jira) ||
204
+ Array.isArray(gitlab) ||
205
+ Array.isArray(ssh) ||
206
+ Array.isArray(settings) ||
207
+ Array.isArray(wiki) ||
208
+ Array.isArray(host)
209
+ )
210
+ throw new Error("Issue split integration capabilities must be singular");
211
+ services = { jira, gitlab, ssh, settings, wiki, publications: host.publications };
212
+ wiki.registerProcessSource(jiraIssueSplitProcess.id, jiraWikiSource(wiki, jira));
213
+ registerSplitTools(api, services);
214
+ const shouldPoll = createPollSchedule();
215
+ host.polling.create({
216
+ id: "jira-issue-split",
217
+ pollInterval: () => "5s",
218
+ defaultIntervalMs: 5000,
219
+ isEnabled: () => true,
220
+ async pollOnce() {
221
+ const result = emptyPollResult();
222
+ for (const watcher of host.processWatchers?.listBySource(issueSplitSource) ?? []) {
223
+ const key = `${watcher.processId}:${watcher.watcherId}`;
224
+ if (!watcher.enabled || !shouldPoll(key, String(watcher.config.pollInterval))) continue;
225
+ try {
226
+ const client = jira.client(String(watcher.config.jiraProfile));
227
+ if (!client.searchSplitIssues)
228
+ throw new Error("Jira issue split discovery unavailable");
229
+ for (const issue of await client.searchSplitIssues(
230
+ watcher.config.jiraProjects as string[],
231
+ )) {
232
+ const id = `epic-split:${jiraIssueExternalId(client.baseUrl, issue.id)}`;
233
+ const launched = await host.launchRuns.startWatcher(
234
+ watcher,
235
+ { ...watcher.config, issue },
236
+ { idempotencyKey: id },
237
+ );
238
+ if (launched.error) result.errors.push(`${issue.key}: issue split admission failed`);
239
+ else if (launched.process) result.created.push(id);
240
+ else result.skipped.push(id);
241
+ }
242
+ } catch (error) {
243
+ result.errors.push(
244
+ error instanceof Error ? error.message : "Issue split discovery unavailable",
245
+ );
246
+ }
247
+ }
248
+ return result;
249
+ },
250
+ });
251
+ api.onStop(() => {
252
+ services = null;
253
+ });
254
+ },
255
+ };
256
+ export default extension;
package/src/model.ts ADDED
@@ -0,0 +1,236 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import { type JiraIssue, jiraIsEpic, ticketDescriptionMarkdown } from "@leitwerk-dev/jira";
3
+ import {
4
+ type Codec,
5
+ createEmptyStructuralProcessState,
6
+ type StructuralProcessState,
7
+ stringArg,
8
+ } from "@leitwerk-dev/process-sdk";
9
+
10
+ /** @internal */
11
+ export interface SplitRepository {
12
+ /** @internal */ key: string;
13
+ /** @internal */ name: string;
14
+ /** @internal */ projectId: number;
15
+ /** @internal */ origin: string;
16
+ /** @internal */ repoLocator: string;
17
+ /** @internal */ baseBranch: string;
18
+ }
19
+
20
+ /** @internal */
21
+ export interface SplitParams {
22
+ /** @internal */ jiraProfile: string;
23
+ /** @internal */ jiraBaseUrl: string;
24
+ /** @internal */ gitlabProfile: string;
25
+ /** @internal */ sshProfile: string;
26
+ /** @internal */ epic: JiraIssue;
27
+ /** @internal */ topicId: string;
28
+ /** @internal */ repositories: SplitRepository[];
29
+ /** @internal */ issueType: "Story" | "Task" | "Sub-task";
30
+ /** @internal */ subtaskType?: {
31
+ /** @internal */ id: string;
32
+ /** @internal */ name: string;
33
+ };
34
+ /** @internal */ labels: string[];
35
+ }
36
+
37
+ /** @internal */
38
+ export interface SplitDraft {
39
+ /** @internal */ repositoryKey: string;
40
+ /** @internal */ verdict: "applicable" | "not_applicable" | "already_compliant" | "unresolved";
41
+ /** @internal */ reason: string;
42
+ /** @internal */ evidence: string;
43
+ /** @internal */ revision: string;
44
+ /** @internal */ summary: string;
45
+ /** @internal */ description: string;
46
+ /** @internal */ issueType: SplitParams["issueType"];
47
+ /** @internal */ componentIds: string[];
48
+ /** @internal */ mappingRevision: string;
49
+ /** @internal */ blocked: string | null;
50
+ /** @internal */ excluded: boolean;
51
+ /** @internal */
52
+ receipt?: {
53
+ /** @internal */
54
+ id: string;
55
+ /** @internal */
56
+ key: string;
57
+ /** @internal */
58
+ url: string;
59
+ };
60
+ }
61
+
62
+ /** @internal */
63
+ export interface SplitState extends StructuralProcessState {
64
+ /** @internal */ candidates: string[];
65
+ /** @internal */ drafts: SplitDraft[];
66
+ /** @internal */ approved: string[];
67
+ /** @internal */ labels: string[];
68
+ /** @internal */ feedback: string;
69
+ /** @internal */ epicRevision: string;
70
+ /** @internal */ epic: JiraIssue | null;
71
+ }
72
+
73
+ /** @internal */
74
+ export function initialSplitState(params: SplitParams): SplitState {
75
+ return {
76
+ ...createEmptyStructuralProcessState(),
77
+ candidates: [],
78
+ drafts: [],
79
+ approved: [],
80
+ labels: params.labels,
81
+ feedback: "",
82
+ epicRevision: "",
83
+ epic: null,
84
+ };
85
+ }
86
+
87
+ /** @internal */
88
+ export function parseDraft(value: unknown, params?: SplitParams): SplitDraft {
89
+ const record = asUnknownRecord(value);
90
+ if (
91
+ !record ||
92
+ !["applicable", "not_applicable", "already_compliant", "unresolved"].includes(
93
+ String(record.verdict),
94
+ ) ||
95
+ !["Story", "Task", "Sub-task"].includes(String(record.issueType))
96
+ )
97
+ throw new Error("Invalid repository assessment");
98
+ const draft = {
99
+ repositoryKey: stringArg(record, "repositoryKey"),
100
+ verdict: record.verdict as SplitDraft["verdict"],
101
+ reason: stringArg(record, "reason"),
102
+ evidence: stringArg(record, "evidence"),
103
+ revision: typeof record.revision === "string" ? record.revision : "",
104
+ summary: typeof record.summary === "string" ? record.summary : "",
105
+ description: typeof record.description === "string" ? record.description : "",
106
+ issueType: record.issueType as SplitParams["issueType"],
107
+ componentIds: [] as string[],
108
+ mappingRevision: "",
109
+ blocked: null,
110
+ excluded: false,
111
+ };
112
+ if (
113
+ draft.verdict === "applicable" &&
114
+ (!draft.summary.trim() ||
115
+ !draft.description.trim() ||
116
+ !/^[a-f0-9]{40,64}$/i.test(draft.revision))
117
+ )
118
+ throw new Error("Applicable repositories require a ticket draft and inspected commit ID");
119
+ if (params && (draft.issueType === "Sub-task") !== Boolean(params.subtaskType))
120
+ throw new Error("Ticket type does not match the source issue's child relationship");
121
+ return draft;
122
+ }
123
+
124
+ /** @internal */
125
+ export const splitParamsCodec: Codec<SplitParams> = {
126
+ parse(value) {
127
+ const record = asUnknownRecord(value);
128
+ if (
129
+ !record ||
130
+ !Array.isArray(record.repositories) ||
131
+ !asUnknownRecord(record.epic) ||
132
+ !["Story", "Task", "Sub-task"].includes(String(record.issueType)) ||
133
+ !Array.isArray(record.labels) ||
134
+ record.labels.some((label) => typeof label !== "string")
135
+ )
136
+ throw new Error("Invalid issue split snapshot");
137
+ if (!jiraIsEpic(record.epic as JiraIssue)) {
138
+ const subtaskType = asUnknownRecord(record.subtaskType);
139
+ if (!subtaskType || record.issueType !== "Sub-task")
140
+ throw new Error("Issue split requires a retained subtask type");
141
+ stringArg(subtaskType, "id");
142
+ stringArg(subtaskType, "name");
143
+ } else if (record.issueType === "Sub-task") {
144
+ throw new Error("Epic children must be Stories or Tasks");
145
+ }
146
+ for (const key of ["jiraProfile", "jiraBaseUrl", "gitlabProfile", "sshProfile", "topicId"])
147
+ stringArg(record, key);
148
+ for (const candidate of record.repositories) {
149
+ const repository = asUnknownRecord(candidate);
150
+ if (
151
+ !repository ||
152
+ !Number.isSafeInteger(repository.projectId) ||
153
+ Number(repository.projectId) < 1
154
+ )
155
+ throw new Error("Invalid split repository");
156
+ for (const key of ["key", "name", "origin"]) stringArg(repository, key);
157
+ if (typeof repository.repoLocator !== "string" || typeof repository.baseBranch !== "string")
158
+ throw new Error("Invalid repository checkout binding");
159
+ }
160
+ if (
161
+ new Set(record.repositories.map((repository) => repository.key)).size !==
162
+ record.repositories.length
163
+ )
164
+ throw new Error("Duplicate split repository");
165
+ return record as unknown as SplitParams;
166
+ },
167
+ serialize: (value) => value,
168
+ };
169
+
170
+ /** @internal */
171
+ export const splitStateCodec: Codec<SplitState> = {
172
+ parse(value) {
173
+ const record = asUnknownRecord(value);
174
+ if (
175
+ !record ||
176
+ !Array.isArray(record.drafts) ||
177
+ !Array.isArray(record.candidates) ||
178
+ !Array.isArray(record.approved) ||
179
+ !Array.isArray(record.labels) ||
180
+ typeof record.epicRevision !== "string"
181
+ )
182
+ throw new Error("Invalid issue split state");
183
+ for (const values of [record.candidates, record.approved, record.labels])
184
+ if (
185
+ values.some((value) => typeof value !== "string") ||
186
+ new Set(values).size !== values.length
187
+ )
188
+ throw new Error("Invalid split selection");
189
+ for (const value of record.drafts) {
190
+ parseDraft(value);
191
+ if (
192
+ !Array.isArray(value.componentIds) ||
193
+ value.componentIds.some((id: unknown) => typeof id !== "string") ||
194
+ typeof value.mappingRevision !== "string" ||
195
+ typeof value.excluded !== "boolean" ||
196
+ (value.blocked !== null && typeof value.blocked !== "string")
197
+ )
198
+ throw new Error("Invalid persisted split draft");
199
+ if (value.receipt) for (const key of ["id", "key", "url"]) stringArg(value.receipt, key);
200
+ }
201
+ const drafts = record.drafts;
202
+ if (
203
+ new Set(drafts.map((draft) => draft.repositoryKey)).size !== drafts.length ||
204
+ record.approved.some((key) => !drafts.some((draft) => draft.repositoryKey === key))
205
+ )
206
+ throw new Error("Invalid approved split drafts");
207
+ return record as unknown as SplitState;
208
+ },
209
+ serialize: (value) => value,
210
+ };
211
+
212
+ /** @internal */
213
+ export function splitTicketDescription(
214
+ params: SplitParams,
215
+ repository: SplitRepository,
216
+ draft: SplitDraft,
217
+ ): string {
218
+ return ticketDescriptionMarkdown(draft.description, {
219
+ repositoryName: repository.name,
220
+ repositoryUrl: `${repository.origin.replace(/\/$/, "")}/${repository.name.split("/").map(encodeURIComponent).join("/")}`,
221
+ sourceKey: params.epic.key,
222
+ sourceUrl: `${params.jiraBaseUrl.replace(/\/$/, "")}/browse/${encodeURIComponent(params.epic.key)}`,
223
+ });
224
+ }
225
+
226
+ /** @internal */
227
+ export function batchMarkdown(params: SplitParams, state: SplitState): string {
228
+ return `# ${params.epic.key}: repository tickets\n\n[Shared solution wiki](/wiki/${params.topicId})\n\n${params.subtaskType ? `Subtask type: ${params.subtaskType.name} (${params.subtaskType.id}).\n\n` : ""}Labels selected for new tickets: ${state.labels.join(", ") || "none"}.\n\n${state.drafts
229
+ .map((draft) => {
230
+ const repository = params.repositories.find(
231
+ (candidate) => candidate.key === draft.repositoryKey,
232
+ );
233
+ return `## ${repository?.name ?? draft.repositoryKey}\n\n${draft.receipt ? `[${draft.receipt.key}](${draft.receipt.url}) — published` : draft.excluded ? "Excluded by operator" : `${draft.verdict}${draft.blocked ? ` — BLOCKED: ${draft.blocked}` : ""}`}\n\n${draft.reason}\n\n${draft.summary ? `### ${draft.issueType}: ${draft.summary}\n\n${repository ? splitTicketDescription(params, repository, draft) : draft.description}\n\nComponents: ${draft.componentIds.join(", ") || "mapping required"}\n\n` : ""}### Inspection evidence\n\n${draft.evidence}\n\nInspected revision: ${draft.revision || "unavailable"}`;
234
+ })
235
+ .join("\n\n")}`;
236
+ }