pi-dev-flow 0.100.2 → 0.101.1

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 CHANGED
@@ -4,6 +4,23 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.101.1] - 2026-12-04
8
+
9
+ **A reply in Jira reaches the session within about a minute.**
10
+
11
+ ### Changed
12
+ - **A reply in Jira reaches the session within about a minute.** dev-flow used to check for your answer after 30 minutes, then 1, 2 and every 4 hours, so a quick answer could wait hours. Now, while a question is open, it probes the issue every minute with one small call that reads only when the issue last changed. When that moves, it reads the comments and status at once. Jira gives that time only to the minute, so a change is checked once more a minute later, and an answer in the same minute is not missed. The old schedule stays as the backstop. `probe = 2m` in the `flow-jira` block sets the interval (15 seconds at least); `probe = off` turns it off. A failing probe backs off to every 15 minutes.
13
+
14
+ ### Fixed
15
+ - **The doctor no longer misses an empty feature dir made the same millisecond it looks.** It compared the dir's age against zero, and a filesystem time a fraction of a millisecond past the clock made a brand-new dir look younger than that. With no minimum age asked for, the age is no longer checked. This also made a test fail now and then, which once stopped a release publish.
16
+
17
+ ## [0.101.0] - 2026-12-04
18
+
19
+ **Jira issues get the plan as a PDF, mockups included, one per round of the plan discussion.**
20
+
21
+ ### Changed
22
+ - **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.
23
+
7
24
  ## [0.100.2] - 2026-12-04
8
25
 
9
26
  **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 and screenshots attached), and you
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 attached. You can answer there, with a comment or by moving the issue, and the flow carries on.
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. At **Approve?** it attaches `plan.md` and the mockups. Any screenshot the message names by path is attached as well. The same message is never posted twice, and the same file never uploaded twice.
43
- - **The approved plan always reaches the issue.** When the plan is approved, dev-flow posts it to the issue with `plan.md` and the mockups attached. 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 just says so. A flow linked to an issue after approval gets its plan posted at link time.
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.
@@ -50,7 +51,11 @@ status.Story.done = Done
50
51
 
51
52
  ## Watching for your reply
52
53
 
53
- After a question is posted, dev-flow checks the issue on the `watch` schedule: after 30 minutes, then 1 hour later, 2 hours later, and every 4 hours after that, for up to 72 hours. Each check is two HTTP calls and costs no model tokens.
54
+ After a question is posted, dev-flow watches the issue for up to 72 hours (`watchCap`). It costs no model tokens.
55
+
56
+ - **Every minute it probes**: one small call that reads only the issue's last-changed time and status. A comment or a status move changes them, and the full check (comments and status, two calls) runs at once. So your answer reaches the session within about a minute. Jira reports that time only to the minute, so after a change dev-flow checks once more a minute later; an answer posted in the same minute is not missed. Set the interval with `probe = 2m` in the `flow-jira` block (15 seconds at least), or turn it off with `probe = off`. A failing probe slows down, up to every 15 minutes, until it succeeds again.
57
+ - **The `watch` schedule is the backstop**: full checks after 30 minutes, then 1 hour later, 2 hours later, and every 4 hours after that. They report errors the probe keeps quiet about. With `probe = off`, they are the only checks.
58
+ - An open question costs about 60 small calls an hour; nothing is polled while no question is open.
54
59
 
55
60
  - **In pi-web**, an idle session is normally shut down after 10 minutes. While a watch is waiting, dev-flow holds pi-web's session-liveness lease, so the session stays alive to receive your answer. The lease is released when you answer, when the cap passes, or when you reply in chat instead.
56
61
  - **If the session ends anyway** (pi-web restarted, or you closed it), the question stays recorded. When you open the session again, dev-flow checks Jira right away and resumes watching.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.100.2",
3
+ "version": "0.101.1",
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
@@ -153,6 +153,8 @@ export interface JiraConfig {
153
153
  watch: number[];
154
154
  /** seconds after the question when the watch gives up */
155
155
  watchCap: number;
156
+ /** seconds between cheap "did the issue change?" probes while a question waits; 0 = off; unset = 60 */
157
+ probe?: number;
156
158
  }
157
159
 
158
160
  /** A flow's link to its Jira issue, in state.json. */
@@ -172,8 +174,14 @@ export interface JiraLink {
172
174
  lastStatus?: string;
173
175
  /** sha1 of files already attached, so a re-ask does not attach them again */
174
176
  attached?: string[];
177
+ /** the plan PDFs attached, oldest first: one per plan iteration (plan.md and the images it embeds) */
178
+ plans?: { hash: string; name: string }[];
179
+ /** the plan iteration the link seeded from the issue (or the roadmap draft): not a plan worth a PDF yet */
180
+ seeded?: string;
175
181
  /** sha1 of the last closing message mirrored — the same message is never posted twice */
176
182
  mirrored?: string;
183
+ /** the issue's `updated` time as the probe last saw it, once a full check had read up to it */
184
+ updatedSeen?: string;
177
185
  /** the open question a watch is waiting on: armed when it was posted, `checks` made since */
178
186
  watch?: { ask: string; since: string; checks: number };
179
187
  }
@@ -311,6 +311,18 @@ export class JiraClient {
311
311
  };
312
312
  }
313
313
 
314
+ /** The issue's `updated` time and status — one small read, the watch's probe. A comment, an edit or a move
315
+ * all bump `updated`. An empty `updated` (the server left it out) means "unknown": treat it as changed. */
316
+ async stamp(key: string): Promise<JiraResult<{ updated: string; status: string }>> {
317
+ const t = await this.tool("issue").catch(() => undefined);
318
+ const asString = (t?.inputSchema?.properties as Record<string, { type?: string }> | undefined)?.fields?.type === "string";
319
+ const r = await this.call("issue", { issue: key, fields: asString ? "updated,status" : ["updated", "status"] });
320
+ if (!r.ok) return r;
321
+ const v = rec(r.value);
322
+ const f = rec(v.fields ?? v);
323
+ return { ok: true, value: { updated: str(f.updated), status: str(rec(f.status).name ?? f.status) } };
324
+ }
325
+
314
326
  /** The newest comments, newest first: pages of 20 (the server's cap) up to COMMENTS_MAX. */
315
327
  async comments(key: string): Promise<JiraResult<JiraComment[]>> {
316
328
  const toC = (c: Record<string, unknown>): JiraComment => {
@@ -13,6 +13,8 @@
13
13
  * mirror = asks asks (default) | all — which of the agent's closing messages become comments
14
14
  * watch = 30m, 1h, 2h, 4h reply-check intervals after a question; the last repeats
15
15
  * watchCap = 72h stop watching this long after the question
16
+ * probe = 1m while a question waits, look this often whether the issue changed (one
17
+ * small call); a change runs the full check. off = the schedule only
16
18
  *
17
19
  * A status value may name several statuses (`To Do, Backlog`): any of them means that stage; the first is
18
20
  * the one dev-flow moves the issue to. Pure module.
@@ -22,6 +24,12 @@ import type { JiraConfig, JiraStage } from "../core.ts";
22
24
  export const JIRA_STAGES: readonly JiraStage[] = ["plan", "implement", "pre-release", "release", "done"];
23
25
  export const DEFAULT_WATCH = [30 * 60, 60 * 60, 2 * 3600, 4 * 3600];
24
26
  export const DEFAULT_WATCH_CAP = 72 * 3600;
27
+ export const DEFAULT_PROBE = 60;
28
+ /** The shortest probe interval accepted: a faster one would only spend the token's rate limit. */
29
+ export const MIN_PROBE = 15;
30
+
31
+ /** Seconds between probes for `cfg` (0 = off). */
32
+ export const probeSecs = (cfg: Pick<JiraConfig, "probe">) => cfg.probe ?? DEFAULT_PROBE;
25
33
 
26
34
  /** `30m` / `1h` / `2d` / `90s` / `45` (seconds) → seconds; undefined for junk. */
27
35
  export function parseDuration(raw: string): number | undefined {
@@ -93,6 +101,16 @@ export function parseJiraBlock(entries: { line: string; where: string }[]): { cf
93
101
  else cfg.watchCap = s;
94
102
  break;
95
103
  }
104
+ case "probe": {
105
+ const v = value.trim().toLowerCase();
106
+ const s = /^(off|no|none|0)$/.test(v) ? 0 : parseDuration(v);
107
+ if (s === undefined) warn.push(`${where}: flow-jira probe = "${value}" — expected a duration like 1m, or off — keeping 1m`);
108
+ else if (s && s < MIN_PROBE) {
109
+ warn.push(`${where}: flow-jira probe = "${value}" is below ${MIN_PROBE}s — using ${MIN_PROBE}s`);
110
+ cfg.probe = MIN_PROBE;
111
+ } else cfg.probe = s;
112
+ break;
113
+ }
96
114
  default:
97
115
  warn.push(`${where}: unknown flow-jira key "${key}" — ignored`);
98
116
  }
@@ -115,6 +133,7 @@ export function renderJiraBlock(cfg: JiraConfig): string[] {
115
133
  if (cfg.mirror !== "asks") L.push(`mirror = ${cfg.mirror}`);
116
134
  if (cfg.watch.join() !== DEFAULT_WATCH.join()) L.push(`watch = ${cfg.watch.map(fmtDuration).join(", ")}`);
117
135
  if (cfg.watchCap !== DEFAULT_WATCH_CAP) L.push(`watchCap = ${fmtDuration(cfg.watchCap)}`);
136
+ if (cfg.probe !== undefined && cfg.probe !== DEFAULT_PROBE) L.push(`probe = ${cfg.probe ? fmtDuration(cfg.probe) : "off"}`);
118
137
  return L;
119
138
  }
120
139
 
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
+ }
package/src/projectmd.ts CHANGED
@@ -564,7 +564,8 @@ export function emptyFeatureDirs(root: string, minAgeMs = 0, nowMs = Date.now())
564
564
  const df = path.join(root, ".dev-flow");
565
565
  if (!existsSync(df)) return [];
566
566
  return readdirSync(df, { withFileTypes: true })
567
- .filter((d) => d.isDirectory() && holdsNoFile(path.join(df, d.name)) && nowMs - statSync(path.join(df, d.name)).mtimeMs >= minAgeMs)
567
+ // no minimum age: skip the clock — a dir made this very millisecond has an mtime a fraction past Date.now()
568
+ .filter((d) => d.isDirectory() && holdsNoFile(path.join(df, d.name)) && (minAgeMs <= 0 || nowMs - statSync(path.join(df, d.name)).mtimeMs >= minAgeMs))
568
569
  .map((d) => `.dev-flow/${d.name}`);
569
570
  }
570
571
 
@@ -1,15 +1,19 @@
1
1
  /** dev-flow runtime — the Jira reply watch: per session, one timer checking the linked issue on the playbook's
2
2
  * schedule (30m, 1h, 2h, 4h, … until watchCap after the question), with no model turn — each check is two
3
- * HTTP calls. An answer is delivered as the operator's message and ends the watch.
3
+ * HTTP calls. Between scheduled checks a probe looks every `probe` seconds (default 1m) whether the issue
4
+ * changed — one small call — and runs the full check as soon as it did, so an answer arrives within about a
5
+ * minute; the schedule stays as the backstop. An answer is delivered as the operator's message and ends the
6
+ * watch.
4
7
  *
5
8
  * While a watch is armed, pi-web's session-liveness registry keeps the session from being reaped as idle
6
9
  * (pi-web docs/integrations.md: Symbol.for("@agegr/pi-web/session-liveness/v1")); elsewhere the lease is a
7
10
  * no-op and the timer simply lives as long as the process. A session that ends keeps `jira.watch` in state,
8
11
  * and the next session_start catches up and re-arms it. */
9
12
  import { loadProject } from "../projectmd.ts";
13
+ import { probeSecs } from "../jira/config.ts";
10
14
  import { nextCheckDelay, type Relay } from "../jira/sync.ts";
11
15
  import { dfDir, readState } from "./base.ts";
12
- import { checkReplies, disarmWatch } from "./jira.ts";
16
+ import { checkReplies, disarmWatch, probeIssue, recordStamp } from "./jira.ts";
13
17
 
14
18
  export interface WatchDeps {
15
19
  /** deliver relays to the session `key` */
@@ -32,11 +36,23 @@ type LivenessRegistry = { version: number; register: (o: { name: string; session
32
36
 
33
37
  /** The longest a single timer waits; a long interval is reached by re-arming (Node timers cap near 24.8 days). */
34
38
  const MAX_TIMER_MS = 6 * 3600 * 1000;
39
+ const MINUTE_MS = 60_000;
40
+ /** A failing probe backs off, doubling, up to this; the scheduled checks still report the failure. */
41
+ const MAX_PROBE_BACKOFF_MS = 15 * 60_000;
42
+
43
+ /** What a timer does when it fires: the scheduled full check, a probe, or just re-arm (a long wait in parts). */
44
+ type Wake = "check" | "probe" | "partial";
35
45
 
36
46
  export class JiraWatch {
37
47
  private readonly armed = new Map<string, Armed>();
38
48
  private readonly leases = new Map<string, () => void>();
39
49
  private readonly busy = new Set<string>();
50
+ /** the probe interval of a session whose probe is failing (backed off); absent = the configured one */
51
+ private readonly backoff = new Map<string, number>();
52
+ /** a stamp the probe has seen but not yet settled: Jira's `updated` is minute-precision (17:03-0800), so a
53
+ * comment later in the same minute leaves it unchanged — the stamp counts as read only after a full check
54
+ * that ran a minute or more after it was first seen, i.e. after that minute ended */
55
+ private readonly unsettled = new Map<string, { stamp: string; firstSeen: number }>();
40
56
  private readonly deps: WatchDeps;
41
57
 
42
58
  constructor(deps: WatchDeps) {
@@ -67,8 +83,8 @@ export class JiraWatch {
67
83
  }
68
84
  }
69
85
 
70
- /** (Re)arm the watch of `slug` in session `key` from its state: the next check on the schedule, or nothing
71
- * when the flow has no open question; past the cap the watch is dropped with a note. */
86
+ /** (Re)arm the watch of `slug` in session `key` from its state: the next probe or scheduled check, whichever
87
+ * comes first, or nothing when the flow has no open question; past the cap the watch is dropped with a note. */
72
88
  arm(key: string, root: string, slug: string): void {
73
89
  this.cancel(key);
74
90
  const st = readState(root, slug);
@@ -78,31 +94,57 @@ export class JiraWatch {
78
94
  const delay = nextCheckDelay(cfg, Date.parse(w.since), w.checks, this.now());
79
95
  if (delay === null) {
80
96
  disarmWatch(root, slug);
97
+ this.backoff.delete(key);
81
98
  this.deps.note(key, `Jira ${st!.jira!.key}: no answer to ${w.ask} within the watch window — stopped watching. Answer here, or run flow jira check after answering in Jira.`);
82
99
  return;
83
100
  }
84
- const ms = Math.min(delay, MAX_TIMER_MS);
101
+ const probeMs = probeSecs(cfg) ? (this.backoff.get(key) ?? probeSecs(cfg) * 1000) : Infinity;
102
+ const [ms, wake]: [number, Wake] = probeMs < delay ? [Math.min(probeMs, MAX_TIMER_MS), "probe"] : delay > MAX_TIMER_MS ? [MAX_TIMER_MS, "partial"] : [delay, "check"];
85
103
  const set = this.deps.setTimer ?? ((fn: () => void, t: number) => setTimeout(fn, t).unref?.() ?? undefined);
86
- const timer = set(() => void this.tick(key, root, slug, ms < delay), ms);
104
+ const timer = set(() => void this.tick(key, root, slug, wake), ms);
87
105
  this.armed.set(key, { root, slug, timer, at: this.now() + ms });
88
106
  }
89
107
 
90
108
  /** Run one check now (catch-up), then re-arm. */
91
109
  async checkNow(key: string, root: string, slug: string): Promise<void> {
92
- await this.tick(key, root, slug, false);
110
+ await this.tick(key, root, slug, "check");
93
111
  }
94
112
 
95
- private async tick(key: string, root: string, slug: string, partial: boolean): Promise<void> {
113
+ private async tick(key: string, root: string, slug: string, wake: Wake): Promise<void> {
96
114
  this.armed.delete(key);
97
- if (partial) return this.arm(key, root, slug);
115
+ if (wake === "partial") return this.arm(key, root, slug);
98
116
  if (this.busy.has(key)) return;
99
117
  this.busy.add(key);
100
118
  try {
101
- const r = await checkReplies(root, loadProject(dfDir(root)).cfg, slug);
102
- if (r.error) this.deps.note(key, `Jira check failed (will retry on schedule): ${r.error}`);
103
- if (r.relays.length) this.deps.relay(key, r.relays);
119
+ const cfg = loadProject(dfDir(root)).cfg;
120
+ if (wake === "probe") {
121
+ const p = await probeIssue(root, cfg, slug);
122
+ if ("error" in p) {
123
+ const cur = this.backoff.get(key) ?? probeSecs(cfg.jira ?? {}) * 1000;
124
+ this.backoff.set(key, Math.min(cur * 2, MAX_PROBE_BACKOFF_MS));
125
+ } else {
126
+ this.backoff.delete(key);
127
+ if (p.changed) {
128
+ const at = this.now();
129
+ const r = await checkReplies(root, cfg, slug, { scheduled: false });
130
+ if (r.relays.length) this.deps.relay(key, r.relays);
131
+ if (!r.error && p.stamp) {
132
+ const u = this.unsettled.get(key);
133
+ if (u?.stamp !== p.stamp) this.unsettled.set(key, { stamp: p.stamp, firstSeen: at });
134
+ else if (at - u.firstSeen >= MINUTE_MS) {
135
+ recordStamp(root, slug, p.stamp);
136
+ this.unsettled.delete(key);
137
+ }
138
+ }
139
+ }
140
+ }
141
+ } else {
142
+ const r = await checkReplies(root, cfg, slug);
143
+ if (r.error) this.deps.note(key, `Jira check failed (will retry on schedule): ${r.error}`);
144
+ if (r.relays.length) this.deps.relay(key, r.relays);
145
+ }
104
146
  } catch (e) {
105
- this.deps.note(key, `Jira check failed (will retry on schedule): ${(e as Error).message}`);
147
+ if (wake === "check") this.deps.note(key, `Jira check failed (will retry on schedule): ${(e as Error).message}`);
106
148
  } finally {
107
149
  this.busy.delete(key);
108
150
  }
@@ -120,6 +162,8 @@ export class JiraWatch {
120
162
  /** The session ended: stop the timer and give the lease back. */
121
163
  release(key: string): void {
122
164
  this.cancel(key);
165
+ this.backoff.delete(key);
166
+ this.unsettled.delete(key);
123
167
  this.leases.get(key)?.();
124
168
  this.leases.delete(key);
125
169
  }
@@ -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 } = {};
@@ -117,6 +119,7 @@ export async function gateJiraInit(root: string, cfg: Config, rest: string[], fl
117
119
  mirror: (mirrorArg as "asks" | "all" | null) ?? cfg.jira?.mirror ?? "asks",
118
120
  watch: cfg.jira?.watch ?? [...DEFAULT_WATCH],
119
121
  watchCap: cfg.jira?.watchCap ?? DEFAULT_WATCH_CAP,
122
+ ...(cfg.jira?.probe !== undefined ? { probe: cfg.jira.probe } : {}),
120
123
  };
121
124
  const block = ["```flow-jira", ...renderJiraBlock(next), "```"].join("\n");
122
125
  const table = canon.map((t) => ` ${t}: ${JIRA_STAGES.map((g) => `${g} ← ${status[t][g]?.join(" | ") || "—"}`).join("; ")}`).join("\n");
@@ -180,11 +183,13 @@ export async function linkFlow(root: string, cfg: Config, slug: string, key: str
180
183
  const { client, issue } = r;
181
184
  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
185
  const lines = [`linked to Jira ${issue.key} — ${issue.summary} (${issue.type}, ${issue.status}) ${issue.url}`];
186
+ let seeded = false;
183
187
  if (opts.seedPlan && state.stage === "plan") {
184
188
  const planMd = path.join(featDir(root, slug), "plan", "plan.md");
185
189
  const brief = issueBrief(issue);
186
190
  if (!existsSync(planMd)) {
187
191
  writeFileSync(planMd, brief);
192
+ seeded = true;
188
193
  lines.push("the issue's summary and description seeded plan/plan.md — a draft: plan it out and approve as usual");
189
194
  } else if (!readFileSync(planMd, "utf8").includes(issue.url)) {
190
195
  writeFileSync(planMd, `${readFileSync(planMd, "utf8").trimEnd()}\n\n${brief.replace(/^# .*\n/, "## Jira issue\n")}`);
@@ -202,6 +207,7 @@ export async function linkFlow(root: string, cfg: Config, slug: string, key: str
202
207
  const ids = existing.value.map((c) => c.id).filter((id) => /^\d+$/.test(id));
203
208
  if (ids.length) link.seenCommentId = ids.reduce((a, b) => (Number(b) > Number(a) ? b : a));
204
209
  }
210
+ if (seeded) link.seeded = planDigest(path.join(featDir(root, slug), "plan")) ?? undefined;
205
211
  writeState(root, { ...state, jira: link });
206
212
  const moved = await moveToStage(root, cfg, slug, state.stage);
207
213
  if (moved) lines.push(moved);
@@ -267,10 +273,83 @@ export async function syncStageMoves(root: string, cfg: Config, before: Map<stri
267
273
  return out;
268
274
  }
269
275
 
276
+ /** The images plan.md embeds that live under the plan folder — the mockups its PDF prints. */
277
+ function embeddedImages(planDir: string, md: string): string[] {
278
+ const out = new Set<string>();
279
+ for (const m of md.matchAll(/!\[[^\]]*\]\(\s*<?([^\s)>]+)>?/g)) {
280
+ if (/^[a-z][\w+.-]*:/i.test(m[1])) continue; // a URL, not a file
281
+ let ref = m[1];
282
+ try {
283
+ ref = decodeURI(ref);
284
+ } catch {
285
+ /* a stray % — take it literally */
286
+ }
287
+ const f = path.resolve(planDir, ref);
288
+ if (f.startsWith(planDir + path.sep) && existsSync(f) && statSync(f).isFile()) out.add(f);
289
+ }
290
+ return [...out].sort();
291
+ }
292
+
293
+ /** A plan iteration's identity: plan.md and every image it embeds — a re-rendered mockup is a new iteration. */
294
+ function planDigest(planDir: string): string | null {
295
+ const planMd = path.join(planDir, "plan.md");
296
+ if (!existsSync(planMd)) return null;
297
+ const md = readFileSync(planMd, "utf8");
298
+ const h = createHash("sha1").update(md);
299
+ for (const f of embeddedImages(planDir, md)) h.update(`\0${path.relative(planDir, f)}\0`).update(readFileSync(f));
300
+ return h.digest("hex");
301
+ }
302
+
303
+ /** The plan as it stands, for a comment: a PDF of plan.md with its mockups printed in, one per iteration and
304
+ * named for it (`DEV-7-plan-v2.pdf`), so every round of the plan discussion on the issue has its own. An
305
+ * unchanged plan is not attached again: `unchanged` names the PDF that carries it. No chromium (or a failed
306
+ * print): plan.md and its mockups are attached as files instead, and `pdfError` says why. */
307
+ 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> {
308
+ const planDir = path.join(featDir(root, st.slug), "plan");
309
+ const digest = planDigest(planDir);
310
+ if (!digest) return null;
311
+ const plans = [...(link.plans ?? [])];
312
+ const prior = plans.find((p) => p.hash === digest);
313
+ if (prior) return { attached: [], failed: [], plans, name: prior.name, unchanged: true };
314
+ const n = plans.length + 1;
315
+ const name = `${link.key}-plan-v${n}.pdf`;
316
+ const title = readFileSync(path.join(planDir, "plan.md"), "utf8").match(/^# (.+)$/m)?.[1]?.trim() ?? st.slug;
317
+ const tmp = mkdtempSync(path.join(os.tmpdir(), "dev-flow-plan-"));
318
+ try {
319
+ const out = path.join(tmp, name);
320
+ 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` });
321
+ if (pdf.ok) {
322
+ const r = await client.upload(link.key, out);
323
+ if (!r.ok) return { attached: [], failed: [`${name} (${r.error})`], plans };
324
+ plans.push({ hash: digest, name });
325
+ return { attached: [name], failed: [], plans, name };
326
+ }
327
+ // no PDF: the files themselves, each once
328
+ const attached: string[] = [];
329
+ const failed: string[] = [];
330
+ const mock = path.join(planDir, "mockups");
331
+ 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)) : [])];
332
+ for (const f of files) {
333
+ const h = sha1(readFileSync(f));
334
+ if (hashes.has(h)) continue;
335
+ const r = await client.upload(link.key, f);
336
+ if (r.ok) {
337
+ attached.push(path.basename(f));
338
+ hashes.add(h);
339
+ } else failed.push(`${path.basename(f)} (${r.error})`);
340
+ }
341
+ return { attached, failed, plans, pdfError: pdf.error };
342
+ } finally {
343
+ rmSync(tmp, { recursive: true, force: true });
344
+ }
345
+ }
346
+
347
+ const planNote = (pa: { pdfError?: string } | null) => (pa?.pdfError ? `; no plan PDF — ${pa.pdfError}, so plan.md was attached as is` : "");
348
+
270
349
  /** The approved plan on the issue, however the approval came: the Approve? question is mirrored only when the
271
350
  * 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. */
351
+ * time — never reaches that point. Attaches the plan PDF unless this iteration's is already on the issue; the
352
+ * comment carries the plan itself unless an unchanged copy is already there. Returns a gate-output line. */
274
353
  export async function postApprovedPlan(root: string, cfg: Config, slug: string): Promise<string | null> {
275
354
  const st = readState(root, slug);
276
355
  if (!cfg.jira || !st?.jira) return null;
@@ -281,49 +360,34 @@ export async function postApprovedPlan(root: string, cfg: Config, slug: string):
281
360
  const link = st.jira;
282
361
  const plan = readFileSync(planMd, "utf8");
283
362
  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
- }
363
+ const legacy = hashes.has(sha1(plan)); // plan.md itself went up with the question (no chromium then)
364
+ const pa = await attachPlan(c.client, root, st, link, hashes);
365
+ const already = !!pa?.unchanged || legacy;
298
366
  const call = st.versionChoice ? ` Release call: ${st.versionChoice}.` : "";
299
367
  const mode = st.patch ? " (patch)" : st.docs ? " (docs)" : "";
300
368
  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()}`;
369
+ ? `Plan approved${mode} — the copy posted with the question${pa?.unchanged ? ` (${pa.name})` : ""} is the one approved.${call}`
370
+ : `**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()}`;
371
+ const attached = pa?.attached ?? [];
372
+ const failed = pa?.failed ?? [];
303
373
  const r = await c.client.comment(link.key, formatComment({ slug, text: body, attachments: attached }));
304
374
  const fresh = readState(root, slug) ?? st;
305
- const next: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes] };
375
+ const next: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], ...(pa ? { plans: pa.plans } : {}) };
306
376
  if (r.ok && r.value) next.posted = [...next.posted, r.value];
307
377
  writeState(root, { ...fresh, jira: next });
308
378
  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("; ")})` : ""}`;
379
+ return `Jira ${link.key}: approved plan posted${attached.length ? ` with ${attached.join(", ")}` : ""}${failed.length ? ` (not attached: ${failed.join("; ")})` : ""}${planNote(pa)}`;
310
380
  }
311
381
 
312
382
  // ---------------------------------------------------------------- outbound: the closing-message mirror
313
383
 
314
384
  const IMG = /(?:^|[\s(`'"[])((?:\.{0,2}\/|\/)?[\w@.\-/]+\.(?:png|jpe?g|gif|webp))(?=$|[\s)`'",\]:;])/gi;
315
385
 
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. */
386
+ /** Images a mirrored message attaches: every image the message names that exists under the feature folder, its
387
+ * worktree or the repo — never anything outside the repo. (The plan goes as a PDF: attachPlan.) */
318
388
  export function attachmentsFor(root: string, state: FlowState, text: string): string[] {
319
389
  const fd = featDir(root, state.slug);
320
390
  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
391
  const bases = [fd, state.worktree ? worktreeAbs(root, state) : null, root].filter((b): b is string => !!b && existsSync(b));
328
392
  let realRoot = root;
329
393
  try {
@@ -349,6 +413,13 @@ export function attachmentsFor(root: string, state: FlowState, text: string): st
349
413
  return [...out].slice(0, 10);
350
414
  }
351
415
 
416
+ /** plan.md is still exactly the issue's own brief the link seeded — any edit, a first draft included, gets a PDF. */
417
+ function isSeed(root: string, st: FlowState, link: JiraLink): boolean {
418
+ const planDir = path.join(featDir(root, st.slug), "plan");
419
+ if (!existsSync(path.join(planDir, "plan.md"))) return true;
420
+ return !!link.seeded && planDigest(planDir) === link.seeded;
421
+ }
422
+
352
423
  /** Mirror the agent's closing message to the linked issue when the playbook's `mirror` says so. Arms the watch
353
424
  * when it asks something. Returns what happened (for a display note), or null when nothing was posted. */
354
425
  export async function mirrorClosingMessage(root: string, cfg: Config, slug: string, text: string): Promise<{ posted: boolean; watch: boolean; note: string } | null> {
@@ -361,11 +432,23 @@ export async function mirrorClosingMessage(root: string, cfg: Config, slug: stri
361
432
  if (link.mirrored === digest) return null;
362
433
  const c = jiraClient(cfg.jira);
363
434
  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
435
  const attached: string[] = [];
366
436
  const failed: string[] = [];
367
437
  const hashes = new Set(link.attached ?? []);
368
- for (const f of files) {
438
+ // at plan, a message carries the plan as it stands: a new PDF for each new iteration, else a pointer to the
439
+ // one already on the issue when the message is about the plan — never the seed the issue itself gave
440
+ let planLine = "";
441
+ let pa: Awaited<ReturnType<typeof attachPlan>> = null;
442
+ if (st.stage === "plan" && !isSeed(root, st, link)) {
443
+ pa = await attachPlan(c.client, root, st, link, hashes);
444
+ if (pa) {
445
+ attached.push(...pa.attached);
446
+ failed.push(...pa.failed);
447
+ if (pa.name && !pa.unchanged) planLine = `Plan: ${pa.name} (attached; plan.md with its mockups)`;
448
+ else if (pa.name && (st.pendingAsk === "Approve?" || /\bplan\b/i.test(text))) planLine = `Plan: ${pa.name} (unchanged, attached earlier)`;
449
+ }
450
+ }
451
+ for (const f of attachmentsFor(root, st, text)) {
369
452
  const h = sha1(readFileSync(f));
370
453
  if (hashes.has(h)) continue;
371
454
  const r = await c.client.upload(link.key, f);
@@ -375,21 +458,43 @@ export async function mirrorClosingMessage(root: string, cfg: Config, slug: stri
375
458
  } else failed.push(`${path.basename(f)} (${r.error})`);
376
459
  }
377
460
  const ask = asks ? (st.pendingAsk ?? "your answer") : undefined;
378
- const body = formatComment({ slug, ask, text, attachments: attached, answerStatus: answeringStatus(cfg.jira, link, st.pendingAsk) });
461
+ const body = formatComment({ slug, ask, text, plan: planLine, attachments: attached.filter((a) => a !== pa?.name), answerStatus: answeringStatus(cfg.jira, link, st.pendingAsk) });
379
462
  const r = await c.client.comment(link.key, body);
380
463
  const fresh = readState(root, slug) ?? st;
381
- const nextLink: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], mirrored: digest };
464
+ const nextLink: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], mirrored: digest, ...(pa ? { plans: pa.plans } : {}) };
382
465
  if (r.ok && r.value) nextLink.posted = [...nextLink.posted, r.value];
383
466
  if (r.ok && ask) nextLink.watch = { ask, since: now(), checks: 0 };
384
467
  writeState(root, { ...fresh, jira: nextLink });
385
468
  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" : ""}` };
469
+ 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
470
  }
388
471
 
389
472
  // ---------------------------------------------------------------- inbound: one reply check
390
473
 
391
- /** Read the linked issue's new comments and its status; advance the link; return what to relay. */
392
- export async function checkReplies(root: string, cfg: Config, slug: string): Promise<{ relays: Relay[]; error?: string }> {
474
+ /** The watch's probe: one small read of the issue. `changed` when its `updated` time (or status) moved since the
475
+ * last full check the probe triggered, or when either is unknown; `stamp` is what to record once the full
476
+ * check has read past it (recordStamp). */
477
+ export async function probeIssue(root: string, cfg: Config, slug: string): Promise<{ changed: boolean; stamp: string } | { error: string }> {
478
+ const st = readState(root, slug);
479
+ if (!cfg.jira || !st?.jira) return { changed: false, stamp: "" };
480
+ const c = jiraClient(cfg.jira);
481
+ if ("error" in c) return { error: c.error };
482
+ const r = await c.client.stamp(st.jira.key);
483
+ if (!r.ok) return { error: r.error };
484
+ const { updated, status } = r.value;
485
+ const moved = !!status && !!st.jira.lastStatus && status.toLowerCase() !== st.jira.lastStatus.toLowerCase();
486
+ return { changed: !updated || !st.jira.updatedSeen || updated !== st.jira.updatedSeen || moved, stamp: updated };
487
+ }
488
+
489
+ /** The full check the probe ran has read everything up to `stamp`. */
490
+ export function recordStamp(root: string, slug: string, stamp: string): void {
491
+ const st = readState(root, slug);
492
+ if (st?.jira && stamp) writeState(root, { ...st, jira: { ...st.jira, updatedSeen: stamp } });
493
+ }
494
+
495
+ /** Read the linked issue's new comments and its status; advance the link; return what to relay. A check the
496
+ * probe triggered (`scheduled: false`) does not advance the watch schedule. */
497
+ export async function checkReplies(root: string, cfg: Config, slug: string, opts: { scheduled?: boolean } = {}): Promise<{ relays: Relay[]; error?: string }> {
393
498
  const st = readState(root, slug);
394
499
  if (!cfg.jira || !st?.jira) return { relays: [] };
395
500
  const c = jiraClient(cfg.jira);
@@ -406,7 +511,7 @@ export async function checkReplies(root: string, cfg: Config, slug: string): Pro
406
511
  const fresh = readState(root, slug) ?? st;
407
512
  const next: JiraLink = { ...(fresh.jira ?? link), accountId: link.accountId, seenUntil: r.seenUntil ?? link.seenUntil, seenCommentId: r.seenCommentId ?? link.seenCommentId, lastStatus: r.lastStatus };
408
513
  if (r.relays.some((x) => x.kind === "answer")) delete next.watch;
409
- else if (next.watch) next.watch = { ...next.watch, checks: next.watch.checks + 1 };
514
+ else if (next.watch && opts.scheduled !== false) next.watch = { ...next.watch, checks: next.watch.checks + 1 };
410
515
  writeState(root, { ...fresh, jira: next });
411
516
  return { relays: r.relays };
412
517
  }
@@ -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
+ }