pi-dev-flow 0.97.0 → 0.99.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.
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Jira operations over the official Atlassian Rovo MCP server (src/jira/mcp.ts), with the same API token
3
+ * used against Jira's REST API only where the MCP server offers no tool for the job (a fallback per call,
4
+ * never a second configuration).
5
+ *
6
+ * Tool names and argument names are resolved against the server's live `tools/list`: v2 renamed most v1
7
+ * tools (getTransitionsForJiraIssue → listJiraIssueTransitions, …) and the argument spellings are only
8
+ * published as schemas, so each operation names its candidates and the first one offered wins.
9
+ *
10
+ * Every operation returns a JiraResult — it never throws into a gate.
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import path from "node:path";
14
+ import { basicAuth, type JiraCreds } from "./creds.ts";
15
+ import { type FetchLike, McpClient, type McpTool, resultText, resultValue } from "./mcp.ts";
16
+ import type { StatusInfo } from "./config.ts";
17
+
18
+ export const MCP_URL = process.env.JIRA_MCP_URL ?? "https://mcp.atlassian.com/v2/mcp?tools=all";
19
+
20
+ export type JiraResult<T> = { ok: true; value: T; via?: "mcp" | "rest" } | { ok: false; error: string };
21
+
22
+ export interface JiraUser {
23
+ accountId: string;
24
+ displayName: string;
25
+ }
26
+ export interface JiraIssue {
27
+ key: string;
28
+ summary: string;
29
+ description: string;
30
+ status: string;
31
+ statusCategory?: string;
32
+ type: string;
33
+ url: string;
34
+ }
35
+ export interface JiraComment {
36
+ id: string;
37
+ authorId: string;
38
+ authorName: string;
39
+ body: string;
40
+ created: string;
41
+ updated?: string;
42
+ }
43
+
44
+ // logical operation → candidate tool names (v2 first, then v1)
45
+ const TOOLS = {
46
+ me: ["getJiraCurrentUser", "atlassianUserInfo"],
47
+ resources: ["getAccessibleAtlassianResources"],
48
+ projects: ["listJiraProjects", "getVisibleJiraProjects"],
49
+ issueTypes: ["listJiraProjectIssueTypesMetadata", "getJiraProjectIssueTypesMetadata"],
50
+ statuses: ["listJiraStatuses"],
51
+ issue: ["getJiraIssue"],
52
+ comments: ["listJiraIssueComments"],
53
+ comment: ["addOrEditJiraIssueComment", "addCommentToJiraIssue"],
54
+ upload: ["uploadAttachmentToJiraIssue"],
55
+ transitions: ["listJiraIssueTransitions", "getTransitionsForJiraIssue"],
56
+ transition: ["transitionJiraIssue"],
57
+ search: ["searchJiraIssuesUsingJql"],
58
+ create: ["createJiraIssue"],
59
+ } as const;
60
+ type Op = keyof typeof TOOLS;
61
+
62
+ // logical argument → candidate schema property names
63
+ const ARGS: Record<string, string[]> = {
64
+ cloudId: ["cloudId"],
65
+ project: ["projectIdOrKey", "projectKey", "project", "projectId"],
66
+ issue: ["issueIdOrKey", "issueKey", "issueId", "key"],
67
+ issueType: ["issueTypeName", "issueTypeIdOrName", "issueType", "issueTypeId"],
68
+ summary: ["summary", "title"],
69
+ description: ["description", "descriptionText"],
70
+ body: ["commentBody", "body", "comment", "content", "text"],
71
+ format: ["contentFormat", "bodyFormat", "format"],
72
+ transition: ["transition", "transitionId"],
73
+ fields: ["fields"],
74
+ jql: ["jql"],
75
+ max: ["maxResults", "limit"],
76
+ mode: ["mode"],
77
+ view: ["view"],
78
+ order: ["orderBy"],
79
+ // the v2 tool takes a local filePath and hands back a command to run (a two-phase upload) — not content, so
80
+ // attachments go through REST
81
+ file: ["fileContent", "base64Content"],
82
+ filename: ["filename", "fileName", "name"],
83
+ mime: ["mimeType", "contentType"],
84
+ };
85
+
86
+ const str = (v: unknown) => (typeof v === "string" ? v : v == null ? "" : String(v));
87
+ const rec = (v: unknown): Record<string, unknown> => {
88
+ const r = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
89
+ // the v2 server wraps some answers as { data: … }
90
+ return r.data && typeof r.data === "object" && !Array.isArray(r.data) && Object.keys(r).length === 1 ? (r.data as Record<string, unknown>) : r;
91
+ };
92
+ /** The array in a list result: the value itself, or its first array-valued property among the usual ones. */
93
+ function arr(v: unknown, ...keys: string[]): unknown[] {
94
+ if (Array.isArray(v)) return v;
95
+ const r = rec(v);
96
+ if (r.data !== undefined && Object.keys(r).length <= 2) return arr(r.data, ...keys);
97
+ for (const k of [...keys, "values", "results", "items", "issues", "comments", "transitions", "statuses", "issueTypes", "projects", "data"])
98
+ if (Array.isArray(r[k])) return r[k] as unknown[];
99
+ return [];
100
+ }
101
+
102
+ /** Plain text of an Atlassian Document Format node (or a string body as-is). */
103
+ export function adfText(node: unknown): string {
104
+ if (typeof node === "string") return node;
105
+ const n = rec(node);
106
+ if (n.type === "text") return str(n.text);
107
+ if (n.type === "hardBreak") return "\n";
108
+ if (n.type === "mention") return str(rec(n.attrs).text);
109
+ const kids = Array.isArray(n.content) ? (n.content as unknown[]).map(adfText).join("") : "";
110
+ return /^(paragraph|heading|listItem|codeBlock|blockquote|bulletList|orderedList|rule)$/.test(str(n.type)) ? `${kids}\n` : kids;
111
+ }
112
+
113
+ /** Markdown-ish text → a minimal ADF document (paragraphs and code blocks) — for REST, which takes no markdown. */
114
+ export function toAdf(text: string): unknown {
115
+ const content: unknown[] = [];
116
+ const parts = text.split(/```[^\n]*\n([\s\S]*?)```/);
117
+ parts.forEach((part, i) => {
118
+ if (i % 2 === 1) return void content.push({ type: "codeBlock", content: part ? [{ type: "text", text: part.replace(/\n$/, "") }] : [] });
119
+ for (const para of part.split(/\n{2,}/)) {
120
+ const lines = para.split("\n").filter((l, j, a) => l || j < a.length - 1);
121
+ if (!lines.join("").trim()) continue;
122
+ const inl: unknown[] = [];
123
+ lines.forEach((l, j) => {
124
+ if (j) inl.push({ type: "hardBreak" });
125
+ if (l) inl.push({ type: "text", text: l });
126
+ });
127
+ content.push({ type: "paragraph", content: inl });
128
+ }
129
+ });
130
+ return { type: "doc", version: 1, content };
131
+ }
132
+
133
+ const MIME: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".md": "text/markdown", ".txt": "text/plain", ".json": "application/json", ".pdf": "application/pdf" };
134
+ export const mimeOf = (file: string) => MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream";
135
+
136
+ export class JiraClient {
137
+ readonly creds: JiraCreds;
138
+ readonly mcp: McpClient;
139
+ private readonly fetchFn: FetchLike;
140
+ private cloudIdP: Promise<string> | undefined;
141
+ private cloudIdFixed: string | undefined;
142
+ /** the REST base a scoped token needs, once the site URL refused it */
143
+ private gateway: string | undefined;
144
+
145
+ constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string } = {}) {
146
+ this.creds = creds;
147
+ this.fetchFn = opts.fetch ?? (globalThis.fetch as unknown as FetchLike);
148
+ this.cloudIdFixed = opts.cloudId;
149
+ this.mcp = new McpClient(opts.mcpUrl ?? MCP_URL, { authorization: basicAuth(creds) }, this.fetchFn);
150
+ }
151
+
152
+ get site() {
153
+ return this.creds.site;
154
+ }
155
+ issueUrl(key: string) {
156
+ return `https://${this.creds.site}/browse/${key}`;
157
+ }
158
+
159
+ private async tool(op: Op): Promise<McpTool | undefined> {
160
+ const tools = await this.mcp.listTools();
161
+ for (const n of TOOLS[op]) {
162
+ const t = tools.find((x) => x.name === n);
163
+ if (t) return t;
164
+ }
165
+ return undefined;
166
+ }
167
+
168
+ /** Build arguments against the tool's schema: each logical name goes to the first matching property. */
169
+ private args(t: McpTool, logical: Record<string, unknown>): Record<string, unknown> {
170
+ const props = Object.keys(t.inputSchema?.properties ?? {});
171
+ const out: Record<string, unknown> = {};
172
+ for (const [k, v] of Object.entries(logical)) {
173
+ if (v === undefined) continue;
174
+ const name = (ARGS[k] ?? [k]).find((c) => props.includes(c));
175
+ if (name) out[name] = v;
176
+ else if (!props.length) out[(ARGS[k] ?? [k])[0]] = v; // no schema: best guess
177
+ }
178
+ return out;
179
+ }
180
+
181
+ private async call(op: Op, logical: Record<string, unknown>): Promise<JiraResult<unknown>> {
182
+ try {
183
+ const t = await this.tool(op);
184
+ if (!t) return { ok: false, error: `the Atlassian MCP server offers no ${TOOLS[op].join("/")} tool` };
185
+ const needsCloud = t.inputSchema?.properties && "cloudId" in t.inputSchema.properties;
186
+ const args = this.args(t, { ...(needsCloud ? { cloudId: await this.cloudId() } : {}), ...logical });
187
+ const r = await this.mcp.callTool(t.name, args);
188
+ if (r.isError) return { ok: false, error: `${t.name}: ${resultText(r).slice(0, 400)}` };
189
+ return { ok: true, value: resultValue(r), via: "mcp" };
190
+ } catch (e) {
191
+ return { ok: false, error: (e as Error).message };
192
+ }
193
+ }
194
+
195
+ /** The site's cloudId: configured, else looked up among the token's accessible resources, else the site
196
+ * host (the Atlassian tools accept a site URL where they take a cloudId). */
197
+ cloudId(): Promise<string> {
198
+ if (this.cloudIdFixed) return Promise.resolve(this.cloudIdFixed);
199
+ this.cloudIdP ??= (async () => {
200
+ try {
201
+ const t = await this.tool("resources");
202
+ if (t) {
203
+ const r = await this.mcp.callTool(t.name, {});
204
+ const hit = arr(resultValue(r)).map(rec).find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
205
+ if (hit?.cloudId ?? hit?.id) return str(hit.cloudId ?? hit.id);
206
+ }
207
+ } catch {
208
+ /* fall through */
209
+ }
210
+ try {
211
+ const res = await this.fetchFn(`https://${this.creds.site}/_edge/tenant_info`, { method: "GET", headers: {} });
212
+ if (res.ok) {
213
+ const id = str(rec(JSON.parse(await res.text())).cloudId);
214
+ if (id) return id;
215
+ }
216
+ } catch {
217
+ /* fall through */
218
+ }
219
+ return this.creds.site;
220
+ })();
221
+ return this.cloudIdP;
222
+ }
223
+
224
+ private async restBase(): Promise<string> {
225
+ return this.gateway ?? `https://${this.creds.site}/rest/api/3`;
226
+ }
227
+
228
+ /** Jira REST with the same token — only for what the MCP server cannot do. */
229
+ private async rest(method: string, p: string, body?: unknown, extra: Record<string, string> = {}): Promise<JiraResult<unknown>> {
230
+ try {
231
+ const headers: Record<string, string> = { authorization: basicAuth(this.creds), accept: "application/json", ...extra };
232
+ let payload: string | undefined;
233
+ if (body !== undefined && typeof body === "string") payload = body;
234
+ else if (body !== undefined) {
235
+ headers["content-type"] = "application/json";
236
+ payload = JSON.stringify(body);
237
+ }
238
+ let res = await this.fetchFn(`${await this.restBase()}${p}`, { method, headers, body: payload });
239
+ if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
240
+ // a scoped API token answers only through api.atlassian.com/ex/jira/<cloudId>
241
+ const id = await this.cloudId();
242
+ if (/^[0-9a-f-]{36}$/.test(id)) {
243
+ this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
244
+ res = await this.fetchFn(`${this.gateway}${p}`, { method, headers, body: payload });
245
+ }
246
+ }
247
+ const text = await res.text();
248
+ if (!res.ok) return { ok: false, error: `Jira REST ${method} ${p}: HTTP ${res.status} ${text.slice(0, 300)}` };
249
+ return { ok: true, value: text ? JSON.parse(text) : undefined, via: "rest" };
250
+ } catch (e) {
251
+ return { ok: false, error: (e as Error).message };
252
+ }
253
+ }
254
+
255
+ async me(): Promise<JiraResult<JiraUser>> {
256
+ const r = await this.call("me", {});
257
+ if (!r.ok) return r;
258
+ const v = rec(r.value);
259
+ const accountId = str(v.accountId ?? v.account_id ?? v.id);
260
+ if (!accountId) return { ok: false, error: `could not read the account id from ${JSON.stringify(r.value).slice(0, 200)}` };
261
+ return { ok: true, value: { accountId, displayName: str(v.displayName ?? v.name ?? v.email) || accountId } };
262
+ }
263
+
264
+ async projects(): Promise<JiraResult<{ key: string; name: string }[]>> {
265
+ const r = await this.call("projects", { max: 100 });
266
+ if (!r.ok) return r;
267
+ return { ok: true, value: arr(r.value).map(rec).map((p) => ({ key: str(p.key), name: str(p.name) })).filter((p) => p.key) };
268
+ }
269
+
270
+ async issueTypes(project: string): Promise<JiraResult<{ id: string; name: string; subtask: boolean }[]>> {
271
+ const r = await this.call("issueTypes", { project });
272
+ if (!r.ok) return r;
273
+ return { ok: true, value: arr(r.value).map(rec).map((t) => ({ id: str(t.id), name: str(t.name), subtask: t.subtask === true || t.hierarchyLevel === -1 })).filter((t) => t.name) };
274
+ }
275
+
276
+ /** The statuses of each issue type's workflow in a project. MCP `listJiraStatuses` when it answers per issue
277
+ * type, else REST `/project/{key}/statuses` (the one call grouped by issue type). */
278
+ async statuses(project: string): Promise<JiraResult<Record<string, StatusInfo[]>>> {
279
+ const toInfo = (s: Record<string, unknown>): StatusInfo => ({ name: str(s.name), category: str(rec(s.statusCategory).key ?? s.statusCategory ?? s.category) || undefined });
280
+ const grouped = (v: unknown) => {
281
+ // v2 mode "project": { statuses: [{id, name, category}], workTypes: [{name, statusIds}] }
282
+ const r = rec(v);
283
+ if (Array.isArray(r.workTypes) && Array.isArray(r.statuses)) {
284
+ const byId = new Map((r.statuses as unknown[]).map(rec).map((x) => [str(x.id), x]));
285
+ return Object.fromEntries(
286
+ (r.workTypes as unknown[]).map(rec).map((t) => [str(t.name), (Array.isArray(t.statusIds) ? (t.statusIds as unknown[]) : []).map((id) => byId.get(str(id))).filter((x): x is Record<string, unknown> => !!x).map(toInfo)]),
287
+ );
288
+ }
289
+ const list = arr(v).map(rec);
290
+ if (!list.length || !list.every((t) => Array.isArray(t.statuses))) return undefined;
291
+ return Object.fromEntries(list.map((t) => [str(t.name), (t.statuses as unknown[]).map(rec).map(toInfo)]));
292
+ };
293
+ const m = await this.call("statuses", { mode: "project", project });
294
+ if (m.ok && grouped(m.value)) return { ok: true, value: grouped(m.value)!, via: "mcp" };
295
+ const r = await this.rest("GET", `/project/${encodeURIComponent(project)}/statuses`);
296
+ if (r.ok && grouped(r.value)) return { ok: true, value: grouped(r.value)!, via: "rest" };
297
+ return { ok: false, error: !m.ok ? m.error : !r.ok ? r.error : "no per-issue-type statuses in the answer" };
298
+ }
299
+
300
+ async issue(key: string): Promise<JiraResult<JiraIssue>> {
301
+ // v2's default "compact" view leaves out the issue type; "evidence" carries it (fields= cannot ask for it)
302
+ const r = await this.call("issue", { issue: key, view: "evidence" });
303
+ if (!r.ok) return r;
304
+ const v = rec(r.value);
305
+ const f = rec(v.fields ?? v);
306
+ const status = rec(f.status);
307
+ return {
308
+ ok: true,
309
+ value: {
310
+ key: str(v.key) || key,
311
+ summary: str(f.summary),
312
+ description: adfText(f.description).trim(),
313
+ status: str(status.name ?? f.status),
314
+ statusCategory: str(rec(status.statusCategory).key) || undefined,
315
+ type: str(rec(f.issuetype).name ?? f.issuetype),
316
+ url: this.issueUrl(str(v.key) || key),
317
+ },
318
+ };
319
+ }
320
+
321
+ async comments(key: string): Promise<JiraResult<JiraComment[]>> {
322
+ const toC = (c: Record<string, unknown>): JiraComment => {
323
+ const a = rec(c.author);
324
+ return { id: str(c.id), authorId: str(a.accountId), authorName: str(a.displayName), body: adfText(c.body ?? c.renderedBody).trim(), created: str(c.created), updated: str(c.updated) || undefined };
325
+ };
326
+ // "full": the default compact view leaves out the author's accountId, which decides who answered (its page caps at 20)
327
+ const m = await this.call("comments", { issue: key, max: 20, order: "-created", view: "full" });
328
+ if (m.ok) return { ok: true, value: arr(m.value).map(rec).map(toC).filter((c) => c.id), via: "mcp" };
329
+ const r = await this.rest("GET", `/issue/${encodeURIComponent(key)}/comment?orderBy=-created&maxResults=100`);
330
+ if (r.ok) return { ok: true, value: arr(r.value).map(rec).map(toC).filter((c) => c.id), via: "rest" };
331
+ return m;
332
+ }
333
+
334
+ /** Post a comment (markdown); returns its id. */
335
+ async comment(key: string, markdown: string): Promise<JiraResult<string>> {
336
+ const t = await this.tool("comment").catch(() => undefined);
337
+ const takesFormat = !!t && Object.keys(t.inputSchema?.properties ?? {}).some((p) => ARGS.format.includes(p));
338
+ const m = await this.call("comment", { issue: key, body: markdown, ...(takesFormat ? { format: "markdown" } : {}) });
339
+ if (m.ok) {
340
+ const v = rec(m.value);
341
+ return { ok: true, value: str(v.commentId ?? v.id ?? rec(v.comment).id), via: "mcp" };
342
+ }
343
+ const r = await this.rest("POST", `/issue/${encodeURIComponent(key)}/comment`, { body: toAdf(markdown) });
344
+ if (r.ok) return { ok: true, value: str(rec(r.value).id), via: "rest" };
345
+ return m;
346
+ }
347
+
348
+ /** Attach a local file. MCP `uploadAttachmentToJiraIssue` when it takes file content, else REST multipart. */
349
+ async upload(key: string, file: string): Promise<JiraResult<string>> {
350
+ const data = readFileSync(file);
351
+ const name = path.basename(file);
352
+ const t = await this.tool("upload").catch(() => undefined);
353
+ const props = Object.keys(t?.inputSchema?.properties ?? {});
354
+ if (t && props.some((p) => ARGS.file.includes(p))) {
355
+ const m = await this.call("upload", { issue: key, file: data.toString("base64"), filename: name, mime: mimeOf(file) });
356
+ if (m.ok) return { ok: true, value: name, via: "mcp" };
357
+ }
358
+ const boundary = `----devflow${Date.now().toString(16)}`;
359
+ const head = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name.replace(/"/g, "")}"\r\nContent-Type: ${mimeOf(file)}\r\n\r\n`;
360
+ const body = Buffer.concat([Buffer.from(head), data, Buffer.from(`\r\n--${boundary}--\r\n`)]);
361
+ try {
362
+ const send = async (base: string) =>
363
+ this.fetchFn(`${base}/issue/${encodeURIComponent(key)}/attachments`, {
364
+ method: "POST",
365
+ headers: { authorization: basicAuth(this.creds), "x-atlassian-token": "no-check", "content-type": `multipart/form-data; boundary=${boundary}`, accept: "application/json" },
366
+ // SAFETY: fetch accepts a Buffer body; FetchLike types it as string for the JSON paths
367
+ body: body as unknown as string,
368
+ });
369
+ let res = await send(await this.restBase());
370
+ if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
371
+ const id = await this.cloudId();
372
+ if (/^[0-9a-f-]{36}$/.test(id)) {
373
+ this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
374
+ res = await send(this.gateway);
375
+ }
376
+ }
377
+ if (!res.ok) {
378
+ const why = res.status === 401 || res.status === 403 || res.status === 404 ? "Jira's REST API did not accept the token (a scoped token needs write:jira-work; a plain API token works) — the MCP server cannot take file content, so attachments go through REST" : (await res.text()).slice(0, 200);
379
+ return { ok: false, error: `attach ${name}: HTTP ${res.status} — ${why}` };
380
+ }
381
+ return { ok: true, value: name, via: "rest" };
382
+ } catch (e) {
383
+ return { ok: false, error: `attach ${name}: ${(e as Error).message}` };
384
+ }
385
+ }
386
+
387
+ /** Create an issue (markdown description); returns its key. */
388
+ async createIssue(project: string, type: string, summary: string, description: string): Promise<JiraResult<string>> {
389
+ const t = await this.tool("create").catch(() => undefined);
390
+ const props = Object.keys(t?.inputSchema?.properties ?? {});
391
+ const typeProp = props.find((p) => ARGS.issueType.includes(p));
392
+ const types = typeProp === "issueTypeId" ? await this.issueTypes(project) : null;
393
+ const typeVal = types?.ok ? (types.value.find((x) => x.name.toLowerCase() === type.toLowerCase())?.id ?? type) : type;
394
+ const takesFormat = props.some((p) => ARGS.format.includes(p));
395
+ const m = await this.call("create", { project, issueType: typeVal, summary, description: description || undefined, ...(takesFormat && description ? { format: "markdown" } : {}) });
396
+ const keyOf = (v: unknown) => str(rec(v).key ?? rec(rec(v).issue).key);
397
+ if (m.ok && keyOf(m.value)) return { ok: true, value: keyOf(m.value), via: "mcp" };
398
+ const r = await this.rest("POST", "/issue", { fields: { project: { key: project }, issuetype: { name: type }, summary, ...(description ? { description: toAdf(description) } : {}) } });
399
+ if (r.ok && keyOf(r.value)) return { ok: true, value: keyOf(r.value), via: "rest" };
400
+ return m.ok ? { ok: false, error: `created, but no key in the answer: ${JSON.stringify(m.value).slice(0, 200)}` } : m;
401
+ }
402
+
403
+ async transitions(key: string): Promise<JiraResult<{ id: string; name: string; to: string }[]>> {
404
+ const r = await this.call("transitions", { issue: key });
405
+ if (!r.ok) return r;
406
+ return { ok: true, value: arr(r.value).map(rec).map((t) => ({ id: str(t.id), name: str(t.name), to: str(rec(t.to).name ?? t.to) })) };
407
+ }
408
+
409
+ async transition(key: string, id: string): Promise<JiraResult<void>> {
410
+ const t = await this.tool("transition").catch(() => undefined);
411
+ const prop = Object.keys(t?.inputSchema?.properties ?? {}).find((p) => ARGS.transition.includes(p));
412
+ const r = await this.call("transition", { issue: key, transition: prop === "transitionId" ? id : { id } });
413
+ return r.ok ? { ok: true, value: undefined } : r;
414
+ }
415
+
416
+ /** Move an issue to the status named `to` when a transition leads there. */
417
+ async moveTo(key: string, to: string): Promise<JiraResult<string>> {
418
+ const ts = await this.transitions(key);
419
+ if (!ts.ok) return ts;
420
+ const hit = ts.value.find((t) => t.to.toLowerCase() === to.toLowerCase()) ?? ts.value.find((t) => t.name.toLowerCase() === to.toLowerCase());
421
+ if (!hit) return { ok: false, error: `no transition from the current status leads to "${to}" (offered: ${ts.value.map((t) => t.to || t.name).join(", ") || "none"})` };
422
+ const r = await this.transition(key, hit.id);
423
+ return r.ok ? { ok: true, value: hit.to || to } : r;
424
+ }
425
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The ` ```flow-jira ` block under `## global` in project.md — the opt-in Jira sync. No block: off.
3
+ *
4
+ * site = acme.atlassian.net
5
+ * cloudId = 1234-… (filled by `flow jira init`)
6
+ * project = DEV
7
+ * issueTypes = Story, Bug
8
+ * status.Story.plan = To Do
9
+ * status.Story.implement = In Progress
10
+ * status.Story.pre-release = In Review
11
+ * status.Story.release = Ready for Release
12
+ * status.Story.done = Done
13
+ * mirror = asks asks (default) | all — which of the agent's closing messages become comments
14
+ * watch = 30m, 1h, 2h, 4h reply-check intervals after a question; the last repeats
15
+ * watchCap = 72h stop watching this long after the question
16
+ *
17
+ * A status value may name several statuses (`To Do, Backlog`): any of them means that stage; the first is
18
+ * the one dev-flow moves the issue to. Pure module.
19
+ */
20
+ import type { JiraConfig, JiraStage } from "../core.ts";
21
+
22
+ export const JIRA_STAGES: readonly JiraStage[] = ["plan", "implement", "pre-release", "release", "done"];
23
+ export const DEFAULT_WATCH = [30 * 60, 60 * 60, 2 * 3600, 4 * 3600];
24
+ export const DEFAULT_WATCH_CAP = 72 * 3600;
25
+
26
+ /** `30m` / `1h` / `2d` / `90s` / `45` (seconds) → seconds; undefined for junk. */
27
+ export function parseDuration(raw: string): number | undefined {
28
+ const m = raw.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/i);
29
+ if (!m) return undefined;
30
+ const mult = { s: 1, m: 60, h: 3600, d: 86400 }[(m[2] ?? "s").toLowerCase() as "s" | "m" | "h" | "d"];
31
+ return Math.round(Number(m[1]) * mult);
32
+ }
33
+
34
+ export const fmtDuration = (s: number) => (s % 86400 === 0 ? `${s / 86400}d` : s % 3600 === 0 ? `${s / 3600}h` : s % 60 === 0 ? `${s / 60}m` : `${s}s`);
35
+
36
+ const list = (v: string) =>
37
+ v
38
+ .split(",")
39
+ .map((x) => x.trim())
40
+ .filter(Boolean);
41
+
42
+ /** Parse the block's lines (`where` gives each line's location for messages). */
43
+ export function parseJiraBlock(entries: { line: string; where: string }[]): { cfg?: JiraConfig; hard: string[]; warn: string[] } {
44
+ const hard: string[] = [];
45
+ const warn: string[] = [];
46
+ const cfg: JiraConfig = { site: "", project: "", issueTypes: [], status: {}, mirror: "asks", watch: [...DEFAULT_WATCH], watchCap: DEFAULT_WATCH_CAP };
47
+ for (const { line, where } of entries) {
48
+ const t = line.trim();
49
+ if (!t || t.startsWith("#")) continue;
50
+ const m = t.match(/^([A-Za-z][\w.\- ]*?)\s*=\s*(.*)$/);
51
+ if (!m) {
52
+ hard.push(`${where}: expected \`key = value\` inside flow-jira block`);
53
+ continue;
54
+ }
55
+ const [, key, value] = m;
56
+ const st = key.match(/^status\.(.+)\.([a-z-]+)$/);
57
+ if (st) {
58
+ const [, type, stage] = st;
59
+ if (!JIRA_STAGES.includes(stage as JiraStage)) {
60
+ warn.push(`${where}: flow-jira ${key} — unknown stage "${stage}" (expected ${JIRA_STAGES.join(", ")}) — ignored`);
61
+ continue;
62
+ }
63
+ const names = list(value);
64
+ if (names.length) (cfg.status[type] ??= {})[stage as JiraStage] = names;
65
+ continue;
66
+ }
67
+ switch (key) {
68
+ case "site":
69
+ cfg.site = value.trim().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
70
+ break;
71
+ case "cloudId":
72
+ if (value.trim()) cfg.cloudId = value.trim();
73
+ break;
74
+ case "project":
75
+ cfg.project = value.trim();
76
+ break;
77
+ case "issueTypes":
78
+ cfg.issueTypes = list(value);
79
+ break;
80
+ case "mirror":
81
+ if (/^(asks|all)$/.test(value.trim())) cfg.mirror = value.trim() as "asks" | "all";
82
+ else warn.push(`${where}: flow-jira mirror = "${value}" — expected asks or all, keeping asks`);
83
+ break;
84
+ case "watch": {
85
+ const secs = list(value).map(parseDuration);
86
+ if (!secs.length || secs.some((s) => !s)) warn.push(`${where}: flow-jira watch = "${value}" — expected durations like 30m, 1h — keeping ${DEFAULT_WATCH.map(fmtDuration).join(", ")}`);
87
+ else cfg.watch = secs as number[];
88
+ break;
89
+ }
90
+ case "watchCap": {
91
+ const s = parseDuration(value);
92
+ if (s === undefined) warn.push(`${where}: flow-jira watchCap = "${value}" — expected a duration like 72h — keeping 72h`);
93
+ else cfg.watchCap = s;
94
+ break;
95
+ }
96
+ default:
97
+ warn.push(`${where}: unknown flow-jira key "${key}" — ignored`);
98
+ }
99
+ }
100
+ if (!entries.some((e) => e.line.trim() && !e.line.trim().startsWith("#"))) return { hard, warn };
101
+ if (!cfg.site) hard.push("flow-jira: `site` is required (e.g. site = acme.atlassian.net)");
102
+ if (!cfg.project) hard.push("flow-jira: `project` is required (the Jira project key)");
103
+ if (!cfg.issueTypes.length) hard.push("flow-jira: `issueTypes` is required (the issue types a flow may start from)");
104
+ for (const t of cfg.issueTypes) if (!cfg.status[t]) warn.push(`flow-jira: issue type "${t}" has no status.${t}.<stage> lines — its issues can be linked but no status moves sync`);
105
+ for (const t of Object.keys(cfg.status)) if (!cfg.issueTypes.includes(t)) warn.push(`flow-jira: status.${t}.* names an issue type not in issueTypes — ignored`);
106
+ return { cfg, hard, warn };
107
+ }
108
+
109
+ /** The block body for `cfg` (no fences). */
110
+ export function renderJiraBlock(cfg: JiraConfig): string[] {
111
+ const L = [`site = ${cfg.site}`];
112
+ if (cfg.cloudId) L.push(`cloudId = ${cfg.cloudId}`);
113
+ L.push(`project = ${cfg.project}`, `issueTypes = ${cfg.issueTypes.join(", ")}`);
114
+ for (const t of cfg.issueTypes) for (const s of JIRA_STAGES) if (cfg.status[t]?.[s]?.length) L.push(`status.${t}.${s} = ${cfg.status[t][s]!.join(", ")}`);
115
+ if (cfg.mirror !== "asks") L.push(`mirror = ${cfg.mirror}`);
116
+ if (cfg.watch.join() !== DEFAULT_WATCH.join()) L.push(`watch = ${cfg.watch.map(fmtDuration).join(", ")}`);
117
+ if (cfg.watchCap !== DEFAULT_WATCH_CAP) L.push(`watchCap = ${fmtDuration(cfg.watchCap)}`);
118
+ return L;
119
+ }
120
+
121
+ /** Insert or replace the ` ```flow-jira ` block under ## global (creating the section when missing). */
122
+ export function setJiraBlock(text: string, cfg: JiraConfig): string {
123
+ const body = ["```flow-jira", ...renderJiraBlock(cfg), "```"];
124
+ const lines = text.split("\n");
125
+ const open = lines.findIndex((l) => l.trim() === "```flow-jira");
126
+ if (open !== -1) {
127
+ let close = lines.length - 1;
128
+ for (let j = open + 1; j < lines.length; j++)
129
+ if (lines[j].trim() === "```") {
130
+ close = j;
131
+ break;
132
+ }
133
+ lines.splice(open, close - open + 1, ...body);
134
+ return lines.join("\n");
135
+ }
136
+ const head = lines.findIndex((l) => /^##\s+global\s*$/i.test(l));
137
+ if (head === -1) return `## global\n\n${body.join("\n")}\n\n${text}`;
138
+ let end = lines.length;
139
+ for (let i = head + 1; i < lines.length; i++)
140
+ if (/^##\s/.test(lines[i])) {
141
+ end = i;
142
+ break;
143
+ }
144
+ while (end > head + 1 && lines[end - 1].trim() === "") end--;
145
+ lines.splice(end, 0, "", ...body);
146
+ return lines.join("\n");
147
+ }
148
+
149
+ /** The stage a status name maps to for an issue type, or undefined. */
150
+ export function stageOfStatus(cfg: JiraConfig, type: string, status: string): JiraStage | undefined {
151
+ const m = cfg.status[type];
152
+ if (!m) return undefined;
153
+ const s = status.trim().toLowerCase();
154
+ return JIRA_STAGES.find((st) => m[st]?.some((n) => n.toLowerCase() === s));
155
+ }
156
+
157
+ /** The status dev-flow moves an issue to when its flow enters `stage` (the first listed), or undefined. */
158
+ export const statusForStage = (cfg: JiraConfig, type: string, stage: JiraStage) => cfg.status[type]?.[stage]?.[0];
159
+
160
+ export interface StatusInfo {
161
+ name: string;
162
+ category?: string; // Jira status category key: new | indeterminate | done (or the display name)
163
+ }
164
+
165
+ /** Suggest a stage for each workflow status, from its category and name. Unmatched statuses are left out. */
166
+ export function suggestMapping(statuses: StatusInfo[]): Partial<Record<JiraStage, string[]>> {
167
+ const out: Partial<Record<JiraStage, string[]>> = {};
168
+ const put = (st: JiraStage, n: string) => (out[st] ??= []).push(n);
169
+ for (const { name, category } of statuses) {
170
+ const n = name.toLowerCase();
171
+ const cat = (category ?? "").toLowerCase();
172
+ // names first — a workflow's own words beat its categories ("Plan" is in progress by category)
173
+ if (/review|qa|test|verif|accept/.test(n)) put("pre-release", name);
174
+ else if (/ready.*(release|deploy|ship)|releas|deploy|staging/.test(n)) put("release", name);
175
+ else if (/done|closed|resolved|complete/.test(n)) put("done", name);
176
+ else if (/^plan|planning|design|spec|refine|to ?do|backlog|selected|^open$|^new$/.test(n)) put("plan", name);
177
+ else if (/progress|develop|doing|implement|build|coding/.test(n)) put("implement", name);
178
+ else if (cat === "done") put("done", name);
179
+ else if (cat === "indeterminate" || cat === "in progress") put("implement", name);
180
+ else if (cat === "new" || cat === "to do") put("plan", name);
181
+ }
182
+ // put the most likely "move here" status first: in-progress over in-dev variants, to do over backlog
183
+ const rank = (st: JiraStage, n: string) => {
184
+ const l = n.toLowerCase();
185
+ if (st === "plan") return /^plan/.test(l) ? 0 : /to ?do|selected/.test(l) ? 1 : /backlog/.test(l) ? 3 : 2;
186
+ if (st === "implement") return /in progress/.test(l) ? 0 : 1;
187
+ if (st === "done") return /^done$/.test(l) ? 0 : 1;
188
+ return 0;
189
+ };
190
+ for (const st of JIRA_STAGES) out[st]?.sort((a, b) => rank(st, a) - rank(st, b));
191
+ return out;
192
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Jira credentials — a Cloud API token sent as HTTP Basic `email:token` (the Atlassian Rovo MCP server's
3
+ * API-token auth). They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by
4
+ * `/flow jira login`; `JIRA_EMAIL` / `JIRA_API_TOKEN` (and optionally `JIRA_SITE`) override the file.
5
+ * Never printed, never written to project.md or to a comment.
6
+ */
7
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+
11
+ export interface JiraCreds {
12
+ site: string; // acme.atlassian.net
13
+ email: string;
14
+ token: string;
15
+ source: "env" | "file";
16
+ }
17
+
18
+ export const credsPath = (home = os.homedir()) => path.join(process.env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent"), "dev-flow", "jira.json");
19
+
20
+ /** `https://acme.atlassian.net/…` or `acme.atlassian.net` → `acme.atlassian.net`. */
21
+ export const normSite = (s: string) =>
22
+ s
23
+ .trim()
24
+ .replace(/^https?:\/\//, "")
25
+ .replace(/\/.*$/, "")
26
+ .toLowerCase();
27
+
28
+ type Store = { sites?: Record<string, { email: string; token: string }> };
29
+
30
+ function readStore(file: string): Store {
31
+ try {
32
+ return JSON.parse(readFileSync(file, "utf8")) as Store;
33
+ } catch {
34
+ return {};
35
+ }
36
+ }
37
+
38
+ /** Credentials for `site` (or for the only/first stored site when none is named), or null. */
39
+ export function loadCreds(site?: string, env: NodeJS.ProcessEnv = process.env, file = credsPath()): JiraCreds | null {
40
+ const want = site ? normSite(site) : env.JIRA_SITE ? normSite(env.JIRA_SITE) : undefined;
41
+ if (env.JIRA_EMAIL && env.JIRA_API_TOKEN && (want || env.JIRA_SITE))
42
+ return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env" };
43
+ const sites = readStore(file).sites ?? {};
44
+ const key = want ?? Object.keys(sites)[0];
45
+ const hit = key ? sites[key] : undefined;
46
+ return hit && key ? { site: key, email: hit.email, token: hit.token, source: "file" } : null;
47
+ }
48
+
49
+ export function saveCreds(site: string, email: string, token: string, file = credsPath()): void {
50
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
51
+ const store = existsSync(file) ? readStore(file) : {};
52
+ store.sites = { ...(store.sites ?? {}), [normSite(site)]: { email: email.trim(), token: token.trim() } };
53
+ writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
54
+ chmodSync(file, 0o600);
55
+ }
56
+
57
+ export const basicAuth = (c: Pick<JiraCreds, "email" | "token">) => `Basic ${Buffer.from(`${c.email}:${c.token}`).toString("base64")}`;