pi-dev-flow 0.100.1 → 0.101.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/jira/mcp.ts CHANGED
@@ -32,12 +32,33 @@ export interface McpCallResult {
32
32
 
33
33
  export class McpError extends Error {
34
34
  readonly status?: number;
35
- constructor(message: string, status?: number) {
35
+ /** a failure worth retrying: "network" / "timeout" (no answer), or "http" with a 429/5xx status */
36
+ readonly kind: "http" | "network" | "timeout" | "protocol";
37
+ readonly retryAfterMs?: number;
38
+ constructor(message: string, status?: number, kind: McpError["kind"] = status ? "http" : "protocol", retryAfterMs?: number) {
36
39
  super(message);
37
40
  this.status = status;
41
+ this.kind = kind;
42
+ this.retryAfterMs = retryAfterMs;
38
43
  }
39
44
  }
40
45
 
46
+ /** Whether a failed request may be sent again. A read may always be retried on a transient failure. A write
47
+ * (a comment, an issue, a transition) only when the server said it did not run it — 429 or 503 — so a lost
48
+ * answer never posts the same comment twice. */
49
+ export function retryable(e: unknown, idempotent: boolean): boolean {
50
+ if (!(e instanceof McpError)) return false;
51
+ if (e.kind === "http") return e.status === 429 || e.status === 503 || (idempotent && (e.status === 502 || e.status === 504));
52
+ return idempotent && (e.kind === "network" || e.kind === "timeout");
53
+ }
54
+
55
+ export interface McpOptions {
56
+ timeoutMs?: number;
57
+ /** waits before each retry; its length is the number of retries */
58
+ retryDelaysMs?: number[];
59
+ sleep?: (ms: number) => Promise<void>;
60
+ }
61
+
41
62
  const PROTOCOL = "2025-06-18";
42
63
 
43
64
  /** The JSON-RPC message answering `id` in an SSE body (`data:` lines, events split by a blank line). */
@@ -69,15 +90,32 @@ export class McpClient {
69
90
  private readonly headers: Record<string, string>;
70
91
  private readonly fetchFn: FetchLike;
71
92
  private readonly timeoutMs: number;
93
+ private readonly retryDelaysMs: number[];
94
+ private readonly sleep: (ms: number) => Promise<void>;
72
95
 
73
- constructor(url: string, headers: Record<string, string>, fetchFn: FetchLike = globalThis.fetch as unknown as FetchLike, timeoutMs = 30_000) {
96
+ constructor(url: string, headers: Record<string, string>, fetchFn: FetchLike = globalThis.fetch as unknown as FetchLike, opts: McpOptions = {}) {
74
97
  this.url = url;
75
98
  this.headers = headers;
76
99
  this.fetchFn = fetchFn;
77
- this.timeoutMs = timeoutMs;
100
+ this.timeoutMs = opts.timeoutMs ?? 30_000;
101
+ this.retryDelaysMs = opts.retryDelaysMs ?? [1000, 2000, 4000];
102
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
103
+ }
104
+
105
+ /** One POST, retried with backoff on a transient failure (see `retryable`). */
106
+ private async post(body: unknown, id: number | undefined, idempotent: boolean): Promise<unknown> {
107
+ for (let attempt = 0; ; attempt++) {
108
+ try {
109
+ return await this.postOnce(body, id);
110
+ } catch (e) {
111
+ if (attempt >= this.retryDelaysMs.length || !retryable(e, idempotent)) throw e;
112
+ const wait = (e as McpError).retryAfterMs ?? this.retryDelaysMs[attempt];
113
+ await this.sleep(Math.min(wait, 30_000));
114
+ }
115
+ }
78
116
  }
79
117
 
80
- private async post(body: unknown, id?: number): Promise<unknown> {
118
+ private async postOnce(body: unknown, id?: number): Promise<unknown> {
81
119
  const headers: Record<string, string> = {
82
120
  ...this.headers,
83
121
  "content-type": "application/json",
@@ -91,7 +129,7 @@ export class McpClient {
91
129
  try {
92
130
  res = await this.fetchFn(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: ctl.signal });
93
131
  } catch (e) {
94
- throw new McpError(ctl.signal.aborted ? `timed out after ${this.timeoutMs / 1000}s` : `request failed: ${(e as Error).message}`);
132
+ throw ctl.signal.aborted ? new McpError(`timed out after ${this.timeoutMs / 1000}s`, undefined, "timeout") : new McpError(`request failed: ${(e as Error).message}`, undefined, "network");
95
133
  } finally {
96
134
  clearTimeout(timer);
97
135
  }
@@ -99,8 +137,14 @@ export class McpClient {
99
137
  if (sid) this.sessionId = sid;
100
138
  const text = await res.text();
101
139
  if (!res.ok) {
102
- const hint = res.status === 401 || res.status === 403 ? " — check the email and API token, and that an org admin enabled API-token auth for the Atlassian MCP server" : "";
103
- throw new McpError(`HTTP ${res.status}${hint}${text ? `: ${text.slice(0, 300)}` : ""}`, res.status);
140
+ const hint =
141
+ res.status === 401
142
+ ? " — the Atlassian MCP server refused the token (revoked, expired, or not a scoped API token); the operator re-runs /flow jira login"
143
+ : res.status === 403
144
+ ? " — the token may not use the Atlassian MCP server (an org admin enables API-token auth in Atlassian Administration → Rovo MCP server)"
145
+ : "";
146
+ const ra = Number(res.headers.get("retry-after"));
147
+ throw new McpError(`HTTP ${res.status}${hint}${text ? `: ${text.slice(0, 300)}` : ""}`, res.status, "http", Number.isFinite(ra) && ra > 0 ? ra * 1000 : undefined);
104
148
  }
105
149
  if (id === undefined) return undefined; // a notification: 202, no body
106
150
  const type = res.headers.get("content-type") ?? "";
@@ -112,16 +156,16 @@ export class McpClient {
112
156
  return msg.result;
113
157
  }
114
158
 
115
- private async request(method: string, params?: unknown): Promise<unknown> {
159
+ private async request(method: string, params: unknown, idempotent: boolean): Promise<unknown> {
116
160
  const id = this.nextId++;
117
- return this.post({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }, id);
161
+ return this.post({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }, id, idempotent);
118
162
  }
119
163
 
120
164
  /** Handshake once; a failed handshake is retried by the next call. */
121
165
  init(): Promise<void> {
122
166
  this.ready ??= (async () => {
123
- await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pi-dev-flow", version: "1" } });
124
- await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
167
+ await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pi-dev-flow", version: "1" } }, true);
168
+ await this.post({ jsonrpc: "2.0", method: "notifications/initialized" }, undefined, true);
125
169
  })().catch((e) => {
126
170
  this.ready = undefined;
127
171
  this.sessionId = undefined;
@@ -136,7 +180,7 @@ export class McpClient {
136
180
  const out: McpTool[] = [];
137
181
  let cursor: string | undefined;
138
182
  do {
139
- const r = (await this.request("tools/list", cursor ? { cursor } : {})) as { tools?: McpTool[]; nextCursor?: string };
183
+ const r = (await this.request("tools/list", cursor ? { cursor } : {}, true)) as { tools?: McpTool[]; nextCursor?: string };
140
184
  out.push(...(r.tools ?? []));
141
185
  cursor = r.nextCursor;
142
186
  } while (cursor);
@@ -144,17 +188,20 @@ export class McpClient {
144
188
  return out;
145
189
  }
146
190
 
147
- async callTool(name: string, args: Record<string, unknown>): Promise<McpCallResult> {
191
+ /** Call a tool. `idempotent` (a read) lets a lost answer be retried; a write is retried only when the
192
+ * server said it did not run it. */
193
+ async callTool(name: string, args: Record<string, unknown>, opts: { idempotent?: boolean } = {}): Promise<McpCallResult> {
194
+ const idem = opts.idempotent ?? false;
148
195
  await this.init();
149
196
  try {
150
- return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
197
+ return (await this.request("tools/call", { name, arguments: args }, idem)) as McpCallResult;
151
198
  } catch (e) {
152
- // an expired server session: start over once
199
+ // an expired server session: start over once (the call never reached a live session, so it did not run)
153
200
  if (e instanceof McpError && e.status === 404 && this.sessionId) {
154
201
  this.ready = undefined;
155
202
  this.sessionId = undefined;
156
203
  await this.init();
157
- return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
204
+ return (await this.request("tools/call", { name, arguments: args }, idem)) as McpCallResult;
158
205
  }
159
206
  throw e;
160
207
  }
package/src/jira/sync.ts CHANGED
@@ -27,10 +27,11 @@ export function answeringStatus(cfg: JiraConfig, link: JiraLink, ask: string | u
27
27
  }
28
28
 
29
29
  /** A mirrored question (or closing message) as a Jira comment, in markdown. */
30
- export function formatComment(o: { slug: string; ask?: string; text: string; attachments?: string[]; answerStatus?: string }): string {
30
+ export function formatComment(o: { slug: string; ask?: string; text: string; plan?: string; attachments?: string[]; answerStatus?: string }): string {
31
31
  const L: string[] = [];
32
32
  if (o.ask) L.push(`**dev-flow is waiting on: ${o.ask}**`, "");
33
33
  L.push(o.text.trim());
34
+ if (o.plan) L.push("", `**${o.plan}**`);
34
35
  if (o.attachments?.length) L.push("", `Attached: ${o.attachments.join(", ")}`);
35
36
  if (o.ask) L.push("", `_Answer with a comment here${o.answerStatus ? `, or move the issue to **${o.answerStatus}**` : ""}._`);
36
37
  L.push("", `${MARKER} ${o.slug}`);
@@ -0,0 +1,209 @@
1
+ /** plan.md as a printable HTML page — the source of the plan PDF attached to a linked Jira issue. Pure, no I/O.
2
+ *
3
+ * A small CommonMark subset, enough for a plan: headings, paragraphs, fenced code, lists (nested, task boxes),
4
+ * pipe tables, block quotes, rules, and inline code, emphasis, links and images. Raw HTML is shown as text.
5
+ * Images resolve against `base` (the plan folder), so the mockups plan.md embeds print inside the PDF. */
6
+
7
+ const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
8
+
9
+ const FENCE = /^\s{0,3}(`{3,}|~{3,})(.*)$/;
10
+ const HEADING = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
11
+ const RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
12
+ const QUOTE = /^\s{0,3}>\s?/;
13
+ const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
14
+ const TABLE_SEP = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
15
+
16
+ /** Inline markdown → HTML: code spans first (their text is literal), then images, links, emphasis. */
17
+ export function inline(text: string): string {
18
+ const codes: string[] = [];
19
+ let s = text.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g, (_m, _t, c: string) => {
20
+ codes.push(`<code>${esc(c.trim() === "" ? c : c.replace(/^ (.*) $/, "$1"))}</code>`);
21
+ return `\u0000${codes.length - 1}\u0000`;
22
+ });
23
+ s = esc(s);
24
+ s = s.replace(/!\[([^\]]*)\]\(\s*(?:&lt;)?([^\s)]+?)(?:&gt;)?(?:\s+&quot;([^)]*)&quot;)?\s*\)/g, (_m, alt: string, src: string, title?: string) => `<img src="${src}" alt="${alt}"${title ? ` title="${title}"` : ""}>`);
25
+ s = s.replace(/\[([^\]]+)\]\(\s*(?:&lt;)?([^\s)]+?)(?:&gt;)?(?:\s+&quot;[^)]*&quot;)?\s*\)/g, (_m, t: string, href: string) => `<a href="${href}">${t}</a>`);
26
+ s = s.replace(/(^|[\s(])(https?:\/\/[^\s<)]+[^\s<).,;:!?])/g, (_m, pre: string, url: string) => `${pre}<a href="${url}">${url}</a>`);
27
+ s = s.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, "<strong>$2</strong>");
28
+ s = s.replace(/(^|[^\w*])\*(?=\S)([^*]*?\S)\*(?!\*)/g, "$1<em>$2</em>");
29
+ s = s.replace(/(^|[^\w_])_(?=\S)([^_]*?\S)_(?!\w)/g, "$1<em>$2</em>");
30
+ s = s.replace(/~~(?=\S)([\s\S]*?\S)~~/g, "<del>$1</del>");
31
+ s = s.replace(/ {2,}\n|\\\n/g, "<br>\n");
32
+ return s.replace(/\u0000(\d+)\u0000/g, (_m, i: string) => codes[Number(i)]);
33
+ }
34
+
35
+ const cells = (line: string) =>
36
+ line
37
+ .trim()
38
+ .replace(/^\|/, "")
39
+ .replace(/(?<!\\)\|$/, "")
40
+ .split(/(?<!\\)\|/)
41
+ .map((c) => c.trim().replace(/\\\|/g, "|"));
42
+
43
+ const indentOf = (line: string) => line.replace(/\t/g, " ").match(/^ */)![0].length;
44
+
45
+ /** Strip `n` columns of leading indentation (tabs count as four). */
46
+ const dedent = (line: string, n: number) => {
47
+ const l = line.replace(/^\t+/, (t) => " ".repeat(t.length));
48
+ return l.slice(Math.min(n, indentOf(l)));
49
+ };
50
+
51
+ const startsBlock = (line: string, next: string | undefined) =>
52
+ FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || ITEM.test(line) || (line.includes("|") && next !== undefined && TABLE_SEP.test(next) && next.includes("-"));
53
+
54
+ /** Block markdown → HTML. */
55
+ export function blocks(md: string): string {
56
+ const lines = md.replace(/\r\n?/g, "\n").split("\n");
57
+ const out: string[] = [];
58
+ let i = 0;
59
+ while (i < lines.length) {
60
+ const line = lines[i];
61
+ if (!line.trim()) {
62
+ i++;
63
+ continue;
64
+ }
65
+ const fence = line.match(FENCE);
66
+ if (fence) {
67
+ const close = new RegExp(`^\\s{0,3}${fence[1][0] === "`" ? "`" : "~"}{${fence[1].length},}\\s*$`);
68
+ const body: string[] = [];
69
+ i++;
70
+ while (i < lines.length && !close.test(lines[i])) body.push(lines[i++]);
71
+ i++;
72
+ const lang = fence[2].trim().split(/\s+/)[0];
73
+ out.push(`<pre><code${lang ? ` class="language-${esc(lang)}"` : ""}>${esc(body.join("\n"))}</code></pre>`);
74
+ continue;
75
+ }
76
+ const h = line.match(HEADING);
77
+ if (h) {
78
+ out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
79
+ i++;
80
+ continue;
81
+ }
82
+ if (RULE.test(line)) {
83
+ out.push("<hr>");
84
+ i++;
85
+ continue;
86
+ }
87
+ if (QUOTE.test(line)) {
88
+ const body: string[] = [];
89
+ while (i < lines.length && lines[i].trim() && (QUOTE.test(lines[i]) || !startsBlock(lines[i], lines[i + 1]))) body.push(lines[i++].replace(QUOTE, ""));
90
+ out.push(`<blockquote>${blocks(body.join("\n"))}</blockquote>`);
91
+ continue;
92
+ }
93
+ if (line.includes("|") && i + 1 < lines.length && TABLE_SEP.test(lines[i + 1]) && lines[i + 1].includes("-")) {
94
+ const head = cells(line);
95
+ const align = cells(lines[i + 1]).map((c) => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : c.startsWith(":") ? "left" : ""));
96
+ const a = (k: number) => (align[k] ? ` style="text-align:${align[k]}"` : "");
97
+ i += 2;
98
+ const rows: string[][] = [];
99
+ while (i < lines.length && lines[i].trim() && lines[i].includes("|")) rows.push(cells(lines[i++]));
100
+ out.push(
101
+ `<table><thead><tr>${head.map((c, k) => `<th${a(k)}>${inline(c)}</th>`).join("")}</tr></thead><tbody>${rows
102
+ .map((r) => `<tr>${head.map((_c, k) => `<td${a(k)}>${inline(r[k] ?? "")}</td>`).join("")}</tr>`)
103
+ .join("")}</tbody></table>`,
104
+ );
105
+ continue;
106
+ }
107
+ const item = line.match(ITEM);
108
+ if (item) {
109
+ const base = indentOf(line);
110
+ const ordered = /\d/.test(item[2]);
111
+ const items: { lines: string[]; contentIndent: number }[] = [];
112
+ let loose = false;
113
+ while (i < lines.length) {
114
+ const l = lines[i];
115
+ const m = l.match(ITEM);
116
+ if (m && indentOf(l) === base && /\d/.test(m[2]) === ordered) {
117
+ const gap = l.slice(l.search(/\S/) + m[2].length).match(/^ */)![0].length;
118
+ items.push({ lines: [m[3]], contentIndent: indentOf(l) + m[2].length + Math.min(Math.max(gap, 1), 4) });
119
+ i++;
120
+ continue;
121
+ }
122
+ if (!l.trim()) {
123
+ // a blank line continues the list only when more of it follows, indented or as a sibling
124
+ let j = i + 1;
125
+ while (j < lines.length && !lines[j].trim()) j++;
126
+ const nx = lines[j];
127
+ if (nx !== undefined && (indentOf(nx) > base || (ITEM.test(nx) && indentOf(nx) === base && /\d/.test(nx.match(ITEM)![2]) === ordered))) {
128
+ if (indentOf(nx) === base) loose = true;
129
+ items.at(-1)!.lines.push("");
130
+ i++;
131
+ continue;
132
+ }
133
+ break;
134
+ }
135
+ if (indentOf(l) > base) {
136
+ items.at(-1)!.lines.push(dedent(l, items.at(-1)!.contentIndent));
137
+ i++;
138
+ continue;
139
+ }
140
+ // a lazy continuation of the item's paragraph
141
+ if (!startsBlock(l, lines[i + 1]) && items.at(-1)!.lines.at(-1)?.trim()) {
142
+ items.at(-1)!.lines.push(l.trim());
143
+ i++;
144
+ continue;
145
+ }
146
+ break;
147
+ }
148
+ const start = ordered ? Number(item[2].replace(/\D/g, "")) : 1;
149
+ const tag = ordered ? "ol" : "ul";
150
+ const lis = items.map((it) => {
151
+ let first = it.lines[0];
152
+ let box = "";
153
+ const t = first.match(/^\[([ xX])\]\s+(.*)$/);
154
+ if (t) {
155
+ box = `<span class="box">${t[1] === " " ? "☐" : "☑"}</span> `;
156
+ first = t[2];
157
+ }
158
+ const body = [first, ...it.lines.slice(1)];
159
+ let html = blocks(body.join("\n"));
160
+ if (!loose) html = html.replace(/^<p>([\s\S]*?)<\/p>/, "$1");
161
+ return `<li${box ? ' class="task"' : ""}>${box}${html}</li>`;
162
+ });
163
+ out.push(`<${tag}${ordered && start !== 1 ? ` start="${start}"` : ""}>${lis.join("")}</${tag}>`);
164
+ continue;
165
+ }
166
+ const para: string[] = [line.trim()];
167
+ i++;
168
+ while (i < lines.length && lines[i].trim() && !startsBlock(lines[i], lines[i + 1])) para.push(lines[i++].replace(/^\s+/, ""));
169
+ out.push(`<p>${inline(para.join("\n"))}</p>`);
170
+ }
171
+ return out.join("\n");
172
+ }
173
+
174
+ const CSS = `
175
+ @page { size: A4; margin: 16mm 14mm; }
176
+ * { box-sizing: border-box; }
177
+ body { font: 10.5pt/1.5 -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif; color: #1f2328; margin: 0; }
178
+ header.meta { color: #59636e; font-size: 9pt; border-bottom: 1px solid #d1d9e0; padding-bottom: 6px; margin-bottom: 14px; }
179
+ h1, h2, h3, h4, h5, h6 { line-height: 1.25; margin: 1.2em 0 0.5em; break-after: avoid; }
180
+ h1 { font-size: 20pt; margin-top: 0; } h2 { font-size: 15pt; border-bottom: 1px solid #d1d9e0; padding-bottom: 3px; } h3 { font-size: 12.5pt; } h4, h5, h6 { font-size: 11pt; }
181
+ p, ul, ol, table, pre, blockquote { margin: 0 0 0.8em; }
182
+ ul, ol { padding-left: 1.6em; } li > ul, li > ol { margin: 0.2em 0; } li.task { list-style: none; margin-left: -1.3em; }
183
+ code { font: 9pt/1.4 ui-monospace, "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace; background: #f6f8fa; padding: 0.1em 0.3em; border-radius: 4px; }
184
+ pre { background: #f6f8fa; padding: 10px 12px; border-radius: 6px; white-space: pre-wrap; word-break: break-word; }
185
+ pre code { background: none; padding: 0; }
186
+ blockquote { color: #59636e; border-left: 3px solid #d1d9e0; padding: 0 0 0 12px; margin-left: 0; }
187
+ table { border-collapse: collapse; width: 100%; font-size: 9.5pt; }
188
+ th, td { border: 1px solid #d1d9e0; padding: 4px 8px; text-align: left; vertical-align: top; }
189
+ th { background: #f6f8fa; } tr { break-inside: avoid; }
190
+ img { max-width: 100%; max-height: 235mm; break-inside: avoid; border: 1px solid #d1d9e0; border-radius: 4px; vertical-align: top; }
191
+ a { color: #0969da; text-decoration: none; }
192
+ hr { border: 0; border-top: 1px solid #d1d9e0; margin: 1.2em 0; }
193
+ `;
194
+
195
+ /** The whole page: plan.md rendered under a one-line header (`meta`), images resolved against `base`. */
196
+ export function planHtml(md: string, o: { title: string; meta?: string; base?: string }): string {
197
+ return [
198
+ "<!DOCTYPE html>",
199
+ '<html><head><meta charset="utf-8">',
200
+ o.base ? `<base href="${esc(o.base)}">` : "",
201
+ `<title>${esc(o.title)}</title>`,
202
+ `<style>${CSS}</style>`,
203
+ "</head><body>",
204
+ o.meta ? `<header class="meta">${esc(o.meta)}</header>` : "",
205
+ blocks(md),
206
+ "</body></html>",
207
+ "",
208
+ ].join("\n");
209
+ }
@@ -4,7 +4,8 @@
4
4
  * Nothing here runs for a project without a flow-jira block, and nothing here fails a gate: a Jira error is a
5
5
  * note in the gate's output. The watch timers and the pi-web liveness lease live in extensions/dev-flow.ts. */
6
6
  import { createHash } from "node:crypto";
7
- import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync, copyFileSync } from "node:fs";
7
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, copyFileSync } from "node:fs";
8
+ import os from "node:os";
8
9
  import path from "node:path";
9
10
  import { type Config, type FlowState, type JiraConfig, type JiraLink, type JiraStage, needsOperator, sq, parseRowIds, roadmapBriefFor, roadmapItemAt, roadmapItemTitle, roadmapJiraKey, roadmapStampJira } from "../core.ts";
10
11
  import { parseProjectMd } from "../projectmd.ts";
@@ -16,6 +17,7 @@ import { type Relay, answeringStatus, classifyActivity, formatComment, issueBrie
16
17
  import { AGENT_MARK } from "../present.ts";
17
18
  import { dfDir, featDir, flagValue, now, readRoadmap, readState, roadmapFile, sh, tail, unfinishedStates, worktreeAbs, writeState } from "./base.ts";
18
19
  import type { RunResult } from "./checks.ts";
20
+ import { renderPlanPdf } from "./planpdf.ts";
19
21
 
20
22
  /** Test seams: a fake Atlassian server (fetch), the credentials file, the clock. */
21
23
  export const jiraSeams: { fetch?: FetchLike; credsFile?: string; env?: NodeJS.ProcessEnv } = {};
@@ -30,7 +32,7 @@ export function jiraClient(cfg: Pick<JiraConfig, "site" | "cloudId">): { client:
30
32
  }
31
33
 
32
34
  function clientFor(creds: JiraCreds, cloudId?: string): JiraClient {
33
- const id = `${creds.site}\0${creds.email}\0${createHash("sha1").update(creds.token).digest("hex")}\0${cloudId ?? ""}\0${jiraSeams.fetch ? "seam" : ""}`;
35
+ const id = `${creds.site}\0${createHash("sha1").update(creds.token).digest("hex")}\0${cloudId ?? ""}\0${jiraSeams.fetch ? "seam" : ""}`;
34
36
  let c = clients.get(id);
35
37
  if (!c) {
36
38
  c = new JiraClient(creds, { cloudId, fetch: jiraSeams.fetch });
@@ -43,7 +45,7 @@ function clientFor(creds: JiraCreds, cloudId?: string): JiraClient {
43
45
  export const resetJiraClients = () => clients.clear();
44
46
 
45
47
  const noCreds = (site?: string) =>
46
- `no Jira credentials${site ? ` for ${site}` : ""} — the operator runs /flow jira login${site ? ` ${site}` : ""} (an Atlassian Cloud API token; stored in ~/.pi/agent/dev-flow/jira.json, mode 0600), or sets JIRA_SITE, JIRA_EMAIL and JIRA_API_TOKEN. The token never goes through the chat.`;
48
+ `no Jira credentials${site ? ` for ${site}` : ""} — the operator runs /flow jira login${site ? ` ${site}` : ""} (a scoped Atlassian Cloud API token; stored in ~/.pi/agent/dev-flow/jira.json, mode 0600), or sets JIRA_SITE and JIRA_API_TOKEN. The token never goes through the chat.`;
47
49
 
48
50
  const sha1 = (b: string | Buffer) => createHash("sha1").update(b).digest("hex");
49
51
 
@@ -58,8 +60,8 @@ export async function gateJiraInit(root: string, cfg: Config, rest: string[], fl
58
60
  const creds = loadCreds(siteArg ?? cfg.jira?.site, jiraSeams.env ?? process.env, jiraSeams.credsFile ?? credsPath());
59
61
  if (!creds) return { text: needsOperator(noCreds(siteArg ?? cfg.jira?.site), "Jira login?", "ask the operator to run /flow jira login (never ask them to paste the token into the chat); once they say it is done, re-run flow jira init"), isError: true };
60
62
  const client = clientFor(creds, cfg.jira?.site === creds.site ? cfg.jira.cloudId : undefined);
61
- const me = await client.me();
62
- if (!me.ok) return { text: `Jira authentication failed on ${creds.site} (${creds.source === "env" ? "JIRA_EMAIL/JIRA_API_TOKEN" : "stored login"}): ${me.error}\nThe Atlassian MCP server needs a scoped API token (read:jira:agent-interface, write:jira:agent-interface; sent as Bearer), and an org admin must have enabled API-token authentication for it (Atlassian Administration → Rovo MCP server). Check the token (/flow jira login re-enters it).`, isError: true };
63
+ const me = await client.check();
64
+ if (!me.ok) return { text: `Jira check failed on ${creds.site} (${creds.source === "env" ? "JIRA_API_TOKEN" : "stored login"}): ${me.error}`, isError: true };
63
65
  const head = `Jira: authenticated as ${me.value.displayName} on ${creds.site} (Atlassian MCP server)`;
64
66
 
65
67
  const project = flagValue(rest, "project") ?? cfg.jira?.project;
@@ -180,11 +182,13 @@ export async function linkFlow(root: string, cfg: Config, slug: string, key: str
180
182
  const { client, issue } = r;
181
183
  const link: JiraLink = { key: issue.key, type: cfg.jira.issueTypes.find((t) => t.toLowerCase() === issue.type.toLowerCase())!, site: cfg.jira.site, accountId: r.accountId, posted: [], seenUntil: now(), lastStatus: issue.status };
182
184
  const lines = [`linked to Jira ${issue.key} — ${issue.summary} (${issue.type}, ${issue.status}) ${issue.url}`];
185
+ let seeded = false;
183
186
  if (opts.seedPlan && state.stage === "plan") {
184
187
  const planMd = path.join(featDir(root, slug), "plan", "plan.md");
185
188
  const brief = issueBrief(issue);
186
189
  if (!existsSync(planMd)) {
187
190
  writeFileSync(planMd, brief);
191
+ seeded = true;
188
192
  lines.push("the issue's summary and description seeded plan/plan.md — a draft: plan it out and approve as usual");
189
193
  } else if (!readFileSync(planMd, "utf8").includes(issue.url)) {
190
194
  writeFileSync(planMd, `${readFileSync(planMd, "utf8").trimEnd()}\n\n${brief.replace(/^# .*\n/, "## Jira issue\n")}`);
@@ -202,6 +206,7 @@ export async function linkFlow(root: string, cfg: Config, slug: string, key: str
202
206
  const ids = existing.value.map((c) => c.id).filter((id) => /^\d+$/.test(id));
203
207
  if (ids.length) link.seenCommentId = ids.reduce((a, b) => (Number(b) > Number(a) ? b : a));
204
208
  }
209
+ if (seeded) link.seeded = planDigest(path.join(featDir(root, slug), "plan")) ?? undefined;
205
210
  writeState(root, { ...state, jira: link });
206
211
  const moved = await moveToStage(root, cfg, slug, state.stage);
207
212
  if (moved) lines.push(moved);
@@ -267,10 +272,83 @@ export async function syncStageMoves(root: string, cfg: Config, before: Map<stri
267
272
  return out;
268
273
  }
269
274
 
275
+ /** The images plan.md embeds that live under the plan folder — the mockups its PDF prints. */
276
+ function embeddedImages(planDir: string, md: string): string[] {
277
+ const out = new Set<string>();
278
+ for (const m of md.matchAll(/!\[[^\]]*\]\(\s*<?([^\s)>]+)>?/g)) {
279
+ if (/^[a-z][\w+.-]*:/i.test(m[1])) continue; // a URL, not a file
280
+ let ref = m[1];
281
+ try {
282
+ ref = decodeURI(ref);
283
+ } catch {
284
+ /* a stray % — take it literally */
285
+ }
286
+ const f = path.resolve(planDir, ref);
287
+ if (f.startsWith(planDir + path.sep) && existsSync(f) && statSync(f).isFile()) out.add(f);
288
+ }
289
+ return [...out].sort();
290
+ }
291
+
292
+ /** A plan iteration's identity: plan.md and every image it embeds — a re-rendered mockup is a new iteration. */
293
+ function planDigest(planDir: string): string | null {
294
+ const planMd = path.join(planDir, "plan.md");
295
+ if (!existsSync(planMd)) return null;
296
+ const md = readFileSync(planMd, "utf8");
297
+ const h = createHash("sha1").update(md);
298
+ for (const f of embeddedImages(planDir, md)) h.update(`\0${path.relative(planDir, f)}\0`).update(readFileSync(f));
299
+ return h.digest("hex");
300
+ }
301
+
302
+ /** The plan as it stands, for a comment: a PDF of plan.md with its mockups printed in, one per iteration and
303
+ * named for it (`DEV-7-plan-v2.pdf`), so every round of the plan discussion on the issue has its own. An
304
+ * unchanged plan is not attached again: `unchanged` names the PDF that carries it. No chromium (or a failed
305
+ * print): plan.md and its mockups are attached as files instead, and `pdfError` says why. */
306
+ async function attachPlan(client: JiraClient, root: string, st: FlowState, link: JiraLink, hashes: Set<string>): Promise<{ attached: string[]; failed: string[]; plans: { hash: string; name: string }[]; name?: string; unchanged?: boolean; pdfError?: string } | null> {
307
+ const planDir = path.join(featDir(root, st.slug), "plan");
308
+ const digest = planDigest(planDir);
309
+ if (!digest) return null;
310
+ const plans = [...(link.plans ?? [])];
311
+ const prior = plans.find((p) => p.hash === digest);
312
+ if (prior) return { attached: [], failed: [], plans, name: prior.name, unchanged: true };
313
+ const n = plans.length + 1;
314
+ const name = `${link.key}-plan-v${n}.pdf`;
315
+ const title = readFileSync(path.join(planDir, "plan.md"), "utf8").match(/^# (.+)$/m)?.[1]?.trim() ?? st.slug;
316
+ const tmp = mkdtempSync(path.join(os.tmpdir(), "dev-flow-plan-"));
317
+ try {
318
+ const out = path.join(tmp, name);
319
+ const pdf = await renderPlanPdf(planDir, out, { title: `${link.key} plan v${n} — ${title}`, meta: `${link.key} · dev-flow ${st.slug} · plan v${n} · ${now().slice(0, 16).replace("T", " ")} UTC` });
320
+ if (pdf.ok) {
321
+ const r = await client.upload(link.key, out);
322
+ if (!r.ok) return { attached: [], failed: [`${name} (${r.error})`], plans };
323
+ plans.push({ hash: digest, name });
324
+ return { attached: [name], failed: [], plans, name };
325
+ }
326
+ // no PDF: the files themselves, each once
327
+ const attached: string[] = [];
328
+ const failed: string[] = [];
329
+ const mock = path.join(planDir, "mockups");
330
+ const files = [path.join(planDir, "plan.md"), ...(existsSync(mock) ? readdirSync(mock).filter((f) => /\.(png|jpe?g|gif|webp)$/i.test(f)).map((f) => path.join(mock, f)) : [])];
331
+ for (const f of files) {
332
+ const h = sha1(readFileSync(f));
333
+ if (hashes.has(h)) continue;
334
+ const r = await client.upload(link.key, f);
335
+ if (r.ok) {
336
+ attached.push(path.basename(f));
337
+ hashes.add(h);
338
+ } else failed.push(`${path.basename(f)} (${r.error})`);
339
+ }
340
+ return { attached, failed, plans, pdfError: pdf.error };
341
+ } finally {
342
+ rmSync(tmp, { recursive: true, force: true });
343
+ }
344
+ }
345
+
346
+ const planNote = (pa: { pdfError?: string } | null) => (pa?.pdfError ? `; no plan PDF — ${pa.pdfError}, so plan.md was attached as is` : "");
347
+
270
348
  /** The approved plan on the issue, however the approval came: the Approve? question is mirrored only when the
271
349
  * agent closes its turn on it in a linked flow, and an approval given in chat — or a link made at approval
272
- * time — never reaches that point. Attaches plan.md and the mockups not already attached; the comment carries
273
- * the plan itself unless an unchanged copy is already on the issue. Returns a gate-output line. */
350
+ * time — never reaches that point. Attaches the plan PDF unless this iteration's is already on the issue; the
351
+ * comment carries the plan itself unless an unchanged copy is already there. Returns a gate-output line. */
274
352
  export async function postApprovedPlan(root: string, cfg: Config, slug: string): Promise<string | null> {
275
353
  const st = readState(root, slug);
276
354
  if (!cfg.jira || !st?.jira) return null;
@@ -281,49 +359,34 @@ export async function postApprovedPlan(root: string, cfg: Config, slug: string):
281
359
  const link = st.jira;
282
360
  const plan = readFileSync(planMd, "utf8");
283
361
  const hashes = new Set(link.attached ?? []);
284
- const already = hashes.has(sha1(plan)); // the Approve? mirror attached this very plan
285
- const mock = path.join(featDir(root, slug), "plan", "mockups");
286
- const files = [planMd, ...(existsSync(mock) ? readdirSync(mock).filter((f) => /\.(png|jpe?g|gif|webp)$/i.test(f)).map((f) => path.join(mock, f)) : [])];
287
- const attached: string[] = [];
288
- const failed: string[] = [];
289
- for (const f of files) {
290
- const h = sha1(readFileSync(f));
291
- if (hashes.has(h)) continue;
292
- const r = await c.client.upload(link.key, f);
293
- if (r.ok) {
294
- attached.push(path.basename(f));
295
- hashes.add(h);
296
- } else failed.push(`${path.basename(f)} (${r.error})`);
297
- }
362
+ const legacy = hashes.has(sha1(plan)); // plan.md itself went up with the question (no chromium then)
363
+ const pa = await attachPlan(c.client, root, st, link, hashes);
364
+ const already = !!pa?.unchanged || legacy;
298
365
  const call = st.versionChoice ? ` Release call: ${st.versionChoice}.` : "";
299
366
  const mode = st.patch ? " (patch)" : st.docs ? " (docs)" : "";
300
367
  const body = already
301
- ? `Plan approved${mode} — the copy posted with the question is the one approved.${call}`
302
- : `**Plan approved${mode}** — implementation starts.${call}\n\n${plan.length > 24_000 ? `_(the plan is long — see the attached plan.md)_` : plan.trim()}`;
368
+ ? `Plan approved${mode} — the copy posted with the question${pa?.unchanged ? ` (${pa.name})` : ""} is the one approved.${call}`
369
+ : `**Plan approved${mode}** — implementation starts.${call}\n\n${plan.length > 24_000 ? `_(the plan is long — see the attached ${pa?.name ?? "plan.md"})_` : plan.trim()}`;
370
+ const attached = pa?.attached ?? [];
371
+ const failed = pa?.failed ?? [];
303
372
  const r = await c.client.comment(link.key, formatComment({ slug, text: body, attachments: attached }));
304
373
  const fresh = readState(root, slug) ?? st;
305
- const next: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes] };
374
+ const next: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], ...(pa ? { plans: pa.plans } : {}) };
306
375
  if (r.ok && r.value) next.posted = [...next.posted, r.value];
307
376
  writeState(root, { ...fresh, jira: next });
308
377
  if (!r.ok) return `${AGENT_MARK}jira: the approved plan was not posted to ${link.key}: ${r.error}`;
309
- return `Jira ${link.key}: approved plan posted${attached.length ? ` with ${attached.join(", ")}` : ""}${failed.length ? ` (not attached: ${failed.join("; ")})` : ""}`;
378
+ return `Jira ${link.key}: approved plan posted${attached.length ? ` with ${attached.join(", ")}` : ""}${failed.length ? ` (not attached: ${failed.join("; ")})` : ""}${planNote(pa)}`;
310
379
  }
311
380
 
312
381
  // ---------------------------------------------------------------- outbound: the closing-message mirror
313
382
 
314
383
  const IMG = /(?:^|[\s(`'"[])((?:\.{0,2}\/|\/)?[\w@.\-/]+\.(?:png|jpe?g|gif|webp))(?=$|[\s)`'",\]:;])/gi;
315
384
 
316
- /** Files a mirrored message attaches: the plan and its mockups at Approve?, plus every image the message names
317
- * that exists under the feature folder, its worktree or the repo — never anything outside the repo. */
385
+ /** Images a mirrored message attaches: every image the message names that exists under the feature folder, its
386
+ * worktree or the repo — never anything outside the repo. (The plan goes as a PDF: attachPlan.) */
318
387
  export function attachmentsFor(root: string, state: FlowState, text: string): string[] {
319
388
  const fd = featDir(root, state.slug);
320
389
  const out = new Set<string>();
321
- if (state.pendingAsk === "Approve?") {
322
- const plan = path.join(fd, "plan", "plan.md");
323
- if (existsSync(plan)) out.add(plan);
324
- const mock = path.join(fd, "plan", "mockups");
325
- if (existsSync(mock)) for (const f of readdirSync(mock)) if (/\.(png|jpe?g|gif|webp)$/i.test(f)) out.add(path.join(mock, f));
326
- }
327
390
  const bases = [fd, state.worktree ? worktreeAbs(root, state) : null, root].filter((b): b is string => !!b && existsSync(b));
328
391
  let realRoot = root;
329
392
  try {
@@ -349,6 +412,13 @@ export function attachmentsFor(root: string, state: FlowState, text: string): st
349
412
  return [...out].slice(0, 10);
350
413
  }
351
414
 
415
+ /** plan.md is still exactly the issue's own brief the link seeded — any edit, a first draft included, gets a PDF. */
416
+ function isSeed(root: string, st: FlowState, link: JiraLink): boolean {
417
+ const planDir = path.join(featDir(root, st.slug), "plan");
418
+ if (!existsSync(path.join(planDir, "plan.md"))) return true;
419
+ return !!link.seeded && planDigest(planDir) === link.seeded;
420
+ }
421
+
352
422
  /** Mirror the agent's closing message to the linked issue when the playbook's `mirror` says so. Arms the watch
353
423
  * when it asks something. Returns what happened (for a display note), or null when nothing was posted. */
354
424
  export async function mirrorClosingMessage(root: string, cfg: Config, slug: string, text: string): Promise<{ posted: boolean; watch: boolean; note: string } | null> {
@@ -361,11 +431,23 @@ export async function mirrorClosingMessage(root: string, cfg: Config, slug: stri
361
431
  if (link.mirrored === digest) return null;
362
432
  const c = jiraClient(cfg.jira);
363
433
  if ("error" in c) return { posted: false, watch: false, note: `Jira ${link.key}: not mirrored — ${c.error}` };
364
- const files = attachmentsFor(root, st, text);
365
434
  const attached: string[] = [];
366
435
  const failed: string[] = [];
367
436
  const hashes = new Set(link.attached ?? []);
368
- for (const f of files) {
437
+ // at plan, a message carries the plan as it stands: a new PDF for each new iteration, else a pointer to the
438
+ // one already on the issue when the message is about the plan — never the seed the issue itself gave
439
+ let planLine = "";
440
+ let pa: Awaited<ReturnType<typeof attachPlan>> = null;
441
+ if (st.stage === "plan" && !isSeed(root, st, link)) {
442
+ pa = await attachPlan(c.client, root, st, link, hashes);
443
+ if (pa) {
444
+ attached.push(...pa.attached);
445
+ failed.push(...pa.failed);
446
+ if (pa.name && !pa.unchanged) planLine = `Plan: ${pa.name} (attached; plan.md with its mockups)`;
447
+ else if (pa.name && (st.pendingAsk === "Approve?" || /\bplan\b/i.test(text))) planLine = `Plan: ${pa.name} (unchanged, attached earlier)`;
448
+ }
449
+ }
450
+ for (const f of attachmentsFor(root, st, text)) {
369
451
  const h = sha1(readFileSync(f));
370
452
  if (hashes.has(h)) continue;
371
453
  const r = await c.client.upload(link.key, f);
@@ -375,15 +457,15 @@ export async function mirrorClosingMessage(root: string, cfg: Config, slug: stri
375
457
  } else failed.push(`${path.basename(f)} (${r.error})`);
376
458
  }
377
459
  const ask = asks ? (st.pendingAsk ?? "your answer") : undefined;
378
- const body = formatComment({ slug, ask, text, attachments: attached, answerStatus: answeringStatus(cfg.jira, link, st.pendingAsk) });
460
+ const body = formatComment({ slug, ask, text, plan: planLine, attachments: attached.filter((a) => a !== pa?.name), answerStatus: answeringStatus(cfg.jira, link, st.pendingAsk) });
379
461
  const r = await c.client.comment(link.key, body);
380
462
  const fresh = readState(root, slug) ?? st;
381
- const nextLink: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], mirrored: digest };
463
+ const nextLink: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], mirrored: digest, ...(pa ? { plans: pa.plans } : {}) };
382
464
  if (r.ok && r.value) nextLink.posted = [...nextLink.posted, r.value];
383
465
  if (r.ok && ask) nextLink.watch = { ask, since: now(), checks: 0 };
384
466
  writeState(root, { ...fresh, jira: nextLink });
385
467
  if (!r.ok) return { posted: false, watch: false, note: `Jira ${link.key}: could not post the comment — ${r.error}` };
386
- return { posted: true, watch: !!ask, note: `posted to Jira ${link.key}${attached.length ? ` with ${attached.join(", ")}` : ""}${failed.length ? ` (not attached: ${failed.join("; ")})` : ""}${ask ? " — answer there or here" : ""}` };
468
+ return { posted: true, watch: !!ask, note: `posted to Jira ${link.key}${attached.length ? ` with ${attached.join(", ")}` : ""}${failed.length ? ` (not attached: ${failed.join("; ")})` : ""}${planNote(pa)}${ask ? " — answer there or here" : ""}` };
387
469
  }
388
470
 
389
471
  // ---------------------------------------------------------------- inbound: one reply check