@leitwerk-dev/jira 0.0.0-stage → 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,389 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import {
3
+ coreHostCapabilities,
4
+ createCapabilityToken,
5
+ createExternalSourcePollReporter,
6
+ defineProcessWatcherSource,
7
+ type ExternalActionSource,
8
+ type LeitwerkExtensionModule,
9
+ parseProcessWatcherLaunchModelConfig,
10
+ parseTicketCreationConfig,
11
+ type ServerExtensionAPI,
12
+ scopedSettingsCapability,
13
+ type TicketCreationConfig,
14
+ } from "@leitwerk-dev/process-sdk";
15
+ import { createPollSchedule, emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
16
+ import {
17
+ JiraClient,
18
+ type JiraClientLike,
19
+ type JiraIssue,
20
+ jiraEligible,
21
+ jiraIssueExternalId,
22
+ jiraTriggerLabel,
23
+ parseJiraProfiles,
24
+ } from "./client.js";
25
+ import { registerJiraTicketCreation } from "./ticket-creation.js";
26
+ import { registerJiraTools } from "./tools.js";
27
+
28
+ export * from "./client.js";
29
+ export { jiraToMarkdown, markdownToJira } from "./markdown.js";
30
+ export {
31
+ assertJiraTicketText,
32
+ jiraTicketTextProblem,
33
+ jiraTicketWritingInstructions,
34
+ ticketDescriptionMarkdown,
35
+ } from "./ticket-text.js";
36
+ export { ensureIssueWiki, jiraEpicRevision, jiraWikiSource } from "./wiki.js";
37
+
38
+ /** @public */
39
+ export interface JiraIntegration {
40
+ /** @internal */
41
+ profiles(): readonly string[];
42
+
43
+ /** @internal */
44
+ client(profile: string): JiraClientLike;
45
+ }
46
+
47
+ /** @public */
48
+ export const jiraIntegration = createCapabilityToken<JiraIntegration>(
49
+ "@leitwerk-dev/jira.integration",
50
+ );
51
+
52
+ /** Configured project discovery shared by Jira-backed Settings and launchers. @public */
53
+ export const jiraProjectDiscovery = createCapabilityToken<{
54
+ /** @public */ projects(profile: string): Promise<readonly import("./client.js").JiraProject[]>;
55
+ /** @public */ includesProject(
56
+ subject: import("@leitwerk-dev/domain").SettingsSubject | undefined,
57
+ ): boolean;
58
+ }>("@leitwerk-dev/jira.project-discovery");
59
+
60
+ /** @public */
61
+ export const jiraSubjectIdentity = (baseUrl: string, id: string) => JSON.stringify([baseUrl, id]);
62
+
63
+ /** @public */
64
+ export interface JiraWatcherConfig {
65
+ /** @internal */
66
+ label?: string;
67
+ /** @internal */
68
+ profile: string;
69
+
70
+ /** @internal */
71
+ projects: string[];
72
+
73
+ /** @internal */
74
+ pollInterval: string;
75
+ }
76
+
77
+ /** @public */
78
+ export interface JiraWatcherEvent {
79
+ /** @internal */
80
+ triggerLabel?: string;
81
+ /** @internal */
82
+ profile: string;
83
+
84
+ /** @internal */
85
+ issue: JiraIssue;
86
+
87
+ /** @internal */
88
+ projects: string[];
89
+ }
90
+
91
+ /** @public */
92
+ export const jiraIssueWatcherSource = defineProcessWatcherSource<
93
+ JiraWatcherConfig,
94
+ JiraWatcherEvent
95
+ >({
96
+ id: "@leitwerk-dev/jira.issue",
97
+ label: "Jira issue",
98
+ parseConfig(raw) {
99
+ const c = asUnknownRecord(raw);
100
+ if (
101
+ typeof c?.enabled !== "boolean" ||
102
+ typeof c.profile !== "string" ||
103
+ !c.profile.trim() ||
104
+ !Array.isArray(c.projects) ||
105
+ !c.projects.length ||
106
+ c.projects.some((id) => typeof id !== "string" || !/^\d+$/.test(id))
107
+ )
108
+ throw new Error("Jira watcher requires enabled, profile, and explicit project IDs");
109
+ const pollInterval = c.poll_interval ?? "30s";
110
+ if (typeof pollInterval !== "string" || parseDurationMs(pollInterval, -1) <= 0)
111
+ throw new Error("Invalid Jira poll_interval");
112
+ return {
113
+ enabled: c.enabled,
114
+ config: {
115
+ profile: c.profile,
116
+ projects: c.projects as string[],
117
+ pollInterval,
118
+ label: jiraTriggerLabel(c.label),
119
+ },
120
+ launchModelConfig: parseProcessWatcherLaunchModelConfig(c.launch),
121
+ };
122
+ },
123
+ presentConfig: (c) => ({
124
+ targetSummary: `Jira ${c.profile} · ${c.projects.join(", ")}`,
125
+ details: [{ label: "Trigger", value: jiraTriggerLabel(c.label) }],
126
+ }),
127
+ });
128
+
129
+ /** @public */
130
+ export interface JiraSourceConfig {
131
+ /** @internal */
132
+ triggerLabel?: string;
133
+ /** @internal */
134
+ profile: string;
135
+ /** @internal */
136
+ baseUrl: string;
137
+
138
+ /** @internal */
139
+ issueId: string;
140
+
141
+ /** @internal */
142
+ planRevision?: number;
143
+
144
+ /** @internal */
145
+ mode: "plan_bypass" | "cancelled";
146
+ }
147
+ const ISSUE_POLICY = "@leitwerk-dev/jira.issue-policy";
148
+
149
+ /** @public */
150
+ export function jiraIssuePolicy<P, S>(
151
+ resolve: (ctx: {
152
+ /** @internal */
153
+ params: P;
154
+ /** @internal */
155
+ state: S;
156
+ }) => JiraSourceConfig,
157
+ ): ExternalActionSource<P, S, unknown> {
158
+ return {
159
+ kind: ISSUE_POLICY,
160
+ label: "Jira source policy",
161
+ config: {},
162
+ inputMode: "none",
163
+ resolve,
164
+ };
165
+ }
166
+
167
+ /** @public */
168
+ export function setupJiraIntegration(
169
+ api: ServerExtensionAPI,
170
+ integration: JiraIntegration,
171
+ options: {
172
+ /** @public */
173
+ now?: () => number;
174
+ /** @internal */
175
+ ticketCreation?: TicketCreationConfig;
176
+ /** Project IDs or keys explicitly selected by integration profiles. @internal */
177
+ projects?: ReadonlyMap<string, readonly string[]>;
178
+ } = {},
179
+ ) {
180
+ const now = options.now ?? Date.now;
181
+ api.provide(jiraIntegration, integration);
182
+ registerJiraTools(api, integration);
183
+ registerJiraTicketCreation(
184
+ api,
185
+ integration,
186
+ options.ticketCreation ?? { enabled: false, defaultLabels: [] },
187
+ );
188
+ const settings = api.get(scopedSettingsCapability);
189
+ const deps = api.get(coreHostCapabilities.serverSetup);
190
+ const configuredProjects = (profile: string) =>
191
+ new Set([
192
+ ...(options.projects?.get(profile) ?? []),
193
+ ...(!deps || Array.isArray(deps)
194
+ ? []
195
+ : (deps.processWatchers?.listBySource(jiraIssueWatcherSource) ?? [])
196
+ .filter((watcher) => watcher.config.profile === profile)
197
+ .flatMap((watcher) => watcher.config.projects)),
198
+ ]);
199
+ const projectsFor = async (profile: string) => {
200
+ const selected = configuredProjects(profile);
201
+ if (!selected.size) return [];
202
+ const client = integration.client(profile);
203
+ const projects = (await client.listProjects()).filter(
204
+ (project) => selected.has(project.id) || selected.has(project.key),
205
+ );
206
+ return projects;
207
+ };
208
+ const includesProject = (subject: import("@leitwerk-dev/domain").SettingsSubject | undefined) => {
209
+ if (!subject) return false;
210
+ let identity: unknown;
211
+ try {
212
+ identity = JSON.parse(subject.identity);
213
+ } catch {
214
+ return false;
215
+ }
216
+ if (!Array.isArray(identity) || identity.length !== 2) return false;
217
+ const [origin, id] = identity;
218
+ return integration.profiles().some((profile) => {
219
+ if (integration.client(profile).baseUrl !== origin) return false;
220
+ const configured = configuredProjects(profile);
221
+ return configured.has(id) || configured.has(subject.label.split(" · ")[0]);
222
+ });
223
+ };
224
+ api.provide(jiraProjectDiscovery, { projects: projectsFor, includesProject });
225
+ if (settings && !Array.isArray(settings)) {
226
+ settings.registerDiscovery(
227
+ "jira.project",
228
+ async () => {
229
+ const subjects = [];
230
+ for (const profile of integration.profiles()) {
231
+ const client = integration.client(profile);
232
+ for (const project of await projectsFor(profile))
233
+ subjects.push({
234
+ scopeType: "jira.project",
235
+ identity: jiraSubjectIdentity(client.baseUrl, project.id),
236
+ label: `${project.key} · ${project.name}`,
237
+ });
238
+ }
239
+ return subjects;
240
+ },
241
+ { includesSubject: (subject) => includesProject(subject) },
242
+ );
243
+ settings.registerDiscovery(
244
+ "jira.component",
245
+ async () => {
246
+ const subjects = [];
247
+ for (const profile of integration.profiles()) {
248
+ const client = integration.client(profile);
249
+ for (const project of await projectsFor(profile)) {
250
+ const parent = settings.discover({
251
+ scopeType: "jira.project",
252
+ identity: jiraSubjectIdentity(client.baseUrl, project.id),
253
+ label: `${project.key} · ${project.name}`,
254
+ });
255
+ for (const component of await client.listComponents(project.id))
256
+ subjects.push({
257
+ scopeType: "jira.component",
258
+ identity: jiraSubjectIdentity(client.baseUrl, component.id),
259
+ label: `${project.key} / ${component.name}`,
260
+ context: { "jira.project": parent.id },
261
+ });
262
+ }
263
+ }
264
+ return subjects;
265
+ },
266
+ { includesSubject: (_subject, context) => includesProject(context["jira.project"]) },
267
+ );
268
+ }
269
+ if (!deps || Array.isArray(deps)) return;
270
+ const shouldPoll = createPollSchedule(now);
271
+ return deps.polling.create({
272
+ id: "jira",
273
+ pollInterval: () => "5s",
274
+ defaultIntervalMs: 5000,
275
+ isEnabled: () => true,
276
+ async pollOnce() {
277
+ const result = emptyPollResult();
278
+ for (const watcher of deps.processWatchers?.listBySource(jiraIssueWatcherSource) ?? []) {
279
+ const key = `${watcher.processId}:${watcher.watcherId}`;
280
+ if (!watcher.enabled || !shouldPoll(key, watcher.config.pollInterval)) continue;
281
+ try {
282
+ const client = integration.client(watcher.config.profile);
283
+ for (const issue of await client.searchIssues(
284
+ watcher.config.projects,
285
+ watcher.config.label,
286
+ )) {
287
+ if (
288
+ !jiraEligible(issue, watcher.config.label) ||
289
+ !watcher.config.projects.includes(issue.fields.project.id)
290
+ )
291
+ continue;
292
+ const id = jiraIssueExternalId(client.baseUrl, issue.id);
293
+ const launch = await deps.launchRuns.startWatcher(
294
+ watcher,
295
+ {
296
+ profile: watcher.config.profile,
297
+ issue,
298
+ projects: watcher.config.projects,
299
+ triggerLabel: jiraTriggerLabel(watcher.config.label),
300
+ },
301
+ { idempotencyKey: id },
302
+ );
303
+ if (launch.error)
304
+ result.errors.push(
305
+ `${issue.key}: admission failed; inspect launch diagnostics and component mappings`,
306
+ );
307
+ else if (launch.process) result.created.push(id);
308
+ else result.skipped.push(id);
309
+ }
310
+ } catch (error) {
311
+ result.errors.push(error instanceof Error ? error.message : "Jira discovery unavailable");
312
+ }
313
+ }
314
+ const report = createExternalSourcePollReporter(deps.externalSources, result, {
315
+ forwardGeneration: true,
316
+ currentKinds: [ISSUE_POLICY],
317
+ });
318
+ await report.poll(ISSUE_POLICY, async (armed) => {
319
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation}`;
320
+ if (!shouldPoll(key)) return;
321
+ const c = armed.resolved as unknown as JiraSourceConfig;
322
+ try {
323
+ const client = integration.client(c.profile);
324
+ if (client.baseUrl !== c.baseUrl) throw new Error("Jira profile installation changed");
325
+ const issue = await client.getIssue(c.issueId);
326
+ if (issue.id !== c.issueId) throw new Error("Uncorrelated Jira issue evidence");
327
+ const fire =
328
+ c.mode === "plan_bypass"
329
+ ? jiraEligible(issue, c.triggerLabel) &&
330
+ issue.fields.labels.includes("leitwerk-skip-plan-decision")
331
+ : !jiraEligible(issue, c.triggerLabel);
332
+ if (fire)
333
+ await report.fire(
334
+ armed,
335
+ { issueId: issue.id, planRevision: c.planRevision },
336
+ `${issue.id}:${c.mode}:${c.planRevision ?? ""}`,
337
+ );
338
+ } catch (error) {
339
+ await report.observe(armed, { refreshError: "Jira issue unavailable; policy unchanged" });
340
+ throw error;
341
+ }
342
+ });
343
+ return result;
344
+ },
345
+ });
346
+ }
347
+
348
+ /** @public */
349
+ const extension: LeitwerkExtensionModule = {
350
+ manifest: { id: "jira", version: "0.3.0" },
351
+ scopedSettings: {
352
+ scopes: [
353
+ { id: "jira.project", label: "Jira projects" },
354
+ {
355
+ id: "jira.component",
356
+ label: "Jira components",
357
+ overview: {
358
+ itemLabel: "Component",
359
+ itemLabelPlural: "Components",
360
+ parentLabel: "Project",
361
+ labelSeparator: " / ",
362
+ },
363
+ },
364
+ ],
365
+ settings: [],
366
+ },
367
+ setupServer(api, config) {
368
+ const profiles = parseJiraProfiles(config);
369
+ const clients = new Map([...profiles].map(([id, profile]) => [id, new JiraClient(profile)]));
370
+ setupJiraIntegration(
371
+ api,
372
+ {
373
+ profiles: () => [...clients.keys()],
374
+ client: (profile) => {
375
+ const client = clients.get(profile);
376
+ if (!client) throw new Error(`Jira profile '${profile}' is unavailable`);
377
+ return client;
378
+ },
379
+ },
380
+ {
381
+ ticketCreation: parseTicketCreationConfig(config, "Jira"),
382
+ projects: new Map(
383
+ [...profiles].map(([id, profile]) => [id, profile.project ? [profile.project] : []]),
384
+ ),
385
+ },
386
+ );
387
+ },
388
+ };
389
+ export default extension;