pi-dev-flow 0.98.0 → 0.99.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.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Jira credentials — a Cloud API token sent as HTTP Basic `email:token` (the Atlassian Rovo MCP server's
3
+ * API-token auth). They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by
4
+ * `/flow jira login`; `JIRA_EMAIL` / `JIRA_API_TOKEN` (and optionally `JIRA_SITE`) override the file.
5
+ * Never printed, never written to project.md or to a comment.
6
+ */
7
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+
11
+ export interface JiraCreds {
12
+ site: string; // acme.atlassian.net
13
+ email: string;
14
+ token: string;
15
+ source: "env" | "file";
16
+ }
17
+
18
+ export const credsPath = (home = os.homedir()) => path.join(process.env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent"), "dev-flow", "jira.json");
19
+
20
+ /** `https://acme.atlassian.net/…` or `acme.atlassian.net` → `acme.atlassian.net`. */
21
+ export const normSite = (s: string) =>
22
+ s
23
+ .trim()
24
+ .replace(/^https?:\/\//, "")
25
+ .replace(/\/.*$/, "")
26
+ .toLowerCase();
27
+
28
+ type Store = { sites?: Record<string, { email: string; token: string }> };
29
+
30
+ function readStore(file: string): Store {
31
+ try {
32
+ return JSON.parse(readFileSync(file, "utf8")) as Store;
33
+ } catch {
34
+ return {};
35
+ }
36
+ }
37
+
38
+ /** Credentials for `site` (or for the only/first stored site when none is named), or null. */
39
+ export function loadCreds(site?: string, env: NodeJS.ProcessEnv = process.env, file = credsPath()): JiraCreds | null {
40
+ const want = site ? normSite(site) : env.JIRA_SITE ? normSite(env.JIRA_SITE) : undefined;
41
+ if (env.JIRA_EMAIL && env.JIRA_API_TOKEN && (want || env.JIRA_SITE))
42
+ return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env" };
43
+ const sites = readStore(file).sites ?? {};
44
+ const key = want ?? Object.keys(sites)[0];
45
+ const hit = key ? sites[key] : undefined;
46
+ return hit && key ? { site: key, email: hit.email, token: hit.token, source: "file" } : null;
47
+ }
48
+
49
+ export function saveCreds(site: string, email: string, token: string, file = credsPath()): void {
50
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
51
+ const store = existsSync(file) ? readStore(file) : {};
52
+ store.sites = { ...(store.sites ?? {}), [normSite(site)]: { email: email.trim(), token: token.trim() } };
53
+ writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
54
+ chmodSync(file, 0o600);
55
+ }
56
+
57
+ export const basicAuth = (c: Pick<JiraCreds, "email" | "token">) => `Basic ${Buffer.from(`${c.email}:${c.token}`).toString("base64")}`;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Minimal MCP client over Streamable HTTP — just enough to call the official Atlassian Rovo MCP server
3
+ * (https://mcp.atlassian.com/v2/mcp) from extension code, outside any model turn. pi's extension API can
4
+ * register an MCP server for the agent but offers no way for an extension to call one of its tools, and the
5
+ * Jira watch must poll without spending model turns — hence this ~150-line client instead of a dependency.
6
+ *
7
+ * Speaks JSON-RPC 2.0: `initialize` → `notifications/initialized` → `tools/list` / `tools/call`. A response
8
+ * may come back as `application/json` or as a `text/event-stream` carrying the JSON-RPC message(s); both are
9
+ * read. The server's `Mcp-Session-Id` is echoed on every later request.
10
+ *
11
+ * Pure of pi imports; `fetch` is injectable for tests.
12
+ */
13
+
14
+ export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{
15
+ ok: boolean;
16
+ status: number;
17
+ headers: { get(name: string): string | null };
18
+ text(): Promise<string>;
19
+ }>;
20
+
21
+ export interface McpTool {
22
+ name: string;
23
+ description?: string;
24
+ inputSchema?: { properties?: Record<string, unknown>; required?: string[] };
25
+ }
26
+
27
+ export interface McpCallResult {
28
+ content?: { type: string; text?: string; [k: string]: unknown }[];
29
+ structuredContent?: unknown;
30
+ isError?: boolean;
31
+ }
32
+
33
+ export class McpError extends Error {
34
+ readonly status?: number;
35
+ constructor(message: string, status?: number) {
36
+ super(message);
37
+ this.status = status;
38
+ }
39
+ }
40
+
41
+ const PROTOCOL = "2025-06-18";
42
+
43
+ /** The JSON-RPC message answering `id` in an SSE body (`data:` lines, events split by a blank line). */
44
+ export function parseSse(body: string, id: number): unknown {
45
+ for (const event of body.split(/\r?\n\r?\n/)) {
46
+ const data = event
47
+ .split(/\r?\n/)
48
+ .filter((l) => l.startsWith("data:"))
49
+ .map((l) => l.slice(5).replace(/^ /, ""))
50
+ .join("\n");
51
+ if (!data) continue;
52
+ try {
53
+ const msg = JSON.parse(data) as { id?: number };
54
+ if (msg && msg.id === id) return msg;
55
+ } catch {
56
+ /* not JSON — keep looking */
57
+ }
58
+ }
59
+ return undefined;
60
+ }
61
+
62
+ export class McpClient {
63
+ private sessionId: string | undefined;
64
+ private nextId = 1;
65
+ private ready: Promise<void> | undefined;
66
+ private toolsCache: McpTool[] | undefined;
67
+
68
+ readonly url: string;
69
+ private readonly headers: Record<string, string>;
70
+ private readonly fetchFn: FetchLike;
71
+ private readonly timeoutMs: number;
72
+
73
+ constructor(url: string, headers: Record<string, string>, fetchFn: FetchLike = globalThis.fetch as unknown as FetchLike, timeoutMs = 30_000) {
74
+ this.url = url;
75
+ this.headers = headers;
76
+ this.fetchFn = fetchFn;
77
+ this.timeoutMs = timeoutMs;
78
+ }
79
+
80
+ private async post(body: unknown, id?: number): Promise<unknown> {
81
+ const headers: Record<string, string> = {
82
+ ...this.headers,
83
+ "content-type": "application/json",
84
+ accept: "application/json, text/event-stream",
85
+ "mcp-protocol-version": PROTOCOL,
86
+ };
87
+ if (this.sessionId) headers["mcp-session-id"] = this.sessionId;
88
+ const ctl = new AbortController();
89
+ const timer = setTimeout(() => ctl.abort(), this.timeoutMs);
90
+ let res: Awaited<ReturnType<FetchLike>>;
91
+ try {
92
+ res = await this.fetchFn(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: ctl.signal });
93
+ } catch (e) {
94
+ throw new McpError(ctl.signal.aborted ? `timed out after ${this.timeoutMs / 1000}s` : `request failed: ${(e as Error).message}`);
95
+ } finally {
96
+ clearTimeout(timer);
97
+ }
98
+ const sid = res.headers.get("mcp-session-id");
99
+ if (sid) this.sessionId = sid;
100
+ const text = await res.text();
101
+ if (!res.ok) {
102
+ const hint = res.status === 401 || res.status === 403 ? " — check the email and API token, and that an org admin enabled API-token auth for the Atlassian MCP server" : "";
103
+ throw new McpError(`HTTP ${res.status}${hint}${text ? `: ${text.slice(0, 300)}` : ""}`, res.status);
104
+ }
105
+ if (id === undefined) return undefined; // a notification: 202, no body
106
+ const type = res.headers.get("content-type") ?? "";
107
+ const msg = (type.includes("text/event-stream") ? parseSse(text, id) : text ? JSON.parse(text) : undefined) as
108
+ | { result?: unknown; error?: { code: number; message: string } }
109
+ | undefined;
110
+ if (!msg) throw new McpError("empty response");
111
+ if (msg.error) throw new McpError(`MCP error ${msg.error.code}: ${msg.error.message}`);
112
+ return msg.result;
113
+ }
114
+
115
+ private async request(method: string, params?: unknown): Promise<unknown> {
116
+ const id = this.nextId++;
117
+ return this.post({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }, id);
118
+ }
119
+
120
+ /** Handshake once; a failed handshake is retried by the next call. */
121
+ init(): Promise<void> {
122
+ this.ready ??= (async () => {
123
+ await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pi-dev-flow", version: "1" } });
124
+ await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
125
+ })().catch((e) => {
126
+ this.ready = undefined;
127
+ this.sessionId = undefined;
128
+ throw e;
129
+ });
130
+ return this.ready;
131
+ }
132
+
133
+ async listTools(): Promise<McpTool[]> {
134
+ if (this.toolsCache) return this.toolsCache;
135
+ await this.init();
136
+ const out: McpTool[] = [];
137
+ let cursor: string | undefined;
138
+ do {
139
+ const r = (await this.request("tools/list", cursor ? { cursor } : {})) as { tools?: McpTool[]; nextCursor?: string };
140
+ out.push(...(r.tools ?? []));
141
+ cursor = r.nextCursor;
142
+ } while (cursor);
143
+ this.toolsCache = out;
144
+ return out;
145
+ }
146
+
147
+ async callTool(name: string, args: Record<string, unknown>): Promise<McpCallResult> {
148
+ await this.init();
149
+ try {
150
+ return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
151
+ } catch (e) {
152
+ // an expired server session: start over once
153
+ if (e instanceof McpError && e.status === 404 && this.sessionId) {
154
+ this.ready = undefined;
155
+ this.sessionId = undefined;
156
+ await this.init();
157
+ return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
158
+ }
159
+ throw e;
160
+ }
161
+ }
162
+ }
163
+
164
+ /** A tool result's payload: structuredContent, else the text blocks parsed as JSON, else the joined text. */
165
+ export function resultValue(r: McpCallResult): unknown {
166
+ if (r.structuredContent !== undefined) return r.structuredContent;
167
+ const text = (r.content ?? []).filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n");
168
+ try {
169
+ return JSON.parse(text);
170
+ } catch {
171
+ return text;
172
+ }
173
+ }
174
+
175
+ /** The text of a tool result (error messages included). */
176
+ export const resultText = (r: McpCallResult) => (r.content ?? []).filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n");
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Jira sync decisions — pure, no I/O: what a mirrored comment says, which Jira activity is the operator's
3
+ * answer, and when the watch checks next.
4
+ *
5
+ * Who may answer: only the token owner's account (`link.accountId`) — you, replying in Jira. dev-flow posts
6
+ * as that same account, so its own comments are told apart by the ids it saved (`link.posted`) and by the
7
+ * footer marker. Anyone else's comment, and any status move that answers nothing, is relayed as information.
8
+ */
9
+ import type { FlowState, JiraConfig, JiraLink, JiraStage } from "../core.ts";
10
+ import { stageOfStatus, statusForStage } from "./config.ts";
11
+ import type { JiraComment } from "./client.ts";
12
+
13
+ export const MARKER = "— dev-flow ·";
14
+
15
+ /** The checkpoint a status move answers: moving the issue into `stage` while dev-flow waits on `ask`. */
16
+ const MOVE_ANSWERS: Record<string, { stage: JiraStage; word: string }> = {
17
+ "Approve?": { stage: "implement", word: "Approved" },
18
+ "Verified?": { stage: "pre-release", word: "Verified" },
19
+ "Release?": { stage: "release", word: "Release" },
20
+ "Finish?": { stage: "done", word: "Finish" },
21
+ };
22
+
23
+ /** The status a move to which answers `ask`, for the comment's hint; undefined when none is mapped. */
24
+ export function answeringStatus(cfg: JiraConfig, link: JiraLink, ask: string | undefined): string | undefined {
25
+ const a = ask ? MOVE_ANSWERS[ask] : undefined;
26
+ return a ? statusForStage(cfg, link.type, a.stage) : undefined;
27
+ }
28
+
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 {
31
+ const L: string[] = [];
32
+ if (o.ask) L.push(`**dev-flow is waiting on: ${o.ask}**`, "");
33
+ L.push(o.text.trim());
34
+ if (o.attachments?.length) L.push("", `Attached: ${o.attachments.join(", ")}`);
35
+ if (o.ask) L.push("", `_Answer with a comment here${o.answerStatus ? `, or move the issue to **${o.answerStatus}**` : ""}._`);
36
+ L.push("", `${MARKER} ${o.slug}`);
37
+ return L.join("\n");
38
+ }
39
+
40
+ /** Does this closing agent message get mirrored? `all`: always; `asks`: when a gate question is pending or the
41
+ * message asks something (a question mark outside code). */
42
+ export function shouldMirror(mode: JiraConfig["mirror"], pendingAsk: string | undefined, text: string): boolean {
43
+ if (!text.trim()) return false;
44
+ if (mode === "all" || pendingAsk) return true;
45
+ const prose = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`]*`/g, "");
46
+ return /\?\s*(\*\*)?\s*$/m.test(prose);
47
+ }
48
+
49
+ export interface Relay {
50
+ /** answer: delivered as an operator message (it may grant a gate); info: shown, no turn, no grant */
51
+ kind: "answer" | "info";
52
+ text: string;
53
+ }
54
+
55
+ /** Read new Jira activity against the link: the relays to deliver, and the link fields to store. */
56
+ export function classifyActivity(o: {
57
+ link: JiraLink;
58
+ cfg: JiraConfig;
59
+ state: Pick<FlowState, "slug" | "stage" | "pendingAsk">;
60
+ comments: JiraComment[];
61
+ status: string;
62
+ }): { relays: Relay[]; seenUntil?: string; seenCommentId?: string; lastStatus: string } {
63
+ const { link, cfg, state } = o;
64
+ const relays: Relay[] = [];
65
+ // comment ids grow and are exact; times are a fallback (Jira's are minute-precision through the MCP server)
66
+ const num = (id: string) => (/^\d+$/.test(id) ? Number(id) : NaN);
67
+ const sinceId = link.seenCommentId ? num(link.seenCommentId) : NaN;
68
+ const since = link.seenUntil ? Date.parse(link.seenUntil) : 0;
69
+ const isFresh = (c: JiraComment) => (!Number.isNaN(sinceId) && !Number.isNaN(num(c.id)) ? num(c.id) > sinceId : Date.parse(c.created) > since);
70
+ const order = (a: JiraComment, b: JiraComment) => (!Number.isNaN(num(a.id)) && !Number.isNaN(num(b.id)) ? num(a.id) - num(b.id) : Date.parse(a.created) - Date.parse(b.created));
71
+ const fresh = o.comments.filter(isFresh).sort(order);
72
+ let seen = link.seenUntil;
73
+ let seenId = link.seenCommentId;
74
+ for (const c of fresh) {
75
+ if (!seen || Date.parse(c.created) > Date.parse(seen)) seen = c.created;
76
+ if (!Number.isNaN(num(c.id)) && (!seenId || num(c.id) > num(seenId))) seenId = c.id;
77
+ if (link.posted.includes(c.id) || c.body.includes(MARKER)) continue;
78
+ const body = c.body.trim();
79
+ if (!body) continue;
80
+ if (link.accountId && c.authorId === link.accountId) relays.push({ kind: "answer", text: `[Jira ${link.key} · your comment] ${body}` });
81
+ else relays.push({ kind: "info", text: `[Jira ${link.key} · comment from ${c.authorName || "someone else"} — information only, not an answer] ${body}` });
82
+ }
83
+ if (o.status && link.lastStatus && o.status.toLowerCase() !== link.lastStatus.toLowerCase()) {
84
+ const to = stageOfStatus(cfg, link.type, o.status);
85
+ const ans = state.pendingAsk ? MOVE_ANSWERS[state.pendingAsk] : undefined;
86
+ if (ans && to === ans.stage) relays.push({ kind: "answer", text: `[Jira ${link.key} moved to "${o.status}" (mapped to ${to}) — the operator's answer to ${state.pendingAsk}] ${ans.word}` });
87
+ else relays.push({ kind: "info", text: `[Jira ${link.key} moved from "${link.lastStatus}" to "${o.status}"${to ? ` (mapped to ${to})` : ""}; the flow is at ${state.stage}${state.pendingAsk ? `, waiting on ${state.pendingAsk}` : ""} — information only]` });
88
+ }
89
+ return { relays, seenUntil: seen, seenCommentId: seenId, lastStatus: o.status || link.lastStatus || "" };
90
+ }
91
+
92
+ /** Milliseconds from `armedAt` to the next check after `checks` checks, or null past the cap. The schedule's
93
+ * intervals are cumulative (30m, then 1h later, …) and the last one repeats. */
94
+ export function nextCheckDelay(cfg: Pick<JiraConfig, "watch" | "watchCap">, sinceMs: number, checks: number, nowMs: number): number | null {
95
+ const iv = cfg.watch.length ? cfg.watch : [1800];
96
+ let at = sinceMs;
97
+ for (let i = 0; i <= checks; i++) at += iv[Math.min(i, iv.length - 1)] * 1000;
98
+ const cap = sinceMs + cfg.watchCap * 1000;
99
+ if (at > cap) at = nowMs < cap ? cap : NaN;
100
+ if (Number.isNaN(at)) return null;
101
+ return Math.max(0, at - nowMs);
102
+ }
103
+
104
+ /** A flow slug from an issue: `DEV-123 Add login page` → `dev-123-add-login-page` (bounded). */
105
+ export function slugFromIssue(key: string, summary: string): string {
106
+ const words = `${key} ${summary}`
107
+ .toLowerCase()
108
+ .replace(/[^a-z0-9]+/g, " ")
109
+ .trim()
110
+ .split(" ")
111
+ .filter(Boolean);
112
+ let out = "";
113
+ for (const w of words) {
114
+ if ((out ? out.length + 1 : 0) + w.length > 40) break;
115
+ out = out ? `${out}-${w}` : w;
116
+ }
117
+ return out || key.toLowerCase();
118
+ }
119
+
120
+ /** The plan brief seeded from an issue. */
121
+ export function issueBrief(i: { key: string; summary: string; description: string; url: string; type: string }): string {
122
+ return [`# ${i.summary}`, "", `Jira: [${i.key}](${i.url}) (${i.type})`, "", "## Brief (from the issue)", "", i.description.trim() || "_(the issue has no description)_", ""].join("\n");
123
+ }
package/src/projectmd.ts CHANGED
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
9
9
  import path from "node:path";
10
- import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, parseSize, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
10
+ import { parseJiraBlock } from "./jira/config.ts";
11
+ import { applyAnswer, type JiraConfig, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, parseSize, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
11
12
 
12
13
  export const MD_STAGES = ["global", "plan", "implement", "pre-release", "release"] as const;
13
14
  export type MdStage = (typeof MD_STAGES)[number];
@@ -25,6 +26,8 @@ export interface ParsedMd {
25
26
  prose: Record<string, string>;
26
27
  /** ## global `flow-worker` block lines — the setup every stage worker's brief carries (gh#201) */
27
28
  workerPreamble: string[];
29
+ /** ## global `flow-jira` block — the opt-in Jira sync (src/jira/config.ts) */
30
+ jira?: JiraConfig;
28
31
  }
29
32
 
30
33
  // stage → flow-key → config dot-path (aliases); unknown keys warn
@@ -138,6 +141,8 @@ export function parseProjectMd(text: string): ParsedMd {
138
141
  let checkName = "";
139
142
  let checkBody: string[] = [];
140
143
  let guardBody: { line: string; where: string }[] = [];
144
+ let jiraBody: { line: string; where: string }[] = [];
145
+ let jiraSeen = false;
141
146
  let lastLine = ""; // for fence-start line numbers (1-based = index+1)
142
147
  text.split("\n").forEach((line, i) => {
143
148
  const where = `line ${i + 1}`;
@@ -155,6 +160,18 @@ export function parseProjectMd(text: string): ParsedMd {
155
160
  if (guardBody.length) parseGuardRules(guardBody, stage, p);
156
161
  guardBody = [];
157
162
  }
163
+ if (inFence === "flow-jira") {
164
+ if (stage !== "global") p.warn.push(`${where}: flow-jira belongs to ## global — the block under ## ${stage ?? "(no stage)"} is ignored`);
165
+ else if (jiraSeen) p.warn.push(`${where}: a second flow-jira block — ignored (one per project)`);
166
+ else {
167
+ jiraSeen = true;
168
+ const r = parseJiraBlock(jiraBody);
169
+ p.hard.push(...r.hard);
170
+ p.warn.push(...r.warn);
171
+ if (r.cfg && !r.hard.length) p.jira = r.cfg;
172
+ }
173
+ jiraBody = [];
174
+ }
158
175
  inFence = null;
159
176
  checkName = "";
160
177
  checkBody = [];
@@ -226,6 +243,7 @@ export function parseProjectMd(text: string): ParsedMd {
226
243
  } else if (line.trim()) p.warn.push(`${where}: flow-worker lines belong to ## global — ignored under ## ${stage ?? "(no stage)"}`);
227
244
  }
228
245
  else if (inFence === "flow-guard") guardBody.push({ line, where });
246
+ else if (inFence === "flow-jira") jiraBody.push({ line, where });
229
247
  return;
230
248
  }
231
249
  lastLine = where;
@@ -238,6 +256,7 @@ export function parseProjectMd(text: string): ParsedMd {
238
256
  checkName = lang.slice("flow-check".length).trim();
239
257
  } else if (lang === "flow-guard") inFence = "flow-guard";
240
258
  else if (lang === "flow-worker") inFence = "flow-worker";
259
+ else if (lang === "flow-jira") inFence = "flow-jira";
241
260
  else inFence = lang || "code";
242
261
  return;
243
262
  }
@@ -312,6 +331,7 @@ export function mdToConfig(p: ParsedMd): Config {
312
331
  c.checklist = p.checklist;
313
332
  c.prose = p.prose;
314
333
  if (p.workerPreamble.length) c.workerPreamble = [...p.workerPreamble];
334
+ if (p.jira) c.jira = structuredClone(p.jira);
315
335
  return c;
316
336
  }
317
337
 
@@ -236,7 +236,7 @@ export async function releaseTags(root: string): Promise<string[] | null> {
236
236
  }
237
237
 
238
238
  export const GATE_HELP =
239
- "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note> [--evidence=<file:line>]|list|plan|tidy|move <id> --playbook|--code|done <id>[,<id>…] [<what>]|reopen <id> [<why>]|defer <id> <why>|--same <id> [<evidence>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>[,<n>…]|drop <n>[,<n>…]|tidy] | doctor [<issue note>] | guard <command>|--path <file> | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--reflections=r<id>,…] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | review [done <verdict>|--skip] | approve [--yolo] [--version=patch|minor|major|--no-version] | bump <patch|minor|major|none> [slug] | verify [--yolo] [--port=<n>|--replace] [--version=<kind>|--no-version] | release [--yolo|--version=<kind>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — approve --confirmed carries the operator's release call on a versioned project: --version=patch|minor|major (the kind of step — the number is counted from the newest tag when the release runs) or --no-version (merge unreleased), asked with Approve?; it is never asked again, and the operator changes it on any later gate call (verify/release take the same flags) or with bump <kind> --confirmed, until the tag is cut — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list prints open items by id (r<n>: never renumbered), plan groups them into flows with the start command, move <id> re-files one, done <id> checks a fixed one off, reopen <id> brings back one closed by mistake (from the archive too), --same <id> counts a recurrence on its row, defer <id> <why> leaves a row linked to the bound flow open, tidy moves closed ones to reflections-archive.md — start --reflections=<ids> links rows to the flow and finish closes them as fixed by it — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped); <n> is the row number list prints — done leaves the others in place, drop and tidy renumber — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — review records the review flow verify requires before it asks Verified? (and flow release before it ships): done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
239
+ "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note> [--evidence=<file:line>]|list|plan|tidy|move <id> --playbook|--code|done <id>[,<id>…] [<what>]|reopen <id> [<why>]|defer <id> <why>|--same <id> [<evidence>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>[,<n>…]|drop <n>[,<n>…]|tidy] | doctor [<issue note>] | guard <command>|--path <file> | status [slug] [--json] | start <slug> [--jira=<KEY>|--no-jira] [--ui|--patch|--docs] [--reflections=r<id>,…] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | jira [status|init [--project=<KEY>] [--types=<A,B>] [--map=<Type>.<stage>=<Status>]… [--mirror=asks|all] [--confirmed]|create [--summary=<text>] [--description=<text>|--description-file=<path>] [--type=<Type>] [--roadmap=<n>[,<n>…]] [--confirmed]|link <KEY>|unlink|check] | test | check | health | review [done <verdict>|--skip] | approve [--yolo] [--version=patch|minor|major|--no-version] | bump <patch|minor|major|none> [slug] | verify [--yolo] [--port=<n>|--replace] [--version=<kind>|--no-version] | release [--yolo|--version=<kind>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — approve --confirmed carries the operator's release call on a versioned project: --version=patch|minor|major (the kind of step — the number is counted from the newest tag when the release runs) or --no-version (merge unreleased), asked with Approve?; it is never asked again, and the operator changes it on any later gate call (verify/release take the same flags) or with bump <kind> --confirmed, until the tag is cut — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list prints open items by id (r<n>: never renumbered), plan groups them into flows with the start command, move <id> re-files one, done <id> checks a fixed one off, reopen <id> brings back one closed by mistake (from the archive too), --same <id> counts a recurrence on its row, defer <id> <why> leaves a row linked to the bound flow open, tidy moves closed ones to reflections-archive.md — start --reflections=<ids> links rows to the flow and finish closes them as fixed by it — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped); <n> is the row number list prints — done leaves the others in place, drop and tidy renumber — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — review records the review flow verify requires before it asks Verified? (and flow release before it ships): done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
240
240
  export const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
241
241
  export const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
242
242
  export const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -12,10 +12,13 @@ import { type RunResult, type Session, ago, behindNote, releaseDevSlot, pendingC
12
12
  import { GIT_TRACK_NOTE, isSelfRepo, renderQuestions, setupQuestions, tagPatternEvidence } from "./setup.ts";
13
13
  import { foldRows, foldView, legacyPluginRows, pluginUpstream, reflectDeferNote, reflectDoneNote, reflectList, reflectMoveNote, reflectNote, reflectPlanNote, reflectReopenNote, reflectSameNote, reflectTidy } from "./reflect.ts";
14
14
  import { gateFinish, gateRelease, gateReleaseDone, gateVerify } from "./ship.ts";
15
+ import { type JiraGateHooks, gateJira, linkFlow, linkedStages, slugForIssue, startWithoutKey, syncStageMoves } from "./jira.ts";
15
16
 
16
17
  /** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
17
18
  export interface FlowHooks {
18
19
  reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean; report?: { findings: ReflectFinding[]; open: ReflectOpenCheck[] } }>;
20
+ /** the Jira sync's delivery of relayed answers and its watch (extensions/dev-flow.ts) */
21
+ jira?: JiraGateHooks;
19
22
  }
20
23
 
21
24
  /** Write `.dev-flow/.gitignore` when it is missing; true when it did. Best effort — never fails a gate. */
@@ -54,10 +57,38 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
54
57
  state.yolo = true;
55
58
  return null;
56
59
  };
57
- const slugArg = rest.find((a) => !a.startsWith("--"));
60
+ let slugArg = rest.find((a) => !a.startsWith("--"));
61
+ // flow start --jira=KEY: the issue must exist, be in the project and of a synced type — and it names the
62
+ // slug when none was given
63
+ const jiraKey = sub === "start" ? flagValue(rest, "jira")?.toUpperCase() ?? null : null;
64
+ if (jiraKey && !slugArg) {
65
+ const s = await slugForIssue(cfg, jiraKey);
66
+ if ("error" in s) return { text: `start --jira=${jiraKey}: ${s.error}`, isError: true };
67
+ slugArg = s.slug;
68
+ rest.unshift(s.slug);
69
+ } else if (jiraKey && !cfg.jira) return { text: "--jira needs Jira sync configured — run flow jira init first", isError: true };
58
70
  const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord, hooks };
71
+ // the Jira sync follows stage changes: every linked flow's stage before the gate, compared after it
72
+ const before = cfg.jira && sub !== "jira" ? linkedStages(root) : new Map();
73
+ const res = await dispatch(sub, o);
74
+ if (jiraKey && !res.isError && slugArg && readState(root, slugArg)) {
75
+ const r = await linkFlow(root, cfg, slugArg, jiraKey, { seedPlan: true });
76
+ return { ...res, text: `${res.text}\n${"error" in r ? `${AGENT_MARK}jira: the flow started but was not linked to ${jiraKey}: ${r.error} — flow jira link ${jiraKey} retries` : r.lines.join("\n")}` };
77
+ }
78
+ if (sub === "start" && !jiraKey && cfg.jira && !res.isError && slugArg && readState(root, slugArg) && !flag("no-jira")) {
79
+ const lines = await startWithoutKey(root, cfg, slugArg).catch((e) => [`${AGENT_MARK}jira: ${(e as Error).message}`]);
80
+ if (lines.length) return { ...res, text: `${res.text}\n${lines.join("\n")}` };
81
+ }
82
+ const moves = before.size ? await syncStageMoves(root, cfg, before).catch((e) => [`${AGENT_MARK}jira: status sync failed: ${(e as Error).message}`]) : [];
83
+ return moves.length ? { ...res, text: `${res.text}\n${moves.join("\n")}` } : res;
84
+ }
59
85
 
86
+ async function dispatch(sub: string, o: GateCtx): Promise<RunResult> {
87
+ const { root, cfg, rest, flag, sess, hooks } = o;
60
88
  switch (sub) {
89
+ case "jira":
90
+ return gateJira(root, cfg, rest, flag, sess.slug, hooks.jira);
91
+
61
92
  case "init":
62
93
  return gateInit(o);
63
94
 
@@ -0,0 +1,126 @@
1
+ /** dev-flow runtime — the Jira reply watch: per session, one timer checking the linked issue on the playbook's
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.
4
+ *
5
+ * While a watch is armed, pi-web's session-liveness registry keeps the session from being reaped as idle
6
+ * (pi-web docs/integrations.md: Symbol.for("@agegr/pi-web/session-liveness/v1")); elsewhere the lease is a
7
+ * no-op and the timer simply lives as long as the process. A session that ends keeps `jira.watch` in state,
8
+ * and the next session_start catches up and re-arms it. */
9
+ import { loadProject } from "../projectmd.ts";
10
+ import { nextCheckDelay, type Relay } from "../jira/sync.ts";
11
+ import { dfDir, readState } from "./base.ts";
12
+ import { checkReplies, disarmWatch } from "./jira.ts";
13
+
14
+ export interface WatchDeps {
15
+ /** deliver relays to the session `key` */
16
+ relay: (key: string, relays: Relay[]) => void;
17
+ /** a note for the operator only (watch stopped, check failed) */
18
+ note: (key: string, text: string) => void;
19
+ setTimer?: (fn: () => void, ms: number) => unknown;
20
+ clearTimer?: (t: unknown) => void;
21
+ nowMs?: () => number;
22
+ }
23
+
24
+ interface Armed {
25
+ root: string;
26
+ slug: string;
27
+ timer: unknown;
28
+ at: number;
29
+ }
30
+
31
+ type LivenessRegistry = { version: number; register: (o: { name: string; sessionId: string; sessionFile?: string; isActive: () => boolean }) => () => void };
32
+
33
+ /** The longest a single timer waits; a long interval is reached by re-arming (Node timers cap near 24.8 days). */
34
+ const MAX_TIMER_MS = 6 * 3600 * 1000;
35
+
36
+ export class JiraWatch {
37
+ private readonly armed = new Map<string, Armed>();
38
+ private readonly leases = new Map<string, () => void>();
39
+ private readonly busy = new Set<string>();
40
+ private readonly deps: WatchDeps;
41
+
42
+ constructor(deps: WatchDeps) {
43
+ this.deps = deps;
44
+ }
45
+
46
+ private now() {
47
+ return this.deps.nowMs?.() ?? Date.now();
48
+ }
49
+
50
+ isArmed(key: string): boolean {
51
+ return this.armed.has(key);
52
+ }
53
+
54
+ nextAt(key: string): number | undefined {
55
+ return this.armed.get(key)?.at;
56
+ }
57
+
58
+ /** Hold pi-web's liveness lease for this session while a watch is armed (once per session). */
59
+ lease(key: string, sessionId: string | undefined, sessionFile: string | undefined): void {
60
+ if (this.leases.has(key) || !sessionId) return;
61
+ const reg = (globalThis as Record<symbol, unknown>)[Symbol.for("@agegr/pi-web/session-liveness/v1")] as LivenessRegistry | undefined;
62
+ if (reg?.version !== 1) return;
63
+ try {
64
+ this.leases.set(key, reg.register({ name: "pi-dev-flow jira watch", sessionId, sessionFile, isActive: () => this.armed.has(key) }));
65
+ } catch {
66
+ /* a registry that refuses leaves pi-web's idle timeout in charge */
67
+ }
68
+ }
69
+
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. */
72
+ arm(key: string, root: string, slug: string): void {
73
+ this.cancel(key);
74
+ const st = readState(root, slug);
75
+ const cfg = loadProject(dfDir(root)).cfg.jira;
76
+ const w = st?.jira?.watch;
77
+ if (!cfg || !w) return;
78
+ const delay = nextCheckDelay(cfg, Date.parse(w.since), w.checks, this.now());
79
+ if (delay === null) {
80
+ disarmWatch(root, slug);
81
+ 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
+ return;
83
+ }
84
+ const ms = Math.min(delay, MAX_TIMER_MS);
85
+ 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);
87
+ this.armed.set(key, { root, slug, timer, at: this.now() + ms });
88
+ }
89
+
90
+ /** Run one check now (catch-up), then re-arm. */
91
+ async checkNow(key: string, root: string, slug: string): Promise<void> {
92
+ await this.tick(key, root, slug, false);
93
+ }
94
+
95
+ private async tick(key: string, root: string, slug: string, partial: boolean): Promise<void> {
96
+ this.armed.delete(key);
97
+ if (partial) return this.arm(key, root, slug);
98
+ if (this.busy.has(key)) return;
99
+ this.busy.add(key);
100
+ 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);
104
+ } catch (e) {
105
+ this.deps.note(key, `Jira check failed (will retry on schedule): ${(e as Error).message}`);
106
+ } finally {
107
+ this.busy.delete(key);
108
+ }
109
+ this.arm(key, root, slug);
110
+ }
111
+
112
+ /** Stop the timer (the state keeps its watch, so a later session can resume it). */
113
+ cancel(key: string): void {
114
+ const a = this.armed.get(key);
115
+ if (!a) return;
116
+ (this.deps.clearTimer ?? ((t: unknown) => clearTimeout(t as NodeJS.Timeout)))(a.timer);
117
+ this.armed.delete(key);
118
+ }
119
+
120
+ /** The session ended: stop the timer and give the lease back. */
121
+ release(key: string): void {
122
+ this.cancel(key);
123
+ this.leases.get(key)?.();
124
+ this.leases.delete(key);
125
+ }
126
+ }