@leitwerk-dev/jira 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/testing.ts ADDED
@@ -0,0 +1,414 @@
1
+ import { readLocalJson, writeLocalJson } from "@leitwerk-dev/test-support/local-git";
2
+ import {
3
+ type JiraClientLike,
4
+ type JiraComment,
5
+ type JiraComponent,
6
+ type JiraCreateMetadata,
7
+ type JiraCreateProject,
8
+ type JiraIssue,
9
+ type JiraIssueReceipt,
10
+ type JiraProject,
11
+ type JiraRemoteLink,
12
+ type JiraTransition,
13
+ jiraEligible,
14
+ jiraSplitEligible,
15
+ } from "./client.js";
16
+
17
+ export { registerJiraTools } from "./tools.js";
18
+
19
+ function upsertRemoteLink(links: JiraRemoteLink[], input: Omit<JiraRemoteLink, "id">) {
20
+ const previous = links.find((link) => link.globalId === input.globalId);
21
+ const link = { ...structuredClone(input), id: previous?.id ?? links.length + 1 };
22
+ if (previous) links[links.indexOf(previous)] = link;
23
+ else links.push(link);
24
+ const result: Pick<JiraRemoteLink, "id"> = { id: link.id };
25
+ return result;
26
+ }
27
+
28
+ const workflowTransitions: JiraTransition[] = [
29
+ {
30
+ id: "31",
31
+ name: "Start work",
32
+ to: { id: "3", name: "In Progress", statusCategory: { key: "indeterminate" } },
33
+ },
34
+ {
35
+ id: "41",
36
+ name: "Request review",
37
+ to: { id: "4", name: "In Review", statusCategory: { key: "indeterminate" } },
38
+ },
39
+ {
40
+ id: "51",
41
+ name: "Verify change",
42
+ to: { id: "5", name: "In Verification", statusCategory: { key: "indeterminate" } },
43
+ },
44
+ ];
45
+
46
+ /** @internal */
47
+ export class LocalJiraSplitAdapter implements JiraClientLike {
48
+ /** @internal */ readonly baseUrl = "https://jira.test/context";
49
+ /** @internal */ readonly issues = new Map<string, JiraIssue>();
50
+ /** @internal */ readonly comments = new Map<string, JiraComment[]>();
51
+ /** @internal */ readonly remoteLinks = new Map<string, JiraRemoteLink[]>();
52
+ /** @internal */ transitions = structuredClone(workflowTransitions);
53
+ /** @internal */ readonly creations: Record<string, unknown>[] = [];
54
+ /** @internal */ loseNextCreateResponse = false;
55
+ /** @internal */ searchVisible = true;
56
+ /** @internal */ components: JiraComponent[] = [{ id: "200", name: "Service" }];
57
+ /** @internal */ epicLinkField: string | null = "customfield_100";
58
+ /** @internal */ issueTypes: JiraCreateMetadata["issueTypes"] = [
59
+ { id: "Story", name: "Story", subtask: false, fields: {} },
60
+ { id: "Task", name: "Task", subtask: false, fields: {} },
61
+ { id: "10003", name: "Sub-task", subtask: true, fields: {} },
62
+ ];
63
+
64
+ /** @internal */ seedIssue(issue: JiraIssue, epicKey?: string): void {
65
+ const stored = structuredClone(issue);
66
+ if (epicKey) Object.assign(stored.fields, { customfield_100: epicKey });
67
+ this.issues.set(issue.id, stored);
68
+ }
69
+ /** @internal */ async getIssue(id: string): Promise<JiraIssue> {
70
+ const issue =
71
+ this.issues.get(id) ?? [...this.issues.values()].find((candidate) => candidate.key === id);
72
+ if (!issue) throw new Error("Jira issue unavailable");
73
+ return structuredClone(issue);
74
+ }
75
+ /** @internal */ async listProjects(): Promise<JiraProject[]> {
76
+ return [
77
+ ...new Map(
78
+ [...this.issues.values()].map((issue) => [issue.fields.project.id, issue.fields.project]),
79
+ ).values(),
80
+ ];
81
+ }
82
+ /** @internal */ async listCreateProjects(projectId?: string): Promise<JiraCreateProject[]> {
83
+ return (await this.listProjects())
84
+ .filter((project) => !projectId || project.id === projectId)
85
+ .map((project) => ({
86
+ ...project,
87
+ issuetypes: this.issueTypes
88
+ .filter((type) => !type.subtask)
89
+ .map((type) => ({
90
+ ...type,
91
+ subtask: false,
92
+ fields: Object.fromEntries(
93
+ Object.entries(type.fields).map(([key, field]) => [
94
+ key,
95
+ {
96
+ ...field,
97
+ name: key,
98
+ required: field.required ?? false,
99
+ },
100
+ ]),
101
+ ),
102
+ })),
103
+ }));
104
+ }
105
+ /** @internal */ async listProjectIssues(projectId: string): Promise<JiraIssue[]> {
106
+ return structuredClone(
107
+ [...this.issues.values()].filter((issue) => issue.fields.project.id === projectId),
108
+ );
109
+ }
110
+ /** @internal */ async listComponents(): Promise<JiraComponent[]> {
111
+ return structuredClone(this.components);
112
+ }
113
+ /** @internal */ async searchIssues(projectIds: readonly string[], triggerLabel?: string) {
114
+ return [...this.issues.values()]
115
+ .filter(
116
+ (issue) =>
117
+ projectIds.includes(issue.fields.project.id) && jiraEligible(issue, triggerLabel),
118
+ )
119
+ .map((issue) => structuredClone(issue));
120
+ }
121
+ /** @internal */ async searchSplitIssues(projectIds: readonly string[]) {
122
+ return [...this.issues.values()]
123
+ .filter((issue) => projectIds.includes(issue.fields.project.id) && jiraSplitEligible(issue))
124
+ .map((issue) => structuredClone(issue));
125
+ }
126
+ /** @internal */ async getEpic(issue: JiraIssue): Promise<JiraIssue | null> {
127
+ if (issue.fields.issuetype?.name === "Epic") return issue;
128
+ if (!this.epicLinkField) return null;
129
+ const key = (issue.fields as unknown as Record<string, unknown>)[this.epicLinkField];
130
+ return typeof key === "string" ? this.getIssue(key) : null;
131
+ }
132
+ /** @internal */ async createMetadata(
133
+ _projectId: string,
134
+ includeEpicLink = true,
135
+ ): Promise<JiraCreateMetadata> {
136
+ if (includeEpicLink && !this.epicLinkField)
137
+ throw new Error("Splitting a Jira epic requires an Epic Link field");
138
+ return {
139
+ epicLinkField: includeEpicLink ? this.epicLinkField : null,
140
+ issueTypes: structuredClone(this.issueTypes),
141
+ };
142
+ }
143
+ /** @internal */ async createIssueReceipt(
144
+ fields: Record<string, unknown>,
145
+ ): Promise<JiraIssueReceipt> {
146
+ const { id, key } = await this.createIssue(fields);
147
+ return { id, key };
148
+ }
149
+ /** @internal */ async createIssue(fields: Record<string, unknown>): Promise<JiraIssue> {
150
+ const type = this.issueTypes.find(
151
+ (candidate) => candidate.id === (fields.issuetype as { id: string }).id,
152
+ );
153
+ if (!type) throw new Error("Unknown Jira issue type");
154
+ if (Boolean(type.subtask) !== Boolean(fields.parent))
155
+ throw new Error("Jira subtask creation requires its parent");
156
+ this.creations.push(structuredClone(fields));
157
+ const id = String(1000 + this.creations.length),
158
+ key = `APP-${id}`;
159
+ const project = (await this.listProjects()).find(
160
+ (candidate) => candidate.id === (fields.project as { id: string }).id,
161
+ );
162
+ if (!project) throw new Error("Unknown Jira project");
163
+ this.seedIssue(
164
+ {
165
+ id,
166
+ key,
167
+ fields: {
168
+ summary: String(fields.summary),
169
+ description: String(fields.description),
170
+ components: (fields.components as { id: string }[]).map(
171
+ ({ id }) => this.components.find((component) => component.id === id)!,
172
+ ),
173
+ labels: fields.labels as string[],
174
+ project,
175
+ issuetype: {
176
+ id: (fields.issuetype as { id: string }).id,
177
+ name: type.name,
178
+ subtask: type.subtask,
179
+ },
180
+ ...(fields.parent
181
+ ? { parent: await this.getIssue((fields.parent as { id: string }).id) }
182
+ : {}),
183
+ status: { statusCategory: { key: "new" } },
184
+ },
185
+ },
186
+ typeof fields.customfield_100 === "string" ? fields.customfield_100 : undefined,
187
+ );
188
+ if (this.loseNextCreateResponse) {
189
+ this.loseNextCreateResponse = false;
190
+ throw new Error("Response lost after Jira creation");
191
+ }
192
+ return this.getIssue(id);
193
+ }
194
+ /** @internal */ async findSplitIssue(projectId: string, marker: string) {
195
+ return this.searchVisible
196
+ ? structuredClone(
197
+ [...this.issues.values()].find(
198
+ (issue) =>
199
+ issue.fields.project.id === projectId && issue.fields.labels.includes(marker),
200
+ ) ?? null,
201
+ )
202
+ : null;
203
+ }
204
+ /** @internal */ async listComments(id: string) {
205
+ return structuredClone(this.comments.get(id) ?? []);
206
+ }
207
+ /** @internal */ async addComment(id: string, body: string): Promise<JiraComment> {
208
+ const comments = this.comments.get(id) ?? [];
209
+ const comment = { id: String(comments.length + 1), body };
210
+ comments.push(comment);
211
+ this.comments.set(id, comments);
212
+ return comment;
213
+ }
214
+ /** @internal */ async updateLabels(id: string, remove: string[], add: string[]) {
215
+ const issue = this.issues.get(id);
216
+ if (!issue) throw new Error("Unknown issue");
217
+ issue.fields.labels = [
218
+ ...new Set([...issue.fields.labels.filter((label) => !remove.includes(label)), ...add]),
219
+ ];
220
+ }
221
+ /** @internal */ async listRemoteLinks(id: string) {
222
+ return structuredClone(this.remoteLinks.get(id) ?? []);
223
+ }
224
+ /** @internal */ async upsertRemoteLink(id: string, input: Omit<JiraRemoteLink, "id">) {
225
+ const links = this.remoteLinks.get(id) ?? [];
226
+ const result = upsertRemoteLink(links, input);
227
+ this.remoteLinks.set(id, links);
228
+ return result;
229
+ }
230
+ /** @internal */ async listTransitions(_id: string) {
231
+ return structuredClone(this.transitions);
232
+ }
233
+ /** @internal */ async transitionIssue(id: string, transitionId: string) {
234
+ const issue = this.issues.get(id);
235
+ const transition = this.transitions.find((transition) => transition.id === transitionId);
236
+ if (!issue || !transition) throw new Error("Jira transition unavailable");
237
+ issue.fields.status = structuredClone(transition.to);
238
+ }
239
+ }
240
+
241
+ /** @internal */
242
+ export class LocalJiraAdapter {
243
+ /** @internal */
244
+ readonly state: {
245
+ /** @internal */
246
+ version: number;
247
+ /** @internal */
248
+ projects: JiraCreateProject[];
249
+ /** @internal */
250
+ issues: JiraIssue[];
251
+ /** @internal */
252
+ comments: Record<string, JiraComment[]>;
253
+ /** @internal */
254
+ remoteLinks: Record<string, JiraRemoteLink[]>;
255
+ };
256
+ /** @internal */
257
+ loseNextIssueResponse = false;
258
+ /** @internal */
259
+ constructor(
260
+ /** @internal */ readonly root: string,
261
+ /** @internal */ readonly baseUrl = "https://jira.test",
262
+ ) {
263
+ this.state = readLocalJson(root, "jira.json", {
264
+ version: 1,
265
+ projects: [],
266
+ issues: [],
267
+ comments: {},
268
+ remoteLinks: {},
269
+ });
270
+ this.state.remoteLinks ??= {};
271
+ }
272
+ /** @internal */
273
+ save(): void {
274
+ writeLocalJson(this.root, "jira.json", this.state);
275
+ }
276
+ /** @internal */
277
+ seed(project: JiraCreateProject): void {
278
+ if (this.state.projects.some((candidate) => candidate.id === project.id)) return;
279
+ this.state.projects.push(structuredClone(project));
280
+ this.save();
281
+ }
282
+ /** @internal */
283
+ client(): JiraClientLike {
284
+ return {
285
+ ...localJiraIssueClient(this.state, () => this.save()),
286
+ baseUrl: this.baseUrl,
287
+ listProjects: async () => structuredClone(this.state.projects),
288
+ listCreateProjects: async (id) =>
289
+ structuredClone(this.state.projects.filter((project) => !id || project.id === id)),
290
+ listComponents: async () => [],
291
+ searchIssues: async (ids) =>
292
+ structuredClone(this.state.issues.filter((issue) => ids.includes(issue.fields.project.id))),
293
+ listProjectIssues: async (id) =>
294
+ structuredClone(this.state.issues.filter((issue) => issue.fields.project.id === id)),
295
+ searchSplitIssues: async (ids) =>
296
+ structuredClone(
297
+ this.state.issues.filter(
298
+ (issue) => ids.includes(issue.fields.project.id) && jiraSplitEligible(issue),
299
+ ),
300
+ ),
301
+ getEpic: async (issue) =>
302
+ issue.fields.issuetype?.name === "Epic" ? structuredClone(issue) : null,
303
+ createMetadata: async (id, includeEpicLink = true) => {
304
+ if (includeEpicLink)
305
+ throw new Error("Local ticket creation does not configure an Epic Link field");
306
+ const project = this.state.projects.find((project) => project.id === id);
307
+ if (!project) throw new Error("Unknown local Jira project");
308
+ return { epicLinkField: null, issueTypes: structuredClone(project.issuetypes) };
309
+ },
310
+ findSplitIssue: async (id, marker) => {
311
+ const matches = this.state.issues.filter(
312
+ (issue) => issue.fields.project.id === id && issue.fields.labels.includes(marker),
313
+ );
314
+ if (matches.length > 1) throw new Error("Multiple Jira tickets share the split identity");
315
+ return structuredClone(matches[0] ?? null);
316
+ },
317
+ createIssueReceipt: async (fields, signal) => {
318
+ const { id, key } = await this.client().createIssue(fields, signal);
319
+ return { id, key };
320
+ },
321
+ createIssue: async (fields) => {
322
+ const project = this.state.projects.find(
323
+ (project) => project.id === (fields.project as { id: string }).id,
324
+ );
325
+ if (!project) throw new Error("Unknown local Jira project");
326
+ const issueType = project.issuetypes.find(
327
+ (type) => type.id === (fields.issuetype as { id: string }).id,
328
+ );
329
+ if (!issueType) throw new Error("Unknown local Jira issue type");
330
+ for (const key of Object.keys(fields)) {
331
+ if (!["project", "issuetype"].includes(key) && !Object.hasOwn(issueType.fields, key))
332
+ throw new Error(`Jira field '${key}' is not on the create screen`);
333
+ }
334
+ const created: JiraIssue = {
335
+ id: String(this.state.issues.length + 1),
336
+ key: `${project.key}-${this.state.issues.filter((issue) => issue.fields.project.id === project.id).length + 1}`,
337
+ fields: {
338
+ ...fields,
339
+ summary: String(fields.summary),
340
+ description: String(fields.description),
341
+ labels: (fields.labels as string[] | undefined) ?? [],
342
+ project,
343
+ components: [],
344
+ status: { statusCategory: { key: "new" } },
345
+ },
346
+ };
347
+ this.state.issues.push(created);
348
+ this.save();
349
+ if (this.loseNextIssueResponse) {
350
+ this.loseNextIssueResponse = false;
351
+ throw new Error("Response lost after issue write");
352
+ }
353
+ return structuredClone(created);
354
+ },
355
+ };
356
+ }
357
+ }
358
+
359
+ /** @internal */
360
+ export function localJiraIssueClient(
361
+ state: Pick<LocalJiraAdapter["state"], "issues" | "comments"> &
362
+ Partial<Pick<LocalJiraAdapter["state"], "remoteLinks">>,
363
+ save: () => void,
364
+ ): Pick<
365
+ JiraClientLike,
366
+ | "getIssue"
367
+ | "listComments"
368
+ | "addComment"
369
+ | "updateLabels"
370
+ | "listRemoteLinks"
371
+ | "upsertRemoteLink"
372
+ | "listTransitions"
373
+ | "transitionIssue"
374
+ > {
375
+ const issue = (id: string) => {
376
+ const found = state.issues.find((issue) => issue.id === id || issue.key === id);
377
+ if (!found) throw new Error("Unknown local Jira issue");
378
+ return found;
379
+ };
380
+ return {
381
+ getIssue: async (id) => structuredClone(issue(id)),
382
+ listComments: async (id) => structuredClone(state.comments[issue(id).id] ?? []),
383
+ addComment: async (id, body) => {
384
+ state.comments[issue(id).id] ??= [];
385
+ const comments = state.comments[issue(id).id];
386
+ const comment = { id: String(comments.length + 1), body };
387
+ comments.push(comment);
388
+ save();
389
+ return structuredClone(comment);
390
+ },
391
+ updateLabels: async (id, remove, add) => {
392
+ const current = issue(id);
393
+ current.fields.labels = [
394
+ ...new Set([...current.fields.labels.filter((label) => !remove.includes(label)), ...add]),
395
+ ];
396
+ save();
397
+ },
398
+ listRemoteLinks: async (id) => structuredClone(state.remoteLinks?.[issue(id).id] ?? []),
399
+ upsertRemoteLink: async (id, input) => {
400
+ state.remoteLinks ??= {};
401
+ state.remoteLinks[issue(id).id] ??= [];
402
+ const result = upsertRemoteLink(state.remoteLinks[issue(id).id], input);
403
+ save();
404
+ return result;
405
+ },
406
+ listTransitions: async () => structuredClone(workflowTransitions),
407
+ transitionIssue: async (id, transitionId) => {
408
+ const transition = workflowTransitions.find((candidate) => candidate.id === transitionId);
409
+ if (!transition) throw new Error("Jira transition unavailable");
410
+ issue(id).fields.status = structuredClone(transition.to);
411
+ save();
412
+ },
413
+ };
414
+ }
@@ -0,0 +1,219 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ listTicketDestinations,
4
+ objectArg,
5
+ parseTicketDestinationId,
6
+ type ServerExtensionAPI,
7
+ stringArg,
8
+ type TicketCreationConfig,
9
+ type TicketCreationDestinationProvider,
10
+ type TicketCreationDestinationSnapshot,
11
+ ticketDestinationId,
12
+ ticketLabelNames,
13
+ } from "@leitwerk-dev/process-sdk";
14
+ import type { JiraCreateProject } from "./client.js";
15
+ import type { JiraIntegration } from "./index.js";
16
+ import { markdownToJira } from "./markdown.js";
17
+
18
+ const reservedFields = ["project", "issuetype", "summary", "description", "labels"];
19
+
20
+ function destinationData(snapshot: TicketCreationDestinationSnapshot) {
21
+ const data = objectArg(snapshot.data);
22
+ return {
23
+ profile: stringArg(data, "profile"),
24
+ baseUrl: stringArg(data, "baseUrl"),
25
+ projectId: stringArg(data, "projectId"),
26
+ projectKey: stringArg(data, "projectKey"),
27
+ issueTypeId: stringArg(data, "issueTypeId"),
28
+ defaultLabels: ticketLabelNames(data.defaultLabels),
29
+ };
30
+ }
31
+
32
+ function validateLabels(issueType: JiraCreateProject["issuetypes"][number], labels: string[]) {
33
+ if (labels.length && !Object.hasOwn(issueType.fields, "labels"))
34
+ throw new Error(
35
+ "The selected Jira issue type does not support labels on its create screen; omit labels and set ticket_creation.default_labels to []",
36
+ );
37
+ }
38
+
39
+ /** @internal */
40
+ export function registerJiraTicketCreation(
41
+ api: ServerExtensionAPI,
42
+ integration: JiraIntegration,
43
+ config: TicketCreationConfig,
44
+ ): void {
45
+ if (!config.enabled) return;
46
+ const summary = (
47
+ profile: string,
48
+ project: JiraCreateProject,
49
+ issueType: JiraCreateProject["issuetypes"][number],
50
+ ) => ({
51
+ id: `${ticketDestinationId(profile, project.id)}.${issueType.id}`,
52
+ displayName: `${project.key} · ${project.name} / ${issueType.name}`,
53
+ group: `${profile} · ${new URL(integration.client(profile).baseUrl).host}`,
54
+ description: `Issue type: ${issueType.name}. Default labels: ${config.defaultLabels.join(", ") || "none"}. Additional fields: ${JSON.stringify(Object.fromEntries(Object.entries(issueType.fields).filter(([key]) => !reservedFields.includes(key))))}`,
55
+ });
56
+ const currentDestination = async (
57
+ data: Omit<ReturnType<typeof destinationData>, "projectKey"> & { projectKey?: string },
58
+ signal?: AbortSignal,
59
+ ) => {
60
+ const client = integration.client(data.profile);
61
+ if (client.baseUrl !== data.baseUrl) throw new Error("Jira profile installation changed");
62
+ const project = (await client.listCreateProjects(data.projectId, signal)).find(
63
+ (project) => project.id === data.projectId,
64
+ );
65
+ const issueType = project?.issuetypes.find(
66
+ (type) => type.id === data.issueTypeId && !type.subtask,
67
+ );
68
+ if (
69
+ !project ||
70
+ (data.projectKey !== undefined && project.key !== data.projectKey) ||
71
+ !issueType
72
+ )
73
+ throw new Error(
74
+ "The selected Jira project or issue type is no longer available for creation",
75
+ );
76
+ validateLabels(issueType, data.defaultLabels);
77
+ return { client, project, issueType };
78
+ };
79
+ const destinations: TicketCreationDestinationProvider = {
80
+ list() {
81
+ return listTicketDestinations("Jira", integration.profiles(), async (profile) =>
82
+ (await integration.client(profile).listCreateProjects()).flatMap((project) =>
83
+ project.issuetypes
84
+ .filter((type) => !type.subtask)
85
+ .map((type) => summary(profile, project, type)),
86
+ ),
87
+ );
88
+ },
89
+ async resolve({ destinationId }) {
90
+ const separator = destinationId.lastIndexOf(".");
91
+ const { profile, resourceId: projectId } = parseTicketDestinationId(
92
+ destinationId.slice(0, separator),
93
+ );
94
+ const issueTypeId = destinationId.slice(separator + 1);
95
+ if (!/^[1-9]\d*$/.test(issueTypeId)) throw new Error("Unknown Jira issue type");
96
+ const client = integration.client(profile);
97
+ const data = {
98
+ profile,
99
+ baseUrl: client.baseUrl,
100
+ projectId,
101
+ issueTypeId,
102
+ defaultLabels: config.defaultLabels,
103
+ };
104
+ const { project, issueType } = await currentDestination(data);
105
+ const destination = summary(profile, project, issueType);
106
+ return {
107
+ summary: {
108
+ ...destination,
109
+ description: `Default labels: ${config.defaultLabels.join(", ") || "none"}`,
110
+ },
111
+ data: { ...data, projectKey: project.key },
112
+ agentContext: destination.description,
113
+ };
114
+ },
115
+ async validate(snapshot) {
116
+ await currentDestination(destinationData(snapshot));
117
+ },
118
+ };
119
+ api.tool<Record<string, unknown>>({
120
+ name: "jira_create_issue",
121
+ description:
122
+ "Create one Jira issue with the selected project's issue type. Write the description in Markdown; the publisher converts it to Jira wiki markup. Supply any required additional fields from its destination metadata; ask the operator when a value is unknown.",
123
+ parameters: {
124
+ type: "object",
125
+ properties: {
126
+ summary: { type: "string", description: "Concise issue title" },
127
+ description: {
128
+ type: "string",
129
+ description: "Complete issue description in Markdown",
130
+ },
131
+ labels: { type: "array", items: { type: "string" } },
132
+ fields: {
133
+ type: "object",
134
+ description:
135
+ "Additional Jira create fields, keyed by metadata field ID, such as components or customfield_10001. Do not include project, issuetype, summary, description or labels.",
136
+ },
137
+ },
138
+ required: ["summary", "description"],
139
+ },
140
+ capability: {
141
+ kind: "ticket_creation",
142
+ displayName: "Jira",
143
+ processId: "ticket_creation_process",
144
+ startTurnId: "create_ticket",
145
+ titlePath: "/summary",
146
+ descriptionPath: "/description",
147
+ descriptionFormat: "markdown",
148
+ destinations,
149
+ },
150
+ async execute(ctx, args) {
151
+ if (!ctx.ticketDestination) throw new Error("A Jira ticket destination is required");
152
+ ctx.signal.throwIfAborted();
153
+ const target = destinationData(ctx.ticketDestination);
154
+ const { client, issueType } = await currentDestination(target, ctx.signal);
155
+ ctx.signal.throwIfAborted();
156
+ const summary = stringArg(args, "summary");
157
+ const description = stringArg(args, "description");
158
+ const labels = [...new Set([...target.defaultLabels, ...ticketLabelNames(args.labels)])];
159
+ validateLabels(issueType, labels);
160
+ if (labels.some((label) => /\s/.test(label)))
161
+ throw new Error("Jira labels cannot contain spaces");
162
+ const fields = args.fields === undefined ? {} : objectArg(args.fields);
163
+ for (const key of Object.keys(fields)) {
164
+ if (reservedFields.includes(key) || !Object.hasOwn(issueType.fields, key))
165
+ throw new Error(
166
+ `Jira field '${key}' is not an additional create field for this issue type`,
167
+ );
168
+ }
169
+ for (const [key, field] of Object.entries(issueType.fields)) {
170
+ if (
171
+ field.required &&
172
+ !field.hasDefaultValue &&
173
+ !reservedFields.includes(key) &&
174
+ (fields[key] == null ||
175
+ fields[key] === "" ||
176
+ (Array.isArray(fields[key]) && fields[key].length === 0))
177
+ )
178
+ throw new Error(
179
+ `Jira requires ${field.name} (${key}); request this value before creating the issue`,
180
+ );
181
+ }
182
+ const digest = createHash("sha256").update(ctx.idempotencyKey).digest("hex");
183
+ const marker = `leitwerk-ticket-write:${digest}`;
184
+ const issue = await ctx.externalWrites.ensure(
185
+ { writeType: "jira.create_issue", dedupKey: ctx.idempotencyKey },
186
+ {
187
+ reconcile: async () =>
188
+ (await client.listProjectIssues(target.projectId, ctx.signal)).find((issue) =>
189
+ issue.fields.description?.includes(marker),
190
+ ) ?? null,
191
+ execute: () => {
192
+ ctx.signal.throwIfAborted();
193
+ return client.createIssue(
194
+ {
195
+ ...fields,
196
+ project: { id: target.projectId },
197
+ issuetype: { id: target.issueTypeId },
198
+ summary,
199
+ description: `${markdownToJira(description)}\n\n{noformat}${marker}{noformat}`,
200
+ ...(labels.length ? { labels } : {}),
201
+ },
202
+ ctx.signal,
203
+ );
204
+ },
205
+ toMetadata: (issue) => ({
206
+ id: issue.id,
207
+ key: issue.key,
208
+ url: `${target.baseUrl}/browse/${encodeURIComponent(issue.key)}`,
209
+ }),
210
+ },
211
+ );
212
+ return {
213
+ externalId: issue.key,
214
+ url: `${target.baseUrl}/browse/${encodeURIComponent(issue.key)}`,
215
+ result: issue,
216
+ };
217
+ },
218
+ });
219
+ }
@@ -0,0 +1,40 @@
1
+ import { SafeOutcomePlanningError } from "@leitwerk-dev/process-sdk";
2
+
3
+ /** @internal */
4
+ export const jiraTicketWritingInstructions =
5
+ "Write summary and description as a normal standalone Jira task for its assignee, using Markdown for the description. Explain the work and acceptance criteria in plain language; retain concrete file paths, prerequisites, and validation steps when needed. Keep evidence, inspected revisions, repository keys, and other tracking data in the separate evidence fields. Do not put raw commit hashes, internal IDs, split identities, solution-wiki references, or model citation tokens in the summary or description. Refer to repositories by their readable names and Jira issues by their issue keys. The publisher adds repository and source-issue links. When revising an existing ticket, preserve useful task details and human notes, and omit any previous generated tracking footer.";
6
+
7
+ // These are references produced by the tools and publisher, not task requirements.
8
+ const internalReference =
9
+ /\bleitwerk-split-[\w-]+\b|\brepo_\d+\b|\bagt_[a-z0-9]+\b|\b[a-f0-9]{40,64}\b|\bturn\d+(?:file|search|view|fetch)\d+\b|[\uE200-\uE202]|【[^】]*(?:†|turn\d+|repo_\d+)[^】]*】|Leitwerk split identity\s*:|(?:Source issue )?solution wiki\s*:/i;
10
+
11
+ /** @internal */
12
+ export function jiraTicketTextProblem(summary: string, description: string): string | null {
13
+ return internalReference.test(`${summary}\n${description}`)
14
+ ? "Revise the ticket summary and description to remove internal references; keep evidence and tracking IDs in the separate evidence fields, then review the revised ticket."
15
+ : null;
16
+ }
17
+
18
+ /** @internal */
19
+ export function assertJiraTicketText(summary: string, description: string): void {
20
+ const problem = jiraTicketTextProblem(summary, description);
21
+ if (problem) throw new SafeOutcomePlanningError("jira_ticket_internal_reference", problem);
22
+ }
23
+
24
+ /** @internal */
25
+ export function ticketDescriptionMarkdown(
26
+ description: string,
27
+ links: {
28
+ /** @internal */
29
+ repositoryName: string;
30
+ /** @internal */
31
+ repositoryUrl: string;
32
+ /** @internal */
33
+ sourceKey: string;
34
+ /** @internal */
35
+ sourceUrl: string;
36
+ },
37
+ ): string {
38
+ const label = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
39
+ return `${description.trim()}\n\nRepository: [${label(links.repositoryName)}](${links.repositoryUrl})\n\nSource issue: [${label(links.sourceKey)}](${links.sourceUrl})`;
40
+ }