pi-dev-flow 0.98.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.99.0] - 2026-12-03
8
+
9
+ **Opt-in Jira sync: start a flow from an issue, or have one created; get questions on the issue with the plan attached; answer by commenting or by moving the issue.**
10
+
11
+ ### Added
12
+ - **Jira sync, off by default.** `flow jira init` sets it up for a project, writing a `flow-jira` block to `project.md`:
13
+ - it checks your login (`/flow jira login` stores an Atlassian API token outside the repo)
14
+ - asks for the Jira project and issue types
15
+ - suggests a Jira status for each flow stage from each type's workflow
16
+
17
+ Once it is on:
18
+ - `flow start --jira=KEY` starts a flow from an issue, and its description seeds the plan.
19
+ - The agent's questions are posted on the issue as comments, with the plan, mockups and named screenshots attached.
20
+ - You can answer by commenting ("Approved") or by moving the issue to the status mapped to the next stage.
21
+ - Stage changes move the issue in turn.
22
+
23
+ dev-flow can also create issues:
24
+ - **A flow started without an issue:** the agent offers to create one in the synced project (`flow jira create`, after you see the summary), or to link an existing one.
25
+ - **Roadmap items:** `flow jira create --roadmap=<n>,…` makes one issue per item and stamps the item with its key. Starting a picked item links its issue.
26
+
27
+ While a question waits, dev-flow checks for your reply after 30m, 1h, 2h, then every 4h for up to 72h, and keeps the pi-web session alive in the meantime. A session that ended anyway catches up when it is next opened. It uses Atlassian's official Rovo MCP server. See [docs/jira.md](docs/jira.md).
28
+
7
29
  ## [0.98.0] - 2026-11-29
8
30
 
9
31
  **A `confirm` or `protect` rule asks in chat instead of a dialog that held the call for hours. Also: `flow guard` tests a playbook rule, a release call the operator never named is shown before it counts, a hand rebase keeps the Verified? word, and five smaller fixes to workers, briefs and cleanup.**
package/README.md CHANGED
@@ -106,6 +106,10 @@ More detail, and what this deliberately is *not*, is in
106
106
  **`/flow-simplify`** removes dead and duplicated code, one verified commit at a time.
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
+ - **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.
112
+ [More](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/jira.md)
109
113
  - **A roadmap.** `.dev-flow/roadmap.md` is a backlog of future features. `flow start <slug>` can
110
114
  pick one up.
111
115
 
@@ -132,6 +136,7 @@ More detail, and what this deliberately is *not*, is in
132
136
  | [Guardrails](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/guardrails.md) | everything enforced, and the deliberate limits |
133
137
  | [Reflections](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/reflections.md) | the agent's notes, the closing review, nudges |
134
138
  | [Concurrency](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/concurrency.md) | several sessions in one repo |
139
+ | [Jira sync](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/jira.md) | starting flows from issues, answering in Jira |
135
140
  | [Headless](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/headless.md) | driving dev-flow from a bot, web UI or queue |
136
141
  | [Development](https://github.com/dmarchevsky/pi-dev-flow/blob/main/docs/development.md) | working on dev-flow itself |
137
142
 
package/docs/jira.md ADDED
@@ -0,0 +1,68 @@
1
+ # Jira sync
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.
4
+
5
+ It talks to Atlassian's official **Rovo MCP server** (`https://mcp.atlassian.com/v2/mcp`). It uses that server's tools for everything, except two calls the server has no tool for, which go to Jira's REST API with the same token (see [Limits](#limits)). Jira Cloud only.
6
+
7
+ ## Setup
8
+
9
+ 1. **Create an API token** at id.atlassian.com → Security → API tokens. Choose **Create API token**, the plain kind. A scoped token ("with scopes") works with the MCP server, but Jira's REST API refuses it unless it carries `read:jira-work`, `write:jira-work` and `read:jira-user`, and attachments go through REST. An org admin must have turned on API-token authentication for the Rovo MCP server (Atlassian Administration → Rovo MCP server). Without that, the server only accepts OAuth sign-in.
10
+ 2. **Run `/flow jira login [site]`** and type the site, your email and the token into its dialogs. dev-flow checks them against the MCP server, then saves them to `~/.pi/agent/dev-flow/jira.json` (mode 0600). The token never passes through the chat or the agent, and is never written to `project.md`. You can use environment variables instead: `JIRA_SITE`, `JIRA_EMAIL` and `JIRA_API_TOKEN` override the file.
11
+ 3. **Ask the agent to set up Jira sync.** It runs `flow jira init`, which asks you one question at a time:
12
+ - **Jira project?** Which project this repo syncs with.
13
+ - **Issue types?** The types a flow may start from, such as Story or Bug.
14
+ - **Mapping OK?** For each type, dev-flow reads its workflow and suggests a status for each flow stage. You can change any of them.
15
+
16
+ The answers are written to `project.md`:
17
+
18
+ ```flow-jira
19
+ site = acme.atlassian.net
20
+ cloudId = …
21
+ project = DEV
22
+ issueTypes = Story, Bug
23
+ status.Story.plan = To Do, Backlog
24
+ status.Story.implement = In Progress
25
+ status.Story.pre-release = In Review
26
+ status.Story.release = Ready for Release
27
+ status.Story.done = Done
28
+ ```
29
+
30
+ | Key | Meaning |
31
+ |---|---|
32
+ | `status.<Type>.<stage>` | Statuses that mean that stage: `plan`, `implement`, `pre-release`, `release` or `done`. dev-flow moves the issue to the first one listed. |
33
+ | `mirror` | `asks` (the default) posts the agent's closing message when it asks you something. `all` posts every closing message. |
34
+ | `watch` | How long to wait between checks for your reply after a question: `30m, 1h, 2h, 4h` by default. The last interval repeats. |
35
+ | `watchCap` | Stop checking this long after the question. Default `72h`. |
36
+
37
+ ## Working from an issue
38
+
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
+ - **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
+ - **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
+ - **Answering in Jira:**
44
+ - **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.
45
+ - **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.
46
+
47
+ Your answer arrives in the session as your own message, so the gates treat it exactly like a chat reply.
48
+ - **dev-flow moves the issue too.** When a stage changes (approve, verify, release, finish), it moves the issue to the mapped status if the workflow allows that transition. If it can't, it says so and the flow carries on.
49
+
50
+ ## Watching for your reply
51
+
52
+ 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.
53
+
54
+ - **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.
55
+ - **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.
56
+ - **Answering in chat** stops the watch. The next question is posted and watched again.
57
+ - `flow jira check` checks now. `flow jira status` shows the links and any watch in progress.
58
+
59
+ ## The agent's own Jira tools
60
+
61
+ In a synced project, dev-flow also registers the Atlassian MCP server for the agent as `atlassian`, so it can read the issue, linked issues and comments when it needs to. The tools are found through tool search. If your `mcp.json` already has a server with that name, yours is used.
62
+
63
+ ## Limits
64
+
65
+ - Jira Cloud only. The Rovo MCP server does not serve Jira Data Center.
66
+ - The MCP server's upload tool takes a local file path and hands back a command to run, so attachments always go through Jira's REST API.
67
+ - Two calls fall back to Jira's REST API with the same token when the MCP server can't do the job: listing workflow statuses per issue type (`/rest/api/3/project/{key}/statuses`), and attaching a file (`/rest/api/3/issue/{key}/attachments`).
68
+ - dev-flow polls Jira; it does not use webhooks, which would need a public URL for Jira to call.
package/docs/playbook.md CHANGED
@@ -231,6 +231,8 @@ merge-strategy setting for that.
231
231
  | `mockupGlobs` | `*.png` | what counts as a mockup render for `--ui` |
232
232
  | `bashTimeout` | `inject` | `require`: refuse shell calls with no timeout, instead of adding one |
233
233
 
234
+ A ` ```flow-jira ` block under `## global` turns on the Jira sync. `flow jira init` writes it; see [jira.md](jira.md).
235
+
234
236
  ## flow init in detail
235
237
 
236
238
  - **Fresh repo:** prints the detection report and the questions. Writes nothing.
@@ -34,10 +34,16 @@ import { type Session, presentRun, worktreeFingerprint } from "../src/runtime/ch
34
34
  import { isSelfRepo } from "../src/runtime/setup.ts";
35
35
  import { foldView, pluginUpstream } from "../src/runtime/reflect.ts";
36
36
  import { type FlowHooks, runFlow } from "../src/runtime/gates.ts";
37
+ import { JiraWatch } from "../src/runtime/jira-watch.ts";
38
+ import { mirrorClosingMessage, disarmWatch, jiraSeams, resetJiraClients } from "../src/runtime/jira.ts";
39
+ import { basicAuth, loadCreds, normSite, saveCreds } from "../src/jira/creds.ts";
40
+ import { JiraClient, MCP_URL } from "../src/jira/client.ts";
41
+ import type { Relay } from "../src/jira/sync.ts";
37
42
  import { grantCheck, grantRecord, isFriction, lastOperatorText, newGrantLedger, operatorMessageCount, type RefusalStreak } from "../src/runtime/grants.ts";
38
43
  import { PIWEB_SUBAGENT, WORKER_TOOLS, piwebLiveClaim, piwebStamp, piwebWorkerMeta, reflectSeams, sessionHeaders, stageWorkerSpawn, workerName, workerSessions, workerTiming, writeTranscriptDigests } from "../src/runtime/workers.ts";
39
44
  export { compactionTakeover } from "../src/runtime/base.ts";
40
45
  export { reflectSeams, stageWorkerSpawn, workerTiming } from "../src/runtime/workers.ts";
46
+ export { jiraSeams } from "../src/runtime/jira.ts";
41
47
 
42
48
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
43
49
  * entries and asserts the warnings the real duplicate would print. */
@@ -221,12 +227,108 @@ export default function devFlow(pi: ExtensionAPI) {
221
227
  return `${core}\n\n`;
222
228
  };
223
229
 
230
+ // ---- Jira sync (project.md flow-jira; off without it) ----
231
+ /** The session this extension instance serves right now — a watch firing for another (an ended or replaced
232
+ * session) leaves its question in state for that session's next start instead of talking into this one. */
233
+ let liveKey: string | null = null;
234
+ const deliverRelays = (key: string, relays: Relay[]) => {
235
+ if (key !== liveKey || !relays.length) return;
236
+ const info = relays.filter((r) => r.kind === "info").map((r) => r.text);
237
+ const answers = relays.filter((r) => r.kind === "answer").map((r) => r.text);
238
+ try {
239
+ if (info.length) pi.sendMessage({ customType: "dev-flow-jira", content: info.join("\n\n"), display: true });
240
+ // an answer is the operator's own word, typed in Jira: delivered as their message, so the grant rules
241
+ // (an operator message after the question) hold as for a chat answer
242
+ if (answers.length) pi.sendUserMessage(answers.join("\n\n"), { deliverAs: "followUp" });
243
+ } catch {
244
+ /* a stale session: its state keeps the watch for the next start */
245
+ }
246
+ };
247
+ const jiraWatch = new JiraWatch({
248
+ relay: deliverRelays,
249
+ note: (key, text) => {
250
+ if (key !== liveKey) return;
251
+ try {
252
+ pi.sendMessage({ customType: "dev-flow-jira", content: text, display: true });
253
+ } catch {
254
+ /* stale session */
255
+ }
256
+ },
257
+ });
258
+ /** Arm (or drop) this session's watch from its bound flow's state, holding pi-web's liveness lease. */
259
+ const rearmJira = (ctx: ExtensionContext, root: string) => {
260
+ const key = sessionKey(ctx);
261
+ const st = boundFeature(root, key);
262
+ if (!st?.jira?.watch) return jiraWatch.cancel(key);
263
+ try {
264
+ jiraWatch.lease(key, ctx.sessionManager?.getSessionId(), ctx.sessionManager?.getSessionFile?.());
265
+ } catch {
266
+ /* no session manager */
267
+ }
268
+ jiraWatch.arm(key, root, st.slug);
269
+ };
270
+ const jiraHooks = (ctx: ExtensionContext, root: string): FlowHooks["jira"] => ({ relay: (relays) => deliverRelays(sessionKey(ctx), relays), rearm: () => rearmJira(ctx, root) });
271
+ /** The text of the newest assistant message on the branch. */
272
+ const closingText = (ctx: ExtensionContext): string => {
273
+ try {
274
+ const branch = ctx.sessionManager?.getBranch() ?? [];
275
+ for (let i = branch.length - 1; i >= 0; i--) {
276
+ // SAFETY: narrow structural view of the SessionEntry union; only a message entry's message is read
277
+ const e = branch[i] as unknown as { type?: string; message?: { role?: string } };
278
+ if (e.type !== "message") continue;
279
+ if (e.message?.role === "user") return "";
280
+ if (e.message?.role === "assistant") {
281
+ const t = assistantTexts([e.message]).join("\n").trim();
282
+ if (t) return t;
283
+ }
284
+ }
285
+ } catch {
286
+ /* unreadable branch */
287
+ }
288
+ return "";
289
+ };
290
+ /** Give the agent the Atlassian MCP server's tools (deferred: found through tool search) for a Jira-synced
291
+ * project — the issue, its links, its history. A server of the same name in mcp.json wins. */
292
+ const registerAtlassianMcp = (cfg: ReturnType<typeof loadProject>["cfg"]) => {
293
+ if (!cfg.jira) return;
294
+ const creds = loadCreds(cfg.jira.site, jiraSeams.env ?? process.env, jiraSeams.credsFile);
295
+ if (!creds) return;
296
+ try {
297
+ pi.registerMcpServer?.("atlassian", { url: MCP_URL, headers: { Authorization: basicAuth(creds) }, exposure: "deferred", description: `Atlassian Jira/Confluence on ${creds.site} (dev-flow Jira sync: project ${cfg.jira.project})` });
298
+ } catch {
299
+ /* another extension owns the name, or no MCP support: the sync itself does not need it */
300
+ }
301
+ };
302
+ /** /flow jira login [site] — the operator's own dialog: the token never passes through the chat or the agent. */
303
+ const jiraLogin = async (ctx: ExtensionContext, root: string, siteArg?: string): Promise<string> => {
304
+ if (!ctx.hasUI) return "flow jira login needs a dialog — set JIRA_SITE, JIRA_EMAIL and JIRA_API_TOKEN instead";
305
+ const cfg = initiated(root) ? loadProject(dfDir(root)).cfg : undefined;
306
+ const site = siteArg ?? cfg?.jira?.site ?? (await ctx.ui.input("Jira site", "acme.atlassian.net"));
307
+ if (!site?.trim()) return "login cancelled";
308
+ const prev = loadCreds(site, {}, jiraSeams.credsFile);
309
+ const email = await ctx.ui.input(`Atlassian account email for ${normSite(site)}`, prev?.email ?? "you@example.com");
310
+ if (!email?.trim()) return "login cancelled";
311
+ const token = await ctx.ui.input("Atlassian API token (id.atlassian.com → Security → API tokens)", "paste the token");
312
+ if (!token?.trim()) return "login cancelled";
313
+ const probe = new JiraClient({ site: normSite(site), email: email.trim(), token: token.trim(), source: "file" }, { fetch: jiraSeams.fetch });
314
+ const me = await probe.me();
315
+ if (!me.ok) return `not saved — the Atlassian MCP server refused the token: ${me.error}`;
316
+ saveCreds(site, email, token, jiraSeams.credsFile);
317
+ resetJiraClients();
318
+ if (cfg) registerAtlassianMcp(cfg);
319
+ return `Jira login saved for ${normSite(site)} — authenticated as ${me.value.displayName}. ${cfg?.jira ? "Jira sync is ready." : "Next: flow jira init picks the project, issue types and status mapping."}`;
320
+ };
321
+
224
322
  pi.registerCommand("flow", {
225
323
  description: `dev-flow gates: ${GATE_HELP}`,
226
324
  handler: async (args, ctx) => {
227
325
  const cmd = parse(args);
228
326
  const root = await flowRoot(ctx.cwd);
229
- const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root), finishReflectHook("flow-finish", ctx, root));
327
+ if (cmd[0] === "jira" && cmd[1] === "login") {
328
+ pi.sendMessage({ customType: "flow", content: await jiraLogin(ctx, root, cmd[2]), display: true });
329
+ return;
330
+ }
331
+ const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root), { ...finishReflectHook("flow-finish", ctx, root), jira: jiraHooks(ctx, root) });
230
332
  // gate output belongs to the conversation, not a toast: display:true renders a [flow] box (TUI + web), no triggerTurn so no model turn fires.
231
333
  // bare reflect is the exception: its whole output is instructions for the agent — displayed without a turn, they would never execute.
232
334
  const wake = cmd.length === 1 && cmd[0] === "reflect";
@@ -258,7 +360,7 @@ export default function devFlow(pi: ExtensionAPI) {
258
360
  // gh#190: --confirmed stands for the operator's chat answer — refuse it when no operator message came after the question
259
361
  const users = operatorMessageCount((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })());
260
362
  const selfGrant = grantCheck(params.args, sessionKey(ctx), users, grantLedger);
261
- const res = selfGrant ? { text: selfGrant, isError: true } : await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
363
+ const res = selfGrant ? { text: selfGrant, isError: true } : await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), { ...finishReflectHook(id, ctx, root, signal, onUpdate), jira: jiraHooks(ctx, root) });
262
364
  grantRecord(params.args, sessionKey(ctx), users, res, grantLedger);
263
365
  if (!res.isError) maybeCompactNow(ctx, root);
264
366
  // two readers: the model gets every instruction, the operator's row renders the view (renderResult) —
@@ -601,6 +703,21 @@ export default function devFlow(pi: ExtensionAPI) {
601
703
  const root = await flowRoot(ctx.cwd);
602
704
  rebuildSession(ctx, root);
603
705
  refreshStatus(ctx, root);
706
+ liveKey = sessionKey(ctx);
707
+ if (!initiated(root)) return;
708
+ const cfg = loadProject(dfDir(root)).cfg;
709
+ if (!cfg.jira) return;
710
+ registerAtlassianMcp(cfg);
711
+ // a question asked before this session (or before a restart) is caught up now, then watched again
712
+ const st = boundFeature(root, sessionKey(ctx));
713
+ if (st?.jira?.watch && !isWorkerSession(ctx)) {
714
+ try {
715
+ jiraWatch.lease(sessionKey(ctx), ctx.sessionManager?.getSessionId(), ctx.sessionManager?.getSessionFile?.());
716
+ } catch {
717
+ /* no session manager */
718
+ }
719
+ void jiraWatch.checkNow(sessionKey(ctx), root, st.slug);
720
+ }
604
721
  });
605
722
  pi.on("session_tree", async (_event, ctx) => {
606
723
  if (!guardsAreMine()) return;
@@ -612,6 +729,8 @@ export default function devFlow(pi: ExtensionAPI) {
612
729
  WEB_CHIP_KEYS.delete(sessionKey(ctx)); // the session's UI is gone; a long-lived server must not keep its slot
613
730
  hollowStreak.delete(sessionKey(ctx));
614
731
  refusalStreak.delete(sessionKey(ctx));
732
+ jiraWatch.release(sessionKey(ctx)); // the question stays in state: the next session_start catches up
733
+ if (liveKey === sessionKey(ctx)) liveKey = null;
615
734
  if (!guardsAreMine()) return;
616
735
  const root = await flowRoot(ctx.cwd);
617
736
  if (!existsSync(dfDir(root))) return;
@@ -628,7 +747,20 @@ export default function devFlow(pi: ExtensionAPI) {
628
747
  // Idle backstop: long between-gate runs compact here instead of letting pi hit the threshold mid-work.
629
748
  pi.on("agent_settled", async (_event, ctx) => {
630
749
  if (!guardsAreMine()) return;
631
- maybeCompactNow(ctx, await flowRoot(ctx.cwd));
750
+ const root = await flowRoot(ctx.cwd);
751
+ maybeCompactNow(ctx, root);
752
+ // the agent stopped: whatever it closed on is waiting for the operator — mirror it to the linked issue
753
+ if (!initiated(root) || isWorkerSession(ctx)) return;
754
+ const cfg = loadProject(dfDir(root)).cfg;
755
+ const st = cfg.jira ? boundFeature(root, sessionKey(ctx)) : null;
756
+ if (!st?.jira) return;
757
+ try {
758
+ const r = await mirrorClosingMessage(root, cfg, st.slug, closingText(ctx));
759
+ if (r) pi.sendMessage({ customType: "dev-flow-jira", content: r.note, display: true });
760
+ } catch (e) {
761
+ pi.sendMessage({ customType: "dev-flow-jira", content: `Jira ${st.jira.key}: mirror failed — ${(e as Error).message}`, display: true });
762
+ }
763
+ rearmJira(ctx, root);
632
764
  });
633
765
  // pi forcing a threshold compaction while a flow is bound means our safe-point pacing missed — rebuild the
634
766
  // summary here with flow-aware instructions and hand it back through the event's custom-compaction channel.
@@ -912,8 +1044,17 @@ export default function devFlow(pi: ExtensionAPI) {
912
1044
  return full;
913
1045
  };
914
1046
 
915
- pi.on("before_agent_start", async (_event, ctx) => {
1047
+ pi.on("before_agent_start", async (event, ctx) => {
916
1048
  if (!guardsAreMine()) return undefined;
1049
+ // the operator answered in chat (not a relayed Jira answer): stop watching Jira — the conversation is here
1050
+ // now; the next question the agent closes on is mirrored and watched again
1051
+ const ev = event as { messageType?: string; prompt?: string };
1052
+ if (ev.messageType === "user" && !String(ev.prompt ?? "").startsWith("[Jira ") && jiraWatch.isArmed(sessionKey(ctx))) {
1053
+ const root = await flowRoot(ctx.cwd);
1054
+ const st = boundFeature(root, sessionKey(ctx));
1055
+ jiraWatch.cancel(sessionKey(ctx));
1056
+ if (st?.jira?.watch) disarmWatch(root, st.slug);
1057
+ }
917
1058
  hollowStreak.delete(sessionKey(ctx)); // a new prompt earns a fresh resume
918
1059
  // One [dev-flow] line per run, whatever number of copies of this package are installed. The same
919
1060
  // package can reach one runtime twice (a project pin beside the npm install) and pi dedupes
@@ -964,6 +1105,8 @@ export default function devFlow(pi: ExtensionAPI) {
964
1105
  if (ref) guidance.push(`Stage playbook: read ${path.join(SKILL_DIR, ref)} before gate work in this stage.`);
965
1106
  const prose = stageGuidance(cfg, state.stage);
966
1107
  if (prose) guidance.push(`Stage guidance (${prose.source}): ${prose.text}`);
1108
+ if (state.jira && cfg.jira)
1109
+ guidance.push(`Jira ${state.jira.key} is linked: your closing message is posted there when it asks something (${state.pendingAsk === "Approve?" ? "plan.md and the mockups are attached; " : ""}name screenshot paths to attach them). \`[Jira ${state.jira.key} · your comment]\` and \`[Jira ${state.jira.key} moved to …]\` messages are the operator's own answers; "information only" ones are not. Stage moves sync the issue's status.`);
967
1110
  guidance.push("Stage reports: open with the stage line the last gate returned, pasted as is; a checkpoint closes with `Done:` / `Next steps:` (see the ground rules).");
968
1111
  const pend = checklistPending(cfg, state, state.stage);
969
1112
  if (pend) guidance.push(`Tier-2 checklist NOT yet confirmed — ${openItemsNote(cfg, state, state.stage)}${state.stage === "release" ? " — release-stage items close with the operator's Finish? answer; no earlier gate records them" : ""}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.98.0",
3
+ "version": "0.99.0",
4
4
  "description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -55,6 +55,39 @@ knobs · merge-policy state.
55
55
  - Start warns when this session runs an older dev-flow build than the
56
56
  checkout (`/reload` before trusting gate output) and lists playbook gaps.
57
57
 
58
+ ### Jira (opt-in: a `flow-jira` block in project.md)
59
+
60
+ - **Turning it on: `flow jira init`.** It asks one thing at a time, and each
61
+ answer is a flag on the next call:
62
+ 1. `Jira login?` — the operator runs `/flow jira login` themselves. Never
63
+ ask for the token in chat.
64
+ 2. `Jira project?` → `--project=KEY`.
65
+ 3. `Issue types?` → `--types=A,B`.
66
+ 4. `Mapping OK?` — show the proposed status mapping. The operator can
67
+ change it with `--map=<Type>.<stage>=<Status>`. On their word,
68
+ re-run with `--confirmed`.
69
+ - **Starting from an issue.** When the operator names an issue key, run
70
+ `flow start --jira=KEY`. The slug comes from the issue unless you give
71
+ one. The issue's description seeds `plan/plan.md`. To link a flow that
72
+ is already running: `flow jira link KEY`.
73
+ - **No issue named at start?** The start output asks you to offer three
74
+ choices: create a new issue, link an existing one, or go without. To
75
+ create one: `flow jira create --summary="…" [--description="…"]
76
+ [--type=…]`. It previews and asks `Create Jira issue?`. On a yes, re-run
77
+ it with `--confirmed`, and the new issue is linked. Never create an issue
78
+ unasked; `--no-jira` on start skips the offer.
79
+ - **Roadmap items:** `flow jira create --roadmap=<n>[,<n>…]` makes one issue
80
+ per item and stamps the item with `[KEY]`. Picking that item and starting
81
+ it links its issue automatically.
82
+ - **Your closing message is posted to the issue** when it asks something,
83
+ with the plan and mockups attached at Approve?. Images you name by path
84
+ are attached too, so name screenshot files explicitly.
85
+ - **Answers that come back from Jira:**
86
+ - `[Jira KEY · your comment] …` and `[Jira KEY moved to … ] Approved` are
87
+ the operator's own answers. Treat them exactly like a chat reply.
88
+ - `… information only` lines are not answers.
89
+ - `flow jira check` reads the issue now. `flow jira status` shows the links.
90
+
58
91
  ### Modes
59
92
 
60
93
  - `normal` — a written plan (`plan/plan.md`) is required before Approve?.
package/src/core.ts CHANGED
@@ -70,6 +70,8 @@ export interface FlowState {
70
70
  /** reflection rows this flow set out to fix (`flow start --reflections=r3,r7`): finish closes each as fixed by
71
71
  * this flow, unless `flow reflect defer <id> "<why>"` left it open with a reason */
72
72
  reflections?: { id: number; body: string; deferred?: string }[];
73
+ /** the Jira issue this flow syncs with (`flow start --jira=KEY`, project.md flow-jira) */
74
+ jira?: JiraLink;
73
75
  verifiedHead?: string; // HEAD the operator's Verified? was given over — release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
74
76
  reflectedAt?: string; // a reflect worker reported for this flow — finish runs one first while this is unset (only --no-reflect --confirmed skips it)
75
77
  devPort?: number; // the port the operator chose for this flow's dev deploy when the default was held by another flow — finish stops it (devDown)
@@ -134,6 +136,48 @@ export interface Versioning {
134
136
  pattern: string;
135
137
  }
136
138
 
139
+ /** A dev-flow stage, plus `done` (the flow finished), as a Jira status mapping target. */
140
+ export type JiraStage = Stage | "done";
141
+
142
+ /** project.md ` ```flow-jira ` block (src/jira/config.ts) — the opt-in Jira sync; absent = off. */
143
+ export interface JiraConfig {
144
+ site: string; // acme.atlassian.net
145
+ cloudId?: string;
146
+ project: string; // project key
147
+ issueTypes: string[];
148
+ /** issue type → stage → status names (the first is where dev-flow moves the issue) */
149
+ status: Record<string, Partial<Record<JiraStage, string[]>>>;
150
+ /** which of the agent's closing messages become comments: asks (a question is pending) | all */
151
+ mirror: "asks" | "all";
152
+ /** seconds between reply checks after a question; the last repeats */
153
+ watch: number[];
154
+ /** seconds after the question when the watch gives up */
155
+ watchCap: number;
156
+ }
157
+
158
+ /** A flow's link to its Jira issue, in state.json. */
159
+ export interface JiraLink {
160
+ key: string;
161
+ type: string; // issue type name
162
+ site: string;
163
+ /** the token owner's account id — only their comments are answers */
164
+ accountId?: string;
165
+ /** ids of comments dev-flow posted (never read back as answers) */
166
+ posted: string[];
167
+ /** ISO time up to which comments have been read */
168
+ seenUntil?: string;
169
+ /** the newest comment id read (Jira ids grow; its comment times are minute-precision) */
170
+ seenCommentId?: string;
171
+ /** the issue's status as last seen (or last set by dev-flow) */
172
+ lastStatus?: string;
173
+ /** sha1 of files already attached, so a re-ask does not attach them again */
174
+ attached?: string[];
175
+ /** sha1 of the last closing message mirrored — the same message is never posted twice */
176
+ mirrored?: string;
177
+ /** the open question a watch is waiting on: armed when it was posted, `checks` made since */
178
+ watch?: { ask: string; since: string; checks: number };
179
+ }
180
+
137
181
  export interface Config {
138
182
  defaultBranch: string;
139
183
  branchPattern: string; // {slug} substituted
@@ -169,6 +213,8 @@ export interface Config {
169
213
  /** Lines from the ## global `flow-worker` block: every flow_stage brief carries them, so a worker can run the
170
214
  * project's checks (e.g. an export of a test password read from a gitignored file) — gh#201. */
171
215
  workerPreamble?: string[];
216
+ /** project.md flow-jira block — the opt-in Jira sync; unset = off */
217
+ jira?: JiraConfig;
172
218
  }
173
219
 
174
220
  export const DEFAULTS: Config = {
@@ -2605,6 +2651,35 @@ export function roadmapPick(text: string, n: number, slug: string): string | nul
2605
2651
  return editOpenRow(text, n, (l) => (l.trim().includes(`(${slug})`) ? l.trim() : `${l.trim()} (${slug})`));
2606
2652
  }
2607
2653
 
2654
+ /** The open item at row n with its brief, or null. */
2655
+ export function roadmapItemAt(text: string, n: number): { item: string; brief: string } | null {
2656
+ const lines = text.split("\n");
2657
+ let row = 0;
2658
+ for (let i = 0; i < lines.length; i++) {
2659
+ if (!isRoadmapRow(lines[i]) || ++row !== n) continue;
2660
+ if (!isOpenItem(lines[i])) return null;
2661
+ const brief: string[] = [];
2662
+ for (let j = i + 1; j < lines.length && isBriefLine(lines[j]); j++) brief.push(lines[j].replace(/^\s+> ?/, ""));
2663
+ return { item: lines[i].trim().slice(6), brief: brief.join("\n").trim() };
2664
+ }
2665
+ return null;
2666
+ }
2667
+
2668
+ /** The Jira key an item was stamped with (`[DEV-12]`), or null. */
2669
+ export const roadmapJiraKey = (item: string): string | null => item.match(/\[([A-Z][A-Z0-9_]*-\d+)\]/)?.[1] ?? null;
2670
+
2671
+ /** An item's text without its stamps — `(slug)` and `[KEY]` — e.g. for an issue summary. */
2672
+ export const roadmapItemTitle = (item: string): string =>
2673
+ item
2674
+ .replace(/\s*\[[A-Z][A-Z0-9_]*-\d+\]/g, "")
2675
+ .replace(/\s*\([a-z0-9-]+\)\s*$/, "")
2676
+ .trim();
2677
+
2678
+ /** Stamp the open item at row n with a Jira key `[KEY]`. Null when row n is no open item. */
2679
+ export function roadmapStampJira(text: string, n: number, key: string): string | null {
2680
+ return editOpenRow(text, n, (l) => (roadmapJiraKey(l) ? l.trim() : l.trim().replace(/^(- \[ \] )(.*?)(\s*\([a-z0-9-]+\))?$/, (_m, h, body, slug) => `${h}${body} [${key}]${slug ?? ""}`)));
2681
+ }
2682
+
2608
2683
  /** Check the open item at row n with a done stamp. Null when row n is no open item. */
2609
2684
  export function roadmapDone(text: string, n: number, stamp: string): string | null {
2610
2685
  return editOpenRow(text, n, (l) => stampItem(l, stamp));