pi-dev-flow 0.100.2 → 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/CHANGELOG.md +7 -0
- package/README.md +2 -2
- package/docs/jira.md +4 -3
- package/package.json +1 -1
- package/src/core.ts +4 -0
- package/src/jira/sync.ts +2 -1
- package/src/planhtml.ts +209 -0
- package/src/runtime/jira.ts +116 -34
- package/src/runtime/planpdf.ts +85 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,13 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.101.0] - 2026-12-04
|
|
8
|
+
|
|
9
|
+
**Jira issues get the plan as a PDF, mockups included, one per round of the plan discussion.**
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
- **Jira issues get the plan as a PDF, mockups included, one per round of the plan discussion.** dev-flow used to attach the raw `plan.md` only with the Approve? question, and Jira can't show the mockups it embeds. Other questions about the plan said "see plan.md" with nothing on the issue to see. Now, at the plan stage, each mirrored question carries the plan as it stands. A changed plan is printed to a new PDF with its mockups in it and attached as `<KEY>-plan-v1.pdf`, `-v2.pdf` and so on. An unchanged plan is named, not attached again, and a re-rendered mockup counts as a change. The issue's own seeded description gets no PDF. The approval comment attaches the approved round's PDF unless that round is already on the issue. The PDF is printed with the headless chromium the plan stage uses for mockups; `DEV_FLOW_CHROMIUM` can name the binary. With no chromium, `plan.md` and the mockups are attached as files, as before, and the note says why.
|
|
13
|
+
|
|
7
14
|
## [0.100.2] - 2026-12-04
|
|
8
15
|
|
|
9
16
|
**Jira sync has one path: the Atlassian MCP server with a scoped token.**
|
package/README.md
CHANGED
|
@@ -107,8 +107,8 @@ More detail, and what this deliberately is *not*, is in
|
|
|
107
107
|
- **`flow_stage` workers.** The agent can hand big chunks of work, or a second-opinion review, to a
|
|
108
108
|
fresh Pi session.
|
|
109
109
|
- **Jira sync (opt-in).** `flow jira init` links the project to a Jira project. A flow can then start
|
|
110
|
-
from an issue, each question goes to the issue as a comment (plan
|
|
111
|
-
can answer there by commenting or by moving the issue.
|
|
110
|
+
from an issue, each question goes to the issue as a comment (the plan attached as a PDF with its
|
|
111
|
+
mockups, one per round), and you can answer there by commenting or by moving the issue.
|
|
112
112
|
[More](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/jira.md)
|
|
113
113
|
- **A roadmap.** `.dev-flow/roadmap.md` is a backlog of future features. `flow start <slug>` can
|
|
114
114
|
pick one up.
|
package/docs/jira.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Jira sync
|
|
2
2
|
|
|
3
|
-
Optional. It is off until you run `flow jira init` in a project. Once on, a flow can start from a Jira issue. Every question dev-flow asks you is also posted on the issue, with the plan and screenshots
|
|
3
|
+
Optional. It is off until you run `flow jira init` in a project. Once on, a flow can start from a Jira issue. Every question dev-flow asks you is also posted on the issue, with the plan attached as a PDF, mockups included, and any screenshots it names. You can answer there, with a comment or by moving the issue, and the flow carries on.
|
|
4
4
|
|
|
5
5
|
It talks to Atlassian's official **Rovo MCP server** (`https://mcp.atlassian.com/v2/mcp`). That server is its only path to Jira: every read and write goes through its tools, and nothing goes to Jira's REST API. Jira Cloud only.
|
|
6
6
|
|
|
@@ -39,8 +39,9 @@ status.Story.done = Done
|
|
|
39
39
|
- **"Start a flow for DEV-12"** runs `flow start --jira=DEV-12`. The issue must be in the project and of a synced type. The flow's slug comes from the issue key and summary, and the description seeds `plan/plan.md`. dev-flow posts a "started" comment and moves the issue to its `plan` status. To link a flow that is already running, use `flow jira link DEV-12`.
|
|
40
40
|
- **No issue yet?** When you start a flow without naming an issue, the agent offers three choices: create a new issue in the synced project, link an existing one, or go without. The agent shows you the summary, type and description before anything is created (`flow jira create`), and links the new issue to the flow. Starting with `--no-jira` skips the offer.
|
|
41
41
|
- **Issues for roadmap items.** Ask the agent to create issues for roadmap items (`flow jira create --roadmap=2,5`). You see the list first. Each item's text becomes the summary and its brief the description, and the item is stamped with its key (`- [ ] Dark mode [DEV-14]`). When that item is picked and started, the flow links to its issue automatically.
|
|
42
|
-
- **Questions go to the issue.** When the agent stops to ask you something, its message is also posted as a comment.
|
|
43
|
-
- **The
|
|
42
|
+
- **Questions go to the issue.** When the agent stops to ask you something, its message is also posted as a comment. Any screenshot the message names by path is attached. The same message is never posted twice, and the same file never uploaded twice.
|
|
43
|
+
- **The plan goes as a PDF, one per round.** Jira can't show `plan.md` with its embedded mockups, so at the plan stage dev-flow prints the plan to a PDF with the mockups in it and attaches it to the comment, for example `DEV-12-plan-v1.pdf`. When the plan changes and you are asked again, the next comment gets `DEV-12-plan-v2.pdf`, so each round of the plan discussion has its own PDF on the issue. A re-rendered mockup counts as a change. If you are asked about an unchanged plan, the comment names the PDF already on the issue instead of attaching another. Until the plan is more than the issue's own description, no PDF is attached. The PDF is printed with the same headless chromium the plan stage renders mockups with: `chromium` or `google-chrome` on `PATH`, Playwright's browser cache, or the binary in `DEV_FLOW_CHROMIUM`. Without one, dev-flow attaches `plan.md` and the mockup images as files and says why.
|
|
44
|
+
- **The approved plan always reaches the issue.** When the plan is approved, dev-flow posts it to the issue, with its PDF attached unless that version is already there. This covers approvals that never passed through a mirrored question: you approved in chat, or the issue was created or linked at the moment you approved. If the identical plan was already posted with the Approve? question, the approval comment names that PDF. A flow linked to an issue after approval gets its plan posted at link time.
|
|
44
45
|
- **Answering in Jira:**
|
|
45
46
|
- **Comment**, for example "Approved", "Verified", or a change request. Only comments from your own account (the token's owner) count as your answer. Other people's comments are shown in the session as information and never approve anything.
|
|
46
47
|
- **Move the issue** to the status mapped to the next stage. A move to `implement` answers Approve?, `pre-release` answers Verified?, `release` answers Release?, and `done` answers Finish?. Any other move is shown as information.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.101.0",
|
|
4
4
|
"description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
package/src/core.ts
CHANGED
|
@@ -172,6 +172,10 @@ export interface JiraLink {
|
|
|
172
172
|
lastStatus?: string;
|
|
173
173
|
/** sha1 of files already attached, so a re-ask does not attach them again */
|
|
174
174
|
attached?: string[];
|
|
175
|
+
/** the plan PDFs attached, oldest first: one per plan iteration (plan.md and the images it embeds) */
|
|
176
|
+
plans?: { hash: string; name: string }[];
|
|
177
|
+
/** the plan iteration the link seeded from the issue (or the roadmap draft): not a plan worth a PDF yet */
|
|
178
|
+
seeded?: string;
|
|
175
179
|
/** sha1 of the last closing message mirrored — the same message is never posted twice */
|
|
176
180
|
mirrored?: string;
|
|
177
181
|
/** the open question a watch is waiting on: armed when it was posted, `checks` made since */
|
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}`);
|
package/src/planhtml.ts
ADDED
|
@@ -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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
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*(?:<)?([^\s)]+?)(?:>)?(?:\s+"([^)]*)")?\s*\)/g, (_m, alt: string, src: string, title?: string) => `<img src="${src}" alt="${alt}"${title ? ` title="${title}"` : ""}>`);
|
|
25
|
+
s = s.replace(/\[([^\]]+)\]\(\s*(?:<)?([^\s)]+?)(?:>)?(?:\s+"[^)]*")?\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
|
+
}
|
package/src/runtime/jira.ts
CHANGED
|
@@ -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 } = {};
|
|
@@ -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
|
|
273
|
-
* the plan itself unless an unchanged copy is already
|
|
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
|
|
285
|
-
const
|
|
286
|
-
const
|
|
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
|
-
/**
|
|
317
|
-
*
|
|
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
|
|
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
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** dev-flow runtime — plan.md printed to a PDF, mockups included, with the headless chromium the plan stage
|
|
2
|
+
* already renders mockups with. The PDF is what a linked Jira issue gets: an issue cannot show plan.md's
|
|
3
|
+
* embedded images, a PDF carries them. */
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { promisify } from "node:util";
|
|
10
|
+
import { planHtml } from "../planhtml.ts";
|
|
11
|
+
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
|
|
14
|
+
/** Test seams: the chromium binary (null: none found), the environment the search reads. */
|
|
15
|
+
export const pdfSeams: { chromium?: string | null; env?: NodeJS.ProcessEnv } = {};
|
|
16
|
+
|
|
17
|
+
const isExe = (f: string) => {
|
|
18
|
+
try {
|
|
19
|
+
return statSync(f).isFile();
|
|
20
|
+
} catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** The headless chromiums to print with, best first: `DEV_FLOW_CHROMIUM`, then chromium / chrome on PATH, the
|
|
26
|
+
* macOS app bundles, then playwright's browser cache (newest build first, its headless shell before its full
|
|
27
|
+
* chrome) — the same search the plan stage's mockup renders use. Empty when there is none. */
|
|
28
|
+
export function chromiumCandidates(): string[] {
|
|
29
|
+
if (pdfSeams.chromium !== undefined) return pdfSeams.chromium ? [pdfSeams.chromium] : [];
|
|
30
|
+
const env = pdfSeams.env ?? process.env;
|
|
31
|
+
const out: string[] = [];
|
|
32
|
+
const add = (f: string) => void (isExe(f) && !out.includes(f) && out.push(f));
|
|
33
|
+
if (env.DEV_FLOW_CHROMIUM) add(env.DEV_FLOW_CHROMIUM);
|
|
34
|
+
const dirs = (env.PATH ?? "").split(path.delimiter).filter(Boolean);
|
|
35
|
+
for (const name of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "chrome"]) for (const d of dirs) add(path.join(d, name));
|
|
36
|
+
add("/Applications/Chromium.app/Contents/MacOS/Chromium");
|
|
37
|
+
add("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
|
|
38
|
+
const cache = env.PLAYWRIGHT_BROWSERS_PATH || path.join(env.HOME ?? os.homedir(), ".cache", "ms-playwright");
|
|
39
|
+
if (existsSync(cache)) {
|
|
40
|
+
const rev = (d: string) => Number(d.match(/(\d+)$/)?.[1] ?? 0);
|
|
41
|
+
const builds = readdirSync(cache)
|
|
42
|
+
.filter((d) => /^chromium/.test(d))
|
|
43
|
+
.sort((a, b) => rev(b) - rev(a) || Number(b.includes("headless")) - Number(a.includes("headless")));
|
|
44
|
+
for (const b of builds)
|
|
45
|
+
for (const rel of ["chrome-headless-shell-linux64/chrome-headless-shell", "chrome-headless-shell-mac-arm64/chrome-headless-shell", "chrome-headless-shell-mac-x64/chrome-headless-shell", "chrome-linux64/chrome", "chrome-linux/chrome"]) add(path.join(cache, b, rel));
|
|
46
|
+
}
|
|
47
|
+
return out.slice(0, 4);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Print `planDir/plan.md` to `out` (a .pdf path). `meta` is the line printed above the plan. Tries each
|
|
51
|
+
* chromium found until one writes the PDF. */
|
|
52
|
+
export async function renderPlanPdf(planDir: string, out: string, o: { title: string; meta?: string }): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
53
|
+
const bins = chromiumCandidates();
|
|
54
|
+
if (!bins.length) return { ok: false, error: "no headless chromium found (chromium / google-chrome on PATH, playwright's cache, or DEV_FLOW_CHROMIUM)" };
|
|
55
|
+
const md = readFileSync(path.join(planDir, "plan.md"), "utf8");
|
|
56
|
+
const tmp = mkdtempSync(path.join(os.tmpdir(), "dev-flow-pdf-"));
|
|
57
|
+
const errors: string[] = [];
|
|
58
|
+
try {
|
|
59
|
+
const html = path.join(tmp, "plan.html");
|
|
60
|
+
writeFileSync(html, planHtml(md, { title: o.title, meta: o.meta, base: `${pathToFileURL(planDir).href}/` }));
|
|
61
|
+
for (const [n, bin] of bins.entries()) {
|
|
62
|
+
rmSync(out, { force: true });
|
|
63
|
+
const args = ["--headless", "--no-sandbox", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", `--user-data-dir=${path.join(tmp, `profile-${n}`)}`, "--allow-file-access-from-files", "--no-pdf-header-footer", "--virtual-time-budget=5000", `--print-to-pdf=${out}`, pathToFileURL(html).href];
|
|
64
|
+
try {
|
|
65
|
+
await execFileAsync(bin, args, { timeout: 45_000, maxBuffer: 4 * 1024 * 1024 });
|
|
66
|
+
} catch (e) {
|
|
67
|
+
// chromium can exit non-zero after writing the PDF (a crashpad or dbus complaint): judge by the file
|
|
68
|
+
if (!isPdf(out)) errors.push(`${path.basename(bin)}: ${String((e as { stderr?: string }).stderr || (e as Error).message).trim().split("\n").slice(-1)[0].slice(0, 200)}`);
|
|
69
|
+
}
|
|
70
|
+
if (isPdf(out)) return { ok: true };
|
|
71
|
+
if (errors.length <= n) errors.push(`${path.basename(bin)}: wrote no PDF`);
|
|
72
|
+
}
|
|
73
|
+
return { ok: false, error: `--print-to-pdf failed — ${errors.join("; ")}` };
|
|
74
|
+
} finally {
|
|
75
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isPdf(f: string): boolean {
|
|
80
|
+
try {
|
|
81
|
+
return readFileSync(f).subarray(0, 5).toString("latin1") === "%PDF-";
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|