pi-dev-flow 0.97.0 → 0.99.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,533 @@
1
+ /** dev-flow runtime — the opt-in Jira sync (project.md ` ```flow-jira `): `flow jira …` gates, `flow start --jira=KEY`,
2
+ * status moves on stage changes, the closing-message mirror and the reply check the watch runs.
3
+ *
4
+ * Nothing here runs for a project without a flow-jira block, and nothing here fails a gate: a Jira error is a
5
+ * note in the gate's output. The watch timers and the pi-web liveness lease live in extensions/dev-flow.ts. */
6
+ import { createHash } from "node:crypto";
7
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync, copyFileSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { type Config, type FlowState, type JiraConfig, type JiraLink, type JiraStage, needsOperator, sq, parseRowIds, roadmapBriefFor, roadmapItemAt, roadmapItemTitle, roadmapJiraKey, roadmapStampJira } from "../core.ts";
10
+ import { parseProjectMd } from "../projectmd.ts";
11
+ import { JIRA_STAGES, setJiraBlock, statusForStage, suggestMapping, renderJiraBlock, DEFAULT_WATCH, DEFAULT_WATCH_CAP } from "../jira/config.ts";
12
+ import { type JiraCreds, credsPath, loadCreds, normSite } from "../jira/creds.ts";
13
+ import { JiraClient } from "../jira/client.ts";
14
+ import type { FetchLike } from "../jira/mcp.ts";
15
+ import { type Relay, answeringStatus, classifyActivity, formatComment, issueBrief, shouldMirror, slugFromIssue } from "../jira/sync.ts";
16
+ import { AGENT_MARK } from "../present.ts";
17
+ import { dfDir, featDir, flagValue, now, readRoadmap, readState, roadmapFile, sh, tail, unfinishedStates, worktreeAbs, writeState } from "./base.ts";
18
+ import type { RunResult } from "./checks.ts";
19
+
20
+ /** Test seams: a fake Atlassian server (fetch), the credentials file, the clock. */
21
+ export const jiraSeams: { fetch?: FetchLike; credsFile?: string; env?: NodeJS.ProcessEnv } = {};
22
+
23
+ const clients = new Map<string, JiraClient>();
24
+
25
+ /** A client for the configured site, or why there is none. One per site and token, so the MCP session is reused. */
26
+ export function jiraClient(cfg: Pick<JiraConfig, "site" | "cloudId">): { client: JiraClient } | { error: string } {
27
+ const creds = loadCreds(cfg.site, jiraSeams.env ?? process.env, jiraSeams.credsFile ?? credsPath());
28
+ if (!creds) return { error: noCreds(cfg.site) };
29
+ return { client: clientFor(creds, cfg.cloudId) };
30
+ }
31
+
32
+ function clientFor(creds: JiraCreds, cloudId?: string): JiraClient {
33
+ const id = `${creds.site}\0${creds.email}\0${createHash("sha1").update(creds.token).digest("hex")}\0${cloudId ?? ""}\0${jiraSeams.fetch ? "seam" : ""}`;
34
+ let c = clients.get(id);
35
+ if (!c) {
36
+ c = new JiraClient(creds, { cloudId, fetch: jiraSeams.fetch });
37
+ clients.set(id, c);
38
+ }
39
+ return c;
40
+ }
41
+
42
+ /** Forget cached clients (tests; a new login). */
43
+ export const resetJiraClients = () => clients.clear();
44
+
45
+ const noCreds = (site?: string) =>
46
+ `no Jira credentials${site ? ` for ${site}` : ""} — the operator runs /flow jira login${site ? ` ${site}` : ""} (an Atlassian Cloud API token; stored in ~/.pi/agent/dev-flow/jira.json, mode 0600), or sets JIRA_SITE, JIRA_EMAIL and JIRA_API_TOKEN. The token never goes through the chat.`;
47
+
48
+ const sha1 = (b: string | Buffer) => createHash("sha1").update(b).digest("hex");
49
+
50
+ // ---------------------------------------------------------------- flow jira init
51
+
52
+ const DEFAULT_SKIP_TYPES = /^(sub-?task|epic)$/i;
53
+
54
+ /** `flow jira init [--site=] [--project=KEY] [--types=A,B] [--map=Type.stage=Status[|Status]]… [--mirror=asks|all] [--confirmed]`
55
+ * — one question at a time: login, project, issue types, then the status mapping preview; --confirmed writes it. */
56
+ export async function gateJiraInit(root: string, cfg: Config, rest: string[], flag: (n: string) => boolean): Promise<RunResult> {
57
+ const siteArg = flagValue(rest, "site");
58
+ const creds = loadCreds(siteArg ?? cfg.jira?.site, jiraSeams.env ?? process.env, jiraSeams.credsFile ?? credsPath());
59
+ if (!creds) return { text: needsOperator(noCreds(siteArg ?? cfg.jira?.site), "Jira login?", "ask the operator to run /flow jira login (never ask them to paste the token into the chat); once they say it is done, re-run flow jira init"), isError: true };
60
+ const client = clientFor(creds, cfg.jira?.site === creds.site ? cfg.jira.cloudId : undefined);
61
+ const me = await client.me();
62
+ if (!me.ok) return { text: `Jira authentication failed on ${creds.site} (${creds.source === "env" ? "JIRA_EMAIL/JIRA_API_TOKEN" : "stored login"}): ${me.error}\nThe Atlassian MCP server takes a Cloud API token as Basic email:token only when an org admin enabled API-token authentication for it (Atlassian Administration → Rovo MCP server). Check the email and token (/flow jira login re-enters them).`, isError: true };
63
+ const head = `Jira: authenticated as ${me.value.displayName} on ${creds.site} (Atlassian MCP server)`;
64
+
65
+ const project = flagValue(rest, "project") ?? cfg.jira?.project;
66
+ if (!project) {
67
+ const ps = await client.projects();
68
+ if (!ps.ok) return { text: `${head}\ncould not list projects: ${ps.error}`, isError: true };
69
+ return { text: needsOperator(`${head}\nWhich Jira project does this repo sync with?\n${ps.value.map((p) => ` ${p.key} — ${p.name}`).join("\n") || " (no projects visible to this account)"}`, "Jira project?", "ask the operator which project, then re-run flow jira init --project=<KEY>"), isError: true };
70
+ }
71
+ const types = await client.issueTypes(project);
72
+ if (!types.ok) return { text: `${head}\ncould not read the issue types of ${project}: ${types.error}`, isError: true };
73
+ const typeArg = flagValue(rest, "types");
74
+ const chosen = typeArg !== null ? typeArg.split(",").map((t) => t.trim()).filter(Boolean) : (cfg.jira?.project === project ? cfg.jira.issueTypes : []);
75
+ const offered = types.value.filter((t) => !t.subtask);
76
+ if (!chosen.length)
77
+ return {
78
+ text: needsOperator(`${head}, project ${project}\nWhich issue types may a flow start from?\n${offered.map((t) => ` ${t.name}${DEFAULT_SKIP_TYPES.test(t.name) ? "" : " (suggested)"}`).join("\n")}`, "Issue types?", `ask the operator, then re-run flow jira init --project=${project} --types=<Type,Type>`),
79
+ isError: true,
80
+ };
81
+ const unknown = chosen.filter((t) => !types.value.some((x) => x.name.toLowerCase() === t.toLowerCase()));
82
+ if (unknown.length) return { text: `${project} has no issue type ${unknown.join(", ")} — it has ${offered.map((t) => t.name).join(", ")}`, isError: true };
83
+ const canon = chosen.map((t) => types.value.find((x) => x.name.toLowerCase() === t.toLowerCase())!.name);
84
+
85
+ const st = await client.statuses(project);
86
+ if (!st.ok) return { text: `${head}\ncould not read the workflow statuses of ${project}: ${st.error}`, isError: true };
87
+ // mapping: what is configured for this project, else the suggestion; --map overrides one stage of one type
88
+ const status: JiraConfig["status"] = {};
89
+ const notes: string[] = [];
90
+ for (const t of canon) {
91
+ const wf = st.value[t] ?? [];
92
+ const prev = cfg.jira?.project === project ? cfg.jira.status[t] : undefined;
93
+ status[t] = prev ? structuredClone(prev) : suggestMapping(wf);
94
+ const unmapped = wf.filter((s) => !JIRA_STAGES.some((g) => status[t][g]?.includes(s.name))).map((s) => s.name);
95
+ notes.push(`${t} workflow: ${wf.map((s) => s.name).join(" · ") || "(no statuses read)"}${unmapped.length ? `\n not mapped (moves into them are shown, never read as answers): ${unmapped.join(", ")}` : ""}`);
96
+ }
97
+ for (const a of rest.filter((x) => x.startsWith("--map="))) {
98
+ const m = a.slice(6).match(/^(.+)\.([a-z-]+)=(.*)$/);
99
+ if (!m || !JIRA_STAGES.includes(m[2] as JiraStage)) return { text: `--map=${a.slice(6)}: expected --map=<Type>.<stage>=<Status>[|<Status>] with stage one of ${JIRA_STAGES.join(", ")}`, isError: true };
100
+ const type = canon.find((t) => t.toLowerCase() === m[1].toLowerCase());
101
+ if (!type) return { text: `--map names issue type "${m[1]}", not one of ${canon.join(", ")}`, isError: true };
102
+ const names = m[3].split("|").map((x) => x.trim()).filter(Boolean);
103
+ const known = st.value[type]?.map((s) => s.name) ?? [];
104
+ const bad = names.filter((n) => known.length && !known.some((k) => k.toLowerCase() === n.toLowerCase()));
105
+ if (bad.length) return { text: `--map: ${type}'s workflow has no status ${bad.join(", ")} — it has ${known.join(", ")}`, isError: true };
106
+ if (names.length) status[type][m[2] as JiraStage] = names.map((n) => known.find((k) => k.toLowerCase() === n.toLowerCase()) ?? n);
107
+ else delete status[type][m[2] as JiraStage];
108
+ }
109
+ const mirrorArg = flagValue(rest, "mirror");
110
+ if (mirrorArg !== null && !/^(asks|all)$/.test(mirrorArg)) return { text: "--mirror is asks or all", isError: true };
111
+ const next: JiraConfig = {
112
+ site: creds.site,
113
+ cloudId: await client.cloudId().then((id) => (id && id !== creds.site ? id : undefined)),
114
+ project,
115
+ issueTypes: canon,
116
+ status,
117
+ mirror: (mirrorArg as "asks" | "all" | null) ?? cfg.jira?.mirror ?? "asks",
118
+ watch: cfg.jira?.watch ?? [...DEFAULT_WATCH],
119
+ watchCap: cfg.jira?.watchCap ?? DEFAULT_WATCH_CAP,
120
+ };
121
+ const block = ["```flow-jira", ...renderJiraBlock(next), "```"].join("\n");
122
+ const table = canon.map((t) => ` ${t}: ${JIRA_STAGES.map((g) => `${g} ← ${status[t][g]?.join(" | ") || "—"}`).join("; ")}`).join("\n");
123
+ if (!flag("confirmed"))
124
+ return {
125
+ text: needsOperator(
126
+ `${head}, project ${project}\n${notes.join("\n")}\nProposed mapping (a move into a stage's status answers that stage's question: implement answers Approve?, pre-release Verified?, release Release?, done Finish?; dev-flow moves the issue to the first status listed):\n${table}\n\nproject.md ## global gets:\n${block}`,
127
+ "Mapping OK?",
128
+ `show the operator the mapping; on their word re-run flow jira init --project=${project} --types=${canon.join(",")} [--map=<Type>.<stage>=<Status>…] --confirmed`,
129
+ ),
130
+ isError: true,
131
+ };
132
+ const mdFile = path.join(dfDir(root), "project.md");
133
+ const text = setJiraBlock(readFileSync(mdFile, "utf8"), next);
134
+ const parsed = parseProjectMd(text);
135
+ if (parsed.hard.length) return { text: `refusing to write project.md — the result would not parse:\n- ${parsed.hard.join("\n- ")}`, isError: true };
136
+ copyFileSync(mdFile, `${mdFile}.bak`);
137
+ writeFileSync(mdFile, text);
138
+ const dirty = await sh("git status --porcelain", root);
139
+ const onlyPlaybook = dirty.ok && dirty.out.trim().split("\n").every((l) => l.trim().endsWith(" .dev-flow/project.md"));
140
+ const tracked = (await sh("git ls-files --error-unmatch .dev-flow/project.md", root)).ok;
141
+ let note = "flow-jira block written to .dev-flow/project.md ## global (previous copy kept as project.md.bak)";
142
+ if (tracked && onlyPlaybook) {
143
+ const commit = await sh(`git add .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(`playbook: jira sync with ${project}`)}`, root);
144
+ note += commit.ok ? " — committed as a playbook chore" : ` — commit failed (${tail(commit.out)}); commit it yourself`;
145
+ }
146
+ return { text: `${head}, project ${project}\n${table}\n${note}\nJira sync is on: flow start --jira=<KEY> starts a flow from an issue; flow jira link <KEY> links the bound flow.` };
147
+ }
148
+
149
+ // ---------------------------------------------------------------- linking a flow to an issue
150
+
151
+ /** Validate and fetch an issue for a link. */
152
+ async function fetchForLink(cfg: JiraConfig, key: string) {
153
+ const c = jiraClient(cfg);
154
+ if ("error" in c) return { error: c.error };
155
+ const issue = await c.client.issue(key);
156
+ if (!issue.ok) return { error: `could not read ${key}: ${issue.error}` };
157
+ if (!issue.value.key.toUpperCase().startsWith(`${cfg.project.toUpperCase()}-`)) return { error: `${issue.value.key} is not in the configured project ${cfg.project}` };
158
+ if (!cfg.issueTypes.some((t) => t.toLowerCase() === issue.value.type.toLowerCase()))
159
+ return { error: `${issue.value.key} is a ${issue.value.type} — the playbook syncs ${cfg.issueTypes.join(", ")} (flow jira init --types=… adds a type)` };
160
+ const me = await c.client.me();
161
+ return { client: c.client, issue: issue.value, accountId: me.ok ? me.value.accountId : undefined };
162
+ }
163
+
164
+ /** `flow start --jira=KEY` without a slug: the slug the issue gives, or the error. */
165
+ export async function slugForIssue(cfg: Config, key: string): Promise<{ slug: string } | { error: string }> {
166
+ if (!cfg.jira) return { error: "--jira needs Jira sync configured — run flow jira init first" };
167
+ const r = await fetchForLink(cfg.jira, key);
168
+ if ("error" in r) return { error: r.error! };
169
+ return { slug: slugFromIssue(r.issue.key, r.issue.summary) };
170
+ }
171
+
172
+ /** Link `slug`'s flow to an issue (start --jira, flow jira link): store the link, seed the plan brief at plan,
173
+ * post the start comment, move the issue to the stage's status. Returns the lines for the gate output. */
174
+ export async function linkFlow(root: string, cfg: Config, slug: string, key: string, opts: { seedPlan: boolean }): Promise<{ lines: string[] } | { error: string }> {
175
+ if (!cfg.jira) return { error: "Jira sync is not configured — run flow jira init first" };
176
+ const r = await fetchForLink(cfg.jira, key);
177
+ if ("error" in r) return { error: r.error! };
178
+ const state = readState(root, slug);
179
+ if (!state) return { error: `no flow ${slug}` };
180
+ const { client, issue } = r;
181
+ 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
+ const lines = [`linked to Jira ${issue.key} — ${issue.summary} (${issue.type}, ${issue.status}) ${issue.url}`];
183
+ if (opts.seedPlan && state.stage === "plan") {
184
+ const planMd = path.join(featDir(root, slug), "plan", "plan.md");
185
+ const brief = issueBrief(issue);
186
+ if (!existsSync(planMd)) {
187
+ writeFileSync(planMd, brief);
188
+ lines.push("the issue's summary and description seeded plan/plan.md — a draft: plan it out and approve as usual");
189
+ } else if (!readFileSync(planMd, "utf8").includes(issue.url)) {
190
+ writeFileSync(planMd, `${readFileSync(planMd, "utf8").trimEnd()}\n\n${brief.replace(/^# .*\n/, "## Jira issue\n")}`);
191
+ lines.push("the issue's description was appended to plan/plan.md");
192
+ }
193
+ }
194
+ const posted = await client.comment(issue.key, formatComment({ slug, text: `Started dev-flow feature \`${slug}\` for this issue (stage ${state.stage}). Questions for you will be posted here; answer with a comment, or move the issue to the status the question names.` }));
195
+ if (posted.ok && posted.value) link.posted.push(posted.value);
196
+ else if (!posted.ok) lines.push(`${AGENT_MARK}jira: could not post the start comment: ${posted.error}`);
197
+ // read from here on, by Jira's clock: the newest comment's time (ours included), so neither the comments
198
+ // before the link nor a skew between this machine and Jira's servers can mislead the watch
199
+ const existing = await client.comments(issue.key);
200
+ if (existing.ok && existing.value.length) {
201
+ link.seenUntil = existing.value.map((c) => c.created).sort((a, b) => Date.parse(a) - Date.parse(b)).at(-1);
202
+ const ids = existing.value.map((c) => c.id).filter((id) => /^\d+$/.test(id));
203
+ if (ids.length) link.seenCommentId = ids.reduce((a, b) => (Number(b) > Number(a) ? b : a));
204
+ }
205
+ writeState(root, { ...state, jira: link });
206
+ const moved = await moveToStage(root, cfg, slug, state.stage);
207
+ if (moved) lines.push(moved);
208
+ return { lines };
209
+ }
210
+
211
+ // ---------------------------------------------------------------- outbound: status moves on stage changes
212
+
213
+ /** Move a linked flow's issue to the status mapped to `stage`; the line for the gate output, or null when there
214
+ * is nothing to do. Records the new status so the watch does not read dev-flow's own move as the operator's. */
215
+ export async function moveToStage(root: string, cfg: Config, slug: string, stage: JiraStage, link?: JiraLink): Promise<string | null> {
216
+ const st = readState(root, slug);
217
+ const l = link ?? st?.jira;
218
+ if (!cfg.jira || !l) return null;
219
+ const target = statusForStage(cfg.jira, l.type, stage);
220
+ if (!target) return null;
221
+ if (l.lastStatus && l.lastStatus.toLowerCase() === target.toLowerCase()) return null;
222
+ const c = jiraClient(cfg.jira);
223
+ if ("error" in c) return `${AGENT_MARK}jira: ${l.key} not moved to "${target}" — ${c.error}`;
224
+ const cur = await c.client.issue(l.key);
225
+ if (cur.ok && cur.value.status.toLowerCase() === target.toLowerCase()) {
226
+ if (st?.jira) writeState(root, { ...st, jira: { ...st.jira, lastStatus: cur.value.status } });
227
+ return null;
228
+ }
229
+ const r = await c.client.moveTo(l.key, target);
230
+ if (!r.ok) return `${AGENT_MARK}jira: ${l.key} not moved to "${target}" (stage ${stage}): ${r.error} — move it by hand if it matters; the flow is unaffected`;
231
+ const fresh = readState(root, slug);
232
+ if (fresh?.jira) writeState(root, { ...fresh, jira: { ...fresh.jira, lastStatus: r.value } });
233
+ return `Jira ${l.key} → ${r.value}`;
234
+ }
235
+
236
+ /** Stage of each linked flow, before a gate runs. */
237
+ export function linkedStages(root: string): Map<string, { stage: string; link: JiraLink }> {
238
+ const m = new Map<string, { stage: string; link: JiraLink }>();
239
+ for (const s of unfinishedStates(root)) if (s.jira) m.set(s.slug, { stage: s.stage, link: s.jira });
240
+ return m;
241
+ }
242
+
243
+ /** After a gate: move the issue of every linked flow whose stage changed (finish removes the state: done). */
244
+ export async function syncStageMoves(root: string, cfg: Config, before: Map<string, { stage: string; link: JiraLink }>): Promise<string[]> {
245
+ if (!cfg.jira || !before.size) return [];
246
+ const out: string[] = [];
247
+ for (const [slug, b] of before) {
248
+ const st = readState(root, slug);
249
+ const stage: JiraStage | null = !st ? "done" : st.stage !== b.stage ? st.stage : null;
250
+ if (!stage) continue;
251
+ const line = await moveToStage(root, cfg, slug, stage, st?.jira ?? b.link);
252
+ if (line) out.push(line);
253
+ if (!st) {
254
+ const c = jiraClient(cfg.jira);
255
+ if (!("error" in c)) await c.client.comment(b.link.key, formatComment({ slug, text: `dev-flow feature \`${slug}\` finished.` }));
256
+ }
257
+ }
258
+ return out;
259
+ }
260
+
261
+ // ---------------------------------------------------------------- outbound: the closing-message mirror
262
+
263
+ const IMG = /(?:^|[\s(`'"[])((?:\.{0,2}\/|\/)?[\w@.\-/]+\.(?:png|jpe?g|gif|webp))(?=$|[\s)`'",\]:;])/gi;
264
+
265
+ /** Files a mirrored message attaches: the plan and its mockups at Approve?, plus every image the message names
266
+ * that exists under the feature folder, its worktree or the repo — never anything outside the repo. */
267
+ export function attachmentsFor(root: string, state: FlowState, text: string): string[] {
268
+ const fd = featDir(root, state.slug);
269
+ const out = new Set<string>();
270
+ if (state.pendingAsk === "Approve?") {
271
+ const plan = path.join(fd, "plan", "plan.md");
272
+ if (existsSync(plan)) out.add(plan);
273
+ const mock = path.join(fd, "plan", "mockups");
274
+ if (existsSync(mock)) for (const f of readdirSync(mock)) if (/\.(png|jpe?g|gif|webp)$/i.test(f)) out.add(path.join(mock, f));
275
+ }
276
+ const bases = [fd, state.worktree ? worktreeAbs(root, state) : null, root].filter((b): b is string => !!b && existsSync(b));
277
+ let realRoot = root;
278
+ try {
279
+ realRoot = realpathSync(root);
280
+ } catch {
281
+ /* keep as is */
282
+ }
283
+ for (const m of text.matchAll(IMG)) {
284
+ const ref = m[1];
285
+ for (const b of path.isAbsolute(ref) ? [""] : bases) {
286
+ const abs = path.resolve(b, ref);
287
+ try {
288
+ if (!statSync(abs).isFile()) continue;
289
+ const real = realpathSync(abs);
290
+ if (!real.startsWith(realRoot + path.sep)) continue;
291
+ out.add(abs);
292
+ break;
293
+ } catch {
294
+ /* not here */
295
+ }
296
+ }
297
+ }
298
+ return [...out].slice(0, 10);
299
+ }
300
+
301
+ /** Mirror the agent's closing message to the linked issue when the playbook's `mirror` says so. Arms the watch
302
+ * when it asks something. Returns what happened (for a display note), or null when nothing was posted. */
303
+ export async function mirrorClosingMessage(root: string, cfg: Config, slug: string, text: string): Promise<{ posted: boolean; watch: boolean; note: string } | null> {
304
+ const st = readState(root, slug);
305
+ if (!cfg.jira || !st?.jira) return null;
306
+ const link = st.jira;
307
+ const asks = shouldMirror("asks", st.pendingAsk, text);
308
+ if (!shouldMirror(cfg.jira.mirror, st.pendingAsk, text)) return null;
309
+ const digest = sha1(`${st.pendingAsk ?? ""}\0${text}`);
310
+ if (link.mirrored === digest) return null;
311
+ const c = jiraClient(cfg.jira);
312
+ if ("error" in c) return { posted: false, watch: false, note: `Jira ${link.key}: not mirrored — ${c.error}` };
313
+ const files = attachmentsFor(root, st, text);
314
+ const attached: string[] = [];
315
+ const failed: string[] = [];
316
+ const hashes = new Set(link.attached ?? []);
317
+ for (const f of files) {
318
+ const h = sha1(readFileSync(f));
319
+ if (hashes.has(h)) continue;
320
+ const r = await c.client.upload(link.key, f);
321
+ if (r.ok) {
322
+ attached.push(path.basename(f));
323
+ hashes.add(h);
324
+ } else failed.push(`${path.basename(f)} (${r.error})`);
325
+ }
326
+ const ask = asks ? (st.pendingAsk ?? "your answer") : undefined;
327
+ const body = formatComment({ slug, ask, text, attachments: attached, answerStatus: answeringStatus(cfg.jira, link, st.pendingAsk) });
328
+ const r = await c.client.comment(link.key, body);
329
+ const fresh = readState(root, slug) ?? st;
330
+ const nextLink: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes], mirrored: digest };
331
+ if (r.ok && r.value) nextLink.posted = [...nextLink.posted, r.value];
332
+ if (r.ok && ask) nextLink.watch = { ask, since: now(), checks: 0 };
333
+ writeState(root, { ...fresh, jira: nextLink });
334
+ if (!r.ok) return { posted: false, watch: false, note: `Jira ${link.key}: could not post the comment — ${r.error}` };
335
+ 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" : ""}` };
336
+ }
337
+
338
+ // ---------------------------------------------------------------- inbound: one reply check
339
+
340
+ /** Read the linked issue's new comments and its status; advance the link; return what to relay. */
341
+ export async function checkReplies(root: string, cfg: Config, slug: string): Promise<{ relays: Relay[]; error?: string }> {
342
+ const st = readState(root, slug);
343
+ if (!cfg.jira || !st?.jira) return { relays: [] };
344
+ const c = jiraClient(cfg.jira);
345
+ if ("error" in c) return { relays: [], error: c.error };
346
+ const link = st.jira;
347
+ const [comments, issue] = await Promise.all([c.client.comments(link.key), c.client.issue(link.key)]);
348
+ if (!comments.ok) return { relays: [], error: `comments of ${link.key}: ${comments.error}` };
349
+ if (!issue.ok) return { relays: [], error: `${link.key}: ${issue.error}` };
350
+ if (!link.accountId) {
351
+ const me = await c.client.me();
352
+ if (me.ok) link.accountId = me.value.accountId;
353
+ }
354
+ const r = classifyActivity({ link, cfg: cfg.jira, state: st, comments: comments.value, status: issue.value.status });
355
+ const fresh = readState(root, slug) ?? st;
356
+ const next: JiraLink = { ...(fresh.jira ?? link), accountId: link.accountId, seenUntil: r.seenUntil ?? link.seenUntil, seenCommentId: r.seenCommentId ?? link.seenCommentId, lastStatus: r.lastStatus };
357
+ if (r.relays.some((x) => x.kind === "answer")) delete next.watch;
358
+ else if (next.watch) next.watch = { ...next.watch, checks: next.watch.checks + 1 };
359
+ writeState(root, { ...fresh, jira: next });
360
+ return { relays: r.relays };
361
+ }
362
+
363
+ /** Stop watching a flow's issue (the operator answered in chat, or the cap passed). */
364
+ export function disarmWatch(root: string, slug: string): void {
365
+ const st = readState(root, slug);
366
+ if (st?.jira?.watch) {
367
+ const { watch: _w, ...rest } = st.jira;
368
+ writeState(root, { ...st, jira: rest });
369
+ }
370
+ }
371
+
372
+ // ---------------------------------------------------------------- creating issues
373
+
374
+ /** The issue type a new issue gets: `--type=`, else the first synced type. */
375
+ function typeFor(cfg: JiraConfig, arg: string | null): { type: string } | { error: string } {
376
+ if (!arg) return { type: cfg.issueTypes[0] };
377
+ const t = cfg.issueTypes.find((x) => x.toLowerCase() === arg.toLowerCase());
378
+ return t ? { type: t } : { error: `--type=${arg} is not a synced issue type (${cfg.issueTypes.join(", ")})` };
379
+ }
380
+
381
+ /** The plan's title (its first `# ` heading), unless it is still the start draft's placeholder. */
382
+ function planTitle(root: string, slug: string): string | null {
383
+ const f = path.join(featDir(root, slug), "plan", "plan.md");
384
+ if (!existsSync(f)) return null;
385
+ const h = readFileSync(f, "utf8").match(/^# (.+)$/m)?.[1]?.trim();
386
+ return h && !/— plan \(draft\)$/.test(h) ? h : null;
387
+ }
388
+
389
+ const excerpt = (t: string, n = 600) => (t.length > n ? `${t.slice(0, n)}…` : t);
390
+
391
+ /** `flow jira create` — a new issue for the bound flow (linked at once), or `--roadmap=<n>[,<n>…]` one per
392
+ * roadmap item (stamped `[KEY]` on the item; flow start of a picked item links it). Creating issues is the
393
+ * operator's call: without --confirmed it previews and asks `Create Jira issue?`. */
394
+ export async function gateJiraCreate(root: string, cfg: Config, rest: string[], flag: (n: string) => boolean, bound: string | null): Promise<RunResult> {
395
+ if (!cfg.jira) return { text: "Jira sync is not configured — run flow jira init first", isError: true };
396
+ const jc = cfg.jira;
397
+ const ty = typeFor(jc, flagValue(rest, "type"));
398
+ if ("error" in ty) return { text: ty.error, isError: true };
399
+ const descFile = flagValue(rest, "description-file");
400
+ let description = flagValue(rest, "description") ?? "";
401
+ if (descFile) {
402
+ try {
403
+ description = readFileSync(path.resolve(root, descFile), "utf8");
404
+ } catch (e) {
405
+ return { text: `--description-file: ${(e as Error).message}`, isError: true };
406
+ }
407
+ }
408
+ const rows = flagValue(rest, "roadmap");
409
+
410
+ if (rows !== null) {
411
+ const ids = parseRowIds(rows);
412
+ const text = readRoadmap(root);
413
+ const items = ids.map((n) => ({ n, it: Number.isNaN(n) ? null : roadmapItemAt(text, n) }));
414
+ const bad = items.filter((x) => !x.it).map((x) => (Number.isNaN(x.n) ? "?" : String(x.n)));
415
+ if (!ids.length || bad.length) return { text: `--roadmap names ${bad.length ? `no open item ${bad.join(", ")}` : "nothing"} — flow roadmap lists them`, isError: true };
416
+ const todo = items.filter((x) => !roadmapJiraKey(x.it!.item));
417
+ const already = items.filter((x) => roadmapJiraKey(x.it!.item)).map((x) => ` ${x.n}. already ${roadmapJiraKey(x.it!.item)}`);
418
+ if (!todo.length) return { text: `nothing to create — every item named has an issue:\n${already.join("\n")}` };
419
+ const preview = todo.map((x) => ` ${x.n}. ${ty.type}: ${roadmapItemTitle(x.it!.item)}${x.it!.brief ? `\n ${excerpt(x.it!.brief, 200).replace(/\n/g, "\n ")}` : ""}`).join("\n");
420
+ if (!flag("confirmed"))
421
+ return {
422
+ text: needsOperator(`create ${todo.length} ${jc.project} issue(s) from the roadmap (summary = the item, description = its brief):\n${preview}${already.length ? `\n${already.join("\n")}` : ""}`, "Create Jira issue?", `ask the operator; on their yes re-run flow jira create --roadmap=${rows}${flagValue(rest, "type") ? ` --type=${ty.type}` : ""} --confirmed`),
423
+ isError: true,
424
+ };
425
+ const c = jiraClient(jc);
426
+ if ("error" in c) return { text: c.error, isError: true };
427
+ const out: string[] = [];
428
+ let next = text;
429
+ for (const x of todo) {
430
+ const r = await c.client.createIssue(jc.project, ty.type, roadmapItemTitle(x.it!.item), x.it!.brief);
431
+ if (!r.ok) {
432
+ out.push(` ${x.n}. not created: ${r.error}`);
433
+ continue;
434
+ }
435
+ next = roadmapStampJira(next, x.n, r.value) ?? next;
436
+ out.push(` ${x.n}. ${r.value} ${c.client.issueUrl(r.value)}`);
437
+ }
438
+ if (next !== text) writeFileSync(roadmapFile(root), next);
439
+ return { text: `Jira issues from the roadmap:\n${out.join("\n")}${already.length ? `\n${already.join("\n")}` : ""}\nflow roadmap pick <n> <slug> then flow start <slug> links the item's issue to its flow` };
440
+ }
441
+
442
+ if (!bound) return { text: "flow jira create needs a bound flow (or --roadmap=<n>) — flow use <slug> first", isError: true };
443
+ const st = readState(root, bound);
444
+ if (!st) return { text: `no flow ${bound}`, isError: true };
445
+ if (st.jira) return { text: `${bound} is already linked to ${st.jira.key}`, isError: true };
446
+ const summary = flagValue(rest, "summary") ?? planTitle(root, bound);
447
+ if (!summary) return { text: `flow jira create needs --summary="<one line>" (the plan has no title yet) [--description="…"|--description-file=<path>] [--type=${jc.issueTypes.join("|")}]`, isError: true };
448
+ if (!flag("confirmed"))
449
+ return {
450
+ text: needsOperator(`create a ${jc.project} ${ty.type} for ${bound} and link it:\n summary: ${summary}\n description: ${description ? excerpt(description).replace(/\n/g, "\n ") : "(none)"}`, "Create Jira issue?", "ask the operator (they may change the summary or type); on their yes re-run the same call with --confirmed"),
451
+ isError: true,
452
+ };
453
+ const c = jiraClient(jc);
454
+ if ("error" in c) return { text: c.error, isError: true };
455
+ const r = await c.client.createIssue(jc.project, ty.type, summary, description);
456
+ if (!r.ok) return { text: `could not create the issue: ${r.error}`, isError: true };
457
+ const l = await linkFlow(root, cfg, bound, r.value, { seedPlan: false });
458
+ return { text: `created ${r.value} ${c.client.issueUrl(r.value)}\n${"error" in l ? `${AGENT_MARK}jira: created but not linked: ${l.error} — flow jira link ${r.value} retries` : l.lines.join("\n")}` };
459
+ }
460
+
461
+ /** After a plain `flow start` in a Jira-synced project: link the picked roadmap item's issue, or suggest one. */
462
+ export async function startWithoutKey(root: string, cfg: Config, slug: string): Promise<string[]> {
463
+ if (!cfg.jira || readState(root, slug)?.jira) return [];
464
+ const picked = roadmapBriefFor(readRoadmap(root), slug);
465
+ const key = picked ? roadmapJiraKey(picked.item) : null;
466
+ if (key) {
467
+ // start already carried the item's brief into the plan — the issue holds the same text
468
+ const r = await linkFlow(root, cfg, slug, key, { seedPlan: false });
469
+ return "error" in r ? [`${AGENT_MARK}jira: the roadmap item's issue ${key} was not linked: ${r.error}`] : r.lines;
470
+ }
471
+ return [
472
+ `Jira sync is on, and this flow has no ${cfg.jira.project} issue.`,
473
+ `${AGENT_MARK}jira: offer the operator, in your next message: create a new ${cfg.jira.project} issue for it (run flow jira create --summary="<one line>" [--description="…"] [--type=${cfg.jira.issueTypes.join("|")}] — it previews and asks Create Jira issue?), link an existing one (flow jira link <KEY>), or go without. Do not create one unasked.`,
474
+ ];
475
+ }
476
+
477
+ // ---------------------------------------------------------------- flow jira <sub>
478
+
479
+ export interface JiraGateHooks {
480
+ /** deliver relays from a check (answers as operator messages, the rest as display-only notes) */
481
+ relay?: (relays: Relay[]) => void;
482
+ /** the watch for this session changed (armed or disarmed) */
483
+ rearm?: () => void;
484
+ }
485
+
486
+ export async function gateJira(root: string, cfg: Config, rest: string[], flag: (n: string) => boolean, bound: string | null, hooks: JiraGateHooks = {}): Promise<RunResult> {
487
+ const [verb = "status", ...more] = rest;
488
+ switch (verb) {
489
+ case "init":
490
+ return gateJiraInit(root, cfg, more, flag);
491
+ case "login":
492
+ return { text: "flow jira login is the operator's: they type /flow jira login [site] — it asks for the email and API token in a dialog, so the token never passes through the chat", isError: true };
493
+ case "status": {
494
+ if (!cfg.jira) return { text: "Jira sync is off for this project (no flow-jira block in .dev-flow/project.md) — flow jira init turns it on" };
495
+ const c = jiraClient(cfg.jira);
496
+ const me = "error" in c ? null : await c.client.me();
497
+ const lines = [`Jira sync: ${cfg.jira.site}, project ${cfg.jira.project}, types ${cfg.jira.issueTypes.join(", ")}, mirror ${cfg.jira.mirror}`, "error" in c ? c.error : me?.ok ? `authenticated as ${me.value.displayName}` : `authentication failed: ${me && !me.ok ? me.error : "?"}`];
498
+ for (const s of unfinishedStates(root).filter((x) => x.jira))
499
+ lines.push(` ${s.slug} ↔ ${s.jira!.key} (${s.jira!.lastStatus ?? "?"})${s.jira!.watch ? ` — watching for an answer to ${s.jira!.watch.ask} since ${s.jira!.watch.since}` : ""}`);
500
+ return { text: lines.join("\n") };
501
+ }
502
+ case "create":
503
+ return gateJiraCreate(root, cfg, more, flag, bound);
504
+ case "link": {
505
+ const key = more.find((a) => !a.startsWith("--"));
506
+ if (!bound) return { text: "flow jira link needs a bound flow — flow use <slug> first", isError: true };
507
+ if (!key) return { text: "usage: flow jira link <ISSUE-KEY>", isError: true };
508
+ const r = await linkFlow(root, cfg, bound, key.toUpperCase(), { seedPlan: true });
509
+ if ("error" in r) return { text: r.error, isError: true };
510
+ return { text: r.lines.join("\n") };
511
+ }
512
+ case "unlink": {
513
+ const st = bound ? readState(root, bound) : null;
514
+ if (!st?.jira) return { text: "the bound flow has no Jira link", isError: true };
515
+ const { jira, ...restState } = st;
516
+ writeState(root, restState as FlowState);
517
+ hooks.rearm?.();
518
+ return { text: `${st.slug} unlinked from ${jira.key} — nothing more is posted or watched` };
519
+ }
520
+ case "check": {
521
+ const st = bound ? readState(root, bound) : null;
522
+ if (!st?.jira) return { text: "the bound flow has no Jira link", isError: true };
523
+ const r = await checkReplies(root, cfg, st.slug);
524
+ if (r.error) return { text: `Jira check failed: ${r.error}`, isError: true };
525
+ hooks.relay?.(r.relays);
526
+ hooks.rearm?.();
527
+ const answers = r.relays.filter((x) => x.kind === "answer").length;
528
+ return { text: r.relays.length ? `Jira ${st.jira.key}: ${r.relays.length} new item(s)${answers ? ` — ${answers} answer(s) relayed as the operator's message; they arrive after this turn` : ""}` : `Jira ${st.jira.key}: nothing new` };
529
+ }
530
+ default:
531
+ return { text: `unknown flow jira verb "${verb}" — init | status | create | link <KEY> | unlink | check (the operator's /flow jira login stores the token)`, isError: true };
532
+ }
533
+ }
@@ -13,6 +13,9 @@ import { gatePublishes, prBodyOwed, publishRelease } from "./publish.ts";
13
13
  /** The release call, asked with Verified? only for a flow approved before Approve? carried it — null when the
14
14
  * playbook decides, the flow has no manifest to version, or the call is on record (the usual case). */
15
15
  function versionQuestion(root: string, state: FlowState, cfg: Config): { ask: string; flags: string } | null {
16
+ // gh#299: a call the agent proposed at Approve? is shown here, where the operator answers anyway
17
+ if (state.versionChoice && state.versionProposed)
18
+ return { ask: `the release call is ${describeVersionChoice(state.versionChoice, state.versionFrom)} — the agent's proposal at Approve?, not your word: keep it, or say patch, minor or major (or merge unreleased)`, flags: "--version=patch|minor|major or --no-version to change it" };
16
19
  if (!cfg.versioning.file || playbookVersionChoice(cfg) || state.versionChoice) return null;
17
20
  return releaseCallQuestion(manifestAt(gateCwd(root, state), cfg.versioning.file), cfg.versioning.file, state.docs);
18
21
  }
@@ -194,6 +197,8 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
194
197
  const was = state!.versionChoice;
195
198
  const choice = verArg.choice ?? state!.versionChoice ?? playbookVersionChoice(cfg);
196
199
  if (choice) recordReleaseCall(root, state!, cfg, choice);
200
+ // the operator answered a Verified? that showed the proposed call (or changed it): it is their word now (gh#299)
201
+ if (askPending || flag("confirmed")) delete state!.versionProposed;
197
202
  const choiceNote = choice ? `\nrelease call: ${describeVersionChoice(choice, state!.versionFrom)}${was && was !== choice ? ` (changed from ${describeVersionChoice(was)})` : ""}` : "";
198
203
  const before = state!.stage;
199
204
  state!.stage = "pre-release";
@@ -393,22 +398,38 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
393
398
  const upstream = (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, wtCwd)).ok ? `origin/${d}` : (await sh(`git rev-parse --verify -q ${sq(`refs/heads/${d}`)}`, wtCwd)).ok ? d : "";
394
399
  const range = `${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`;
395
400
  // one record per commit: "<sha> <subject>" then the files it touched (\x1e starts a record)
396
- const since = await sh(`git log --no-decorate --name-only --format=%x1e%h%x20%s ${upstream ? "--no-merges " : ""}${range}`, wtCwd);
397
- const commits = since.ok
398
- ? since.out.split("\x1e").map((rec) => rec.split("\n").map((l) => l.trim()).filter(Boolean)).filter((r) => r.length).map(([line, ...files]) => ({ line, files }))
401
+ const since = await sh(`git log --no-decorate --name-only --format=%x1e%H%x20%h%x20%s ${upstream ? "--no-merges " : ""}${range}`, wtCwd);
402
+ const listed = since.ok
403
+ ? since.out.split("\x1e").map((rec) => rec.split("\n").map((l) => l.trim()).filter(Boolean)).filter((r) => r.length).map(([head, ...files]) => ({ full: head.split(" ")[0], line: head.split(" ").slice(1).join(" "), files }))
399
404
  : [];
400
405
  const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
401
- const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
406
+ const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - listed.length) : 0;
402
407
  // gh#187: the release-prep commit (the bump, the changelog entry, whatever else the bump rewrites — an
403
408
  // image tag in a compose file) lands after Verified? by design and no container verdict could cover
404
409
  // it. It is the commit that touches the version file, or one that touches nothing but prep files.
405
410
  const prepSet = prepFiles(cfg);
411
+ // gh#298: a rebase replays the verified commits under new ids — same content, so not news. When the verified
412
+ // head is no longer an ancestor, a commit whose patch (prep files left out, where a rebase conflict usually
413
+ // lands) matches one the operator verified rides under the word; changed content still asks.
414
+ const rewritten = upstream && !(await sh(`git merge-base --is-ancestor ${sq(state!.verifiedHead)} HEAD`, wtCwd)).ok;
415
+ const replayed = new Set<string>();
416
+ if (rewritten) {
417
+ const notPrep = [...prepSet].map((f) => sq(`:(exclude)${f}`)).join(" ");
418
+ const pids = async (r: string) => {
419
+ const out = await sh(`git log -p --no-merges --format='commit %H' ${r} -- . ${notPrep} | git patch-id --stable`, wtCwd);
420
+ return out.ok ? out.out.split("\n").map((l) => l.trim().split(/\s+/)).filter((x) => x.length === 2) : [];
421
+ };
422
+ const seen = new Set((await pids(`${sq(state!.verifiedHead)} --not ${sq(upstream)}`)).map(([pid]) => pid));
423
+ for (const [pid, sha] of await pids(range)) if (seen.has(pid)) replayed.add(sha);
424
+ }
425
+ const commits = listed.filter((c) => !replayed.has(c.full));
426
+ const replayNote = replayed.size ? `${replayed.size} commit(s) a rebase replayed with the patch the operator verified ride under it` : "";
406
427
  const isPrep = (c: { files: string[] }) => (!!cfg.versioning.file && c.files.includes(cfg.versioning.file)) || (c.files.length > 0 && c.files.every((f) => prepSet.has(f)));
407
428
  const prep = commits.filter(isPrep);
408
429
  // docs and tests ship no behaviour the operator's look could have caught: they ride under the verdict, named
409
430
  const quiet = commits.filter((c) => !isPrep(c) && c.files.length > 0 && c.files.every(nonBehaviourPath));
410
431
  const changed = commits.filter((c) => !isPrep(c) && !quiet.includes(c));
411
- if (quiet.length) quietAfterVerify = `${quiet.length} docs/test-only commit(s) after Verified? (${quiet.map((c) => c.line.split(" ")[0]).join(", ")}) ride under it`;
432
+ quietAfterVerify = [quiet.length ? `${quiet.length} docs/test-only commit(s) after Verified? (${quiet.map((c) => c.line.split(" ")[0]).join(", ")}) ride under it` : "", replayNote].filter(Boolean).join("; ");
412
433
  // changed code shipping under an earlier word is friction the closing reflection should look at
413
434
  unverifiedChange = changed.length > 0;
414
435
  if (changed.length)
@@ -467,7 +488,11 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
467
488
  markPendingAsk(root, state!, "Release?");
468
489
  if (!ui.hasUI) {
469
490
  const callAsk = cfg.versioning.file && !choice ? " — also ask the release call: a patch, minor or major release, or merge unreleased (no bump, no tag)?" : "";
470
- return { text: needsOperator(`ready to publish${yoloHeld ? ` (${yoloHeld})` : ""}${askWhy ? ` (asked: ${askWhy})` : ""}${postVerify ? ` — ${postVerify}` : ""}${callAsk}`, "Release?", `re-run with --confirmed once the operator answered 'Release?' in chat${callAsk ? " (add --version=patch|minor|major or --no-version for their release call)" : ""}`), isError: true };
491
+ // gh#288: changed code after Verified? is one question, not two — a re-verify after a Release? answer spent it
492
+ const oneQuestion = unverifiedChange && cfg.release.ask !== "always" && !callAsk
493
+ ? "ask ONE question, not both: if these commits change behaviour, run flow verify now and ask Verified? over the new deploy — Release? then answers itself (release.ask = on-change); only if they do not, ask 'Release?' with them named and "
494
+ : "";
495
+ return { text: needsOperator(`ready to publish${yoloHeld ? ` (${yoloHeld})` : ""}${askWhy ? ` (asked: ${askWhy})` : ""}${postVerify ? ` — ${postVerify}` : ""}${callAsk}`, "Release?", `${oneQuestion}re-run with --confirmed once the operator answered 'Release?' in chat${callAsk ? " (add --version=patch|minor|major or --no-version for their release call)" : ""}`), isError: true };
471
496
  }
472
497
  const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleNote ? `\n\n${staleNote}` : ""}${postVerify ? `\n\n${postVerify}` : ""}${yoloHeld ? `\n\n(${yoloHeld})` : ""}`);
473
498
  if (!ok) {