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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,48 @@ 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
+
29
+ ## [0.98.0] - 2026-11-29
30
+
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.**
32
+
33
+ ### Changed
34
+ - **A `confirm` or `protect` rule never opens a dialog inside the agent's call** (fixes #289). The dialog held the call before the command ran, outside its own timeout: 2h53m, 14h43m and about 10 hours in three sessions while nobody was there, with nothing in the transcript to say why. A yes in it also never reached the agent, so one session asked the same question 12 times. Now the call is refused at once as `NEEDS-OPERATOR Run it?` with the rule's reason, and the agent asks you in chat. On your yes it re-runs the same command prefixed with `DEV_FLOW_CONFIRMED=1`, or repeats the same edit. The yes counts only once you have replied since the refusal, and only for that exact command or path. A worker is never granted one. Every rule a call trips is one question. A force push and a merge with no style flag are asked in chat the same way.
35
+
36
+ ### Added
37
+ - **`flow guard "<command>"` and `flow guard --path <file>`** name the playbook `flow-guard` rule a command or an edit would trip, through the same matcher the hooks use, and run nothing. A playbook no longer hand-imports `guardBash` from `src/core.ts` to test its own rules (gh#287).
38
+
39
+ ### Fixed
40
+ - **A release call you never named is shown to you before it counts.** When your Approve? answer names no kind (a bare "approve") and the agent passed `--version=<kind>` from its own proposal, the gate records it as the agent's proposal, says so, and shows it with Verified? to keep or change. Your answer there, or `flow bump <kind> --confirmed`, settles it. If a yolo skips Verified?, the pre-release hint says to ask the kind before cutting the release prep (gh#299).
41
+ - **A hand rebase no longer re-asks Release?** A rebase replays the verified commits under new ids, and the gate listed them as "landed after Verified?". It now compares diffs (`git patch-id`, with the changelog and version file left out): a replayed commit with the patch you verified rides under your Verified?, and a commit whose content changed still asks (gh#298).
42
+ - **Resuming a stopped publish no longer asks for a word already given.** The red-CI "publish stopped" message mentions "the operator's word" (for a real failure's way forward), and that wording re-armed the rule that refuses an unanswered `--confirmed`. After a flaky job was re-run green, the resume was refused and Release? asked again. A stopped or waiting publish now never counts as a question (gh#283).
43
+ - **Release? over changed code asks one question.** When code landed after Verified?, the Release? refusal now tells the agent to ask one thing: re-verify and ask Verified? if behaviour changed, since Release? then answers itself, or else ask Release? with the commits named. Asking Release? first and then re-verifying spent the answer (gh#288).
44
+ - **`flow_stage` with no `op` says what to pass.** It was refused with pi's bare `op: missing`. The schema now lets the call through, so the refusal names the field and the three ops (gh#286).
45
+ - **A worker brief gives its scratch dir as a real path.** It said `$TMPDIR`, which a worker's shell does not set, so `mkdir "$TMPDIR/x"` tried `/x`. The brief now names the feature's tmp dir and says the project playbook's scratch rule wins (gh#281).
46
+ - **A review worker no longer re-runs checks the driver already ran green.** A check that passed against the exact tree under review is marked green in the brief, with "do not re-run it". A read-only reviewer is no longer handed the health probe, since the driver owns the deploy (gh#285).
47
+ - **Empty feature folders are found and cleaned up.** A `.dev-flow/<slug>/` with no file anywhere inside was neither a feature nor a ghost, so nothing named it. `flow doctor` now lists it, and `flow init` removes it without asking once it is ten minutes old. A `plan/` with no file in it counts as empty, not as a ghost (gh#282).
48
+
7
49
  ## [0.97.0] - 2026-11-23
8
50
 
9
51
  **A standard flow asks two questions, Approve? and Verified?, and runs the rest to done. Release? answers itself over docs and test commits and a stale build. Finish files the closing reflection's own fold/drop recommendations and does release-stage items as work. Dev port? is asked only while another flow's deploy is under review.**
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/gates.md CHANGED
@@ -67,7 +67,9 @@ the question also asks: *patch, minor or major release, or merge unreleased?* Yo
67
67
  with `--version=<kind>` or `--no-version`; an Approve? answer without it is refused and nothing is
68
68
  kept. Only the kind of step is recorded, never a number: the number is counted from the newest tag
69
69
  when the release runs, so a flow that released first moves yours along instead of colliding with it.
70
- No later gate asks the call again. You can change it at any point until the tag is cut: say so,
70
+ No later gate asks the call again. When your Approve? answer names no kind (a bare "approve") and the
71
+ agent passed one anyway, the gate records it as the agent's proposal: the output says so, Verified?
72
+ shows it to you to keep or change, and your answer there settles it. You can change it at any point until the tag is cut: say so,
71
73
  and the agent runs `flow bump <patch|minor|major|none> --confirmed`, or passes
72
74
  `--version=<kind>` / `--no-version` on a confirmed `verify` or `release` call. A fold flow — one started with `--reflections`, as `flow reflect plan` prints it — is never asked the call: on a versioned project it always merges unreleased, and `--version=<kind>` or `flow bump <kind>` is refused. A flow approved by an
73
75
  older dev-flow, with no call on record, is asked at Verified? instead.
@@ -150,7 +152,9 @@ Proves the branch is ready to ship:
150
152
  **Release? usually answers itself** (`ask = on-change`, the default): your Verified? is the release
151
153
  word. That happens when your call is on record and only release prep (bump, changelog), docs
152
154
  (`docs/`, README, CHANGELOG) or tests changed since Verified?; the output names any docs/test commit
153
- that rode under it. A `--confirmed` given before the gate asked doesn't count where a question carries news you haven't
155
+ that rode under it. A hand rebase replays the verified commits under new ids: a commit whose diff
156
+ (changelog and version file left out) matches one you verified rides under your Verified? too, while
157
+ a commit whose content changed still asks. A `--confirmed` given before the gate asked doesn't count where a question carries news you haven't
154
158
  seen (commits after Verified? on a yolo flow, or a stale build): the gate asks first. A yolo held back
155
159
  only by `yolo = until-release` is asked like any flow, so your chat answer stands on the first call.
156
160
 
@@ -255,8 +259,11 @@ To drop an unreleased feature, use `flow abort` instead.
255
259
  manages `.dev-flow/roadmap.md`. `pick` stamps an item for `flow start <slug>`, and `finish` checks
256
260
  it off when the feature ships.
257
261
  - `flow doctor ["<note>"]` is a read-only health report: playbook drift, dead commands, ghost
258
- folders, orphan worktrees and branches, and a review of every open reflection. It writes nothing,
259
- so it's safe at any stage and in CI.
262
+ folders, empty feature folders, orphan worktrees and branches, and a review of every open
263
+ reflection. It writes nothing, so it's safe at any stage and in CI. `flow init` removes an empty
264
+ feature folder (no file anywhere inside) without asking, once it is ten minutes old.
265
+ - `flow guard "<command>"` / `flow guard --path <file>` names the playbook `flow-guard` rule a
266
+ command or an edit would trip, or says none does. It reads only.
260
267
 
261
268
  ## status, abort, help, version
262
269
 
@@ -52,10 +52,18 @@ playbook, dev-flow stays silent.
52
52
 
53
53
  **Your own rules.** The `deny` / `confirm` / `protect` / `forbid` rules in your playbook's
54
54
  `flow-guard` block run on every bash command and every edit, at every stage, before dev-flow's own
55
- checks. A block always shows the reason you wrote. See the [playbook](playbook.md).
56
-
57
- **Force pushes ask you.** `git push --force` / `-f` / `--force-with-lease` needs your OK. The
58
- refusal prints the prefix that marks it as approved: `DEV_FLOW_ALLOW_REWRITE=1`.
55
+ checks. A block always shows the reason you wrote. See the [playbook](playbook.md). To test a rule
56
+ before an agent meets it, `flow guard "<command>"` (or `flow guard --path <file>`) names the rule that
57
+ fires, with the same matcher the hooks use, and runs nothing.
58
+
59
+ **Rules that ask you never wait on a dialog.** A `confirm` or `protect` rule refuses the call at
60
+ once with your reason, and the agent asks you in chat. On your yes it re-runs the command prefixed
61
+ with `DEV_FLOW_CONFIRMED=1` (or repeats the edit). The prefix counts only after you replied, and only
62
+ for the command it was asked about. A dialog used to hold the call, outside its own timeout, for
63
+ hours while nobody was there, and a yes in it never reached the agent, so it asked again.
64
+
65
+ **Force pushes ask you.** `git push --force` / `-f` / `--force-with-lease` needs your OK, asked in
66
+ chat. The refusal prints the prefix that marks it as approved: `DEV_FLOW_ALLOW_REWRITE=1`.
59
67
 
60
68
  **Shell calls can't hang.** The model often omits a timeout, so a `gh` waiting on a prompt could
61
69
  freeze a session for hours. A shell call without a timeout gets a default for its kind:
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
@@ -141,12 +141,17 @@ forbid docker/secrets :: secret storage
141
141
  | Verb | Applies to | What happens |
142
142
  |---|---|---|
143
143
  | `deny` | a bash command (regex) | blocked |
144
- | `confirm` | a bash command (regex) | asks you; blocked when there's no UI to ask |
145
- | `protect` | an edit/write path | asks you; blocked when there's no UI |
144
+ | `confirm` | a bash command (regex) | refused with your reason; the agent asks you in chat, and on your yes re-runs it prefixed with `DEV_FLOW_CONFIRMED=1` |
145
+ | `protect` | an edit/write path | refused with your reason; the agent asks you in chat, and on your yes repeats the edit |
146
146
  | `forbid` | an edit/write path | blocked |
147
147
 
148
148
  Tips:
149
- - Text after ` :: ` is the reason, shown when the rule fires.
149
+ - Text after ` :: ` is the reason, shown when the rule fires. Name the safe form in it (`scope it with
150
+ --no-deps`): the agent reads it on every refusal, so it can use that form instead of asking you.
151
+ - A `confirm` or `protect` never opens a dialog. The yes counts only after you reply in chat, and it
152
+ covers that exact command or path. When a safe form always exists, prefer `deny` with the safe form
153
+ in the reason: the agent fixes the command itself and you are never asked.
154
+ - `flow guard "<command>"` or `flow guard --path <file>` shows which rule fires, without running anything.
150
155
  - `flow_stage` workers get these rules in their brief. A worker has no one to ask, so `confirm` and
151
156
  `protect` are refusals for it, and the reason you write is what it reads.
152
157
  - An invalid regex makes the playbook invalid, and `flow init` refuses it.
@@ -226,6 +231,8 @@ merge-strategy setting for that.
226
231
  | `mockupGlobs` | `*.png` | what counts as a mockup render for `--ui` |
227
232
  | `bashTimeout` | `inject` | `require`: refuse shell calls with no timeout, instead of adding one |
228
233
 
234
+ A ` ```flow-jira ` block under `## global` turns on the Jira sync. `flow jira init` writes it; see [jira.md](jira.md).
235
+
229
236
  ## flow init in detail
230
237
 
231
238
  - **Fresh repo:** prints the detection report and the questions. Writes nothing.
@@ -24,20 +24,26 @@ import path from "node:path";
24
24
  import { Type } from "typebox";
25
25
  import { compact, defineTool, isToolCallEventType, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
26
26
  import { type ExtensionAPI, type ToolCallEvent, type ToolCallEventResult, type TurnEndEvent, type TurnEndEventResult } from "@earendil-works/pi-coding-agent";
27
- import { ALLOW_REWRITE, applicableItems, openItemsNote, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, workerSteerAt, recoverReflectRows, assistantTexts, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, hollowStop, hollowStopNote, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, worktreeWorkGuard, flowArgsShapeError, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
27
+ import { ALLOW_REWRITE, OPERATOR_CONFIRMED, confirmedPrefix, guardConfirmVerdict, type GuardAsk, applicableItems, openItemsNote, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, workerSteerAt, recoverReflectRows, assistantTexts, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, hollowStop, hollowStopNote, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, worktreeWorkGuard, flowArgsShapeError, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
28
28
  import { loadProject } from "../src/projectmd.ts";
29
29
  import { bashTimeout, requireTimeout, timeoutClass } from "../src/timeouts.ts";
30
30
  import { AGENT_MARK, operatorCommandAsks, operatorCommandCorrection, viewHeader, askLine, type GateView } from "../src/present.ts";
31
31
  import { Text } from "@earendil-works/pi-tui";
32
32
  import { CONTEXT_EMITTED, COPIES, GATE_HELP, SELF_BUILD, SKILL_DIR, type Ui, WEB_CHIP_KEYS, LEGACY_CHIP_KEYS, nextChipKeys, baseSeams, bindings, boundFeature, claimBlocker, claimFile, compacting, compactionTakeover, coreInjected, coreStale, currentBranch, dfDir, featDir, featureRefs, flowCompactInstructions, flowRoot, guardsAreMine, initiated, lastContext, loadedVersion, maybeCompactNow, noteFriction, now, readClaim, readReflections, readReflectionsText, readRoadmap, readState, registerCopy, releaseSession, sessionKey, sh, skillCore, unfinishedStates, worktreeAbs, writeClaim, writeState } from "../src/runtime/base.ts";
33
- import { type Session, presentRun } from "../src/runtime/checks.ts";
33
+ import { type Session, presentRun, worktreeFingerprint } from "../src/runtime/checks.ts";
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 { grantCheck, grantRecord, isFriction, newGrantLedger, operatorMessageCount, type RefusalStreak } from "../src/runtime/grants.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";
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. */
@@ -86,12 +92,6 @@ function refreshStatus(ctx: ExtensionContext, root: string): void {
86
92
  }
87
93
 
88
94
 
89
- /** A project confirm rule with no operator present is a block — a hidden confirmation is not a confirmation. */
90
- async function askOperator(ctx: ExtensionContext, what: string, why: string): Promise<string | null> {
91
- if (!ctx.hasUI) return needsOperator(`${why}: this needs an operator confirmation and no UI is available — ask them, or run it yourself outside Pi`);
92
- const ok = await ctx.ui.confirm("dev-flow project rule", `${what}\n\n${why}\n\nProceed?`);
93
- return ok ? null : `operator declined — ${why}`;
94
- }
95
95
 
96
96
  /** What a kill by dev-flow's own timeout tells the agent (and the operator reading the transcript). */
97
97
  export function timeoutKillNote(armed: { s: number; cls: string }): string {
@@ -126,6 +126,7 @@ export default function devFlow(pi: ExtensionAPI) {
126
126
  key,
127
127
  slug: bindings.get(key) ?? null,
128
128
  operatorMessages: operatorMessageCount((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })()),
129
+ operatorText: lastOperatorText((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })()),
129
130
  bind: (slug) => {
130
131
  const prev = bindings.get(key);
131
132
  bindings.set(key, slug);
@@ -148,6 +149,22 @@ export default function devFlow(pi: ExtensionAPI) {
148
149
 
149
150
  /** Which gate asked for the operator's word, and when features started — per session (gh#190). */
150
151
  const grantLedger = newGrantLedger();
152
+ /** Per session: the last guard confirm refused, so the operator's answer can be matched to it (gh#289). */
153
+ const guardAsks = new Map<string, GuardAsk>();
154
+ /** A call that trips confirm rule(s): never a dialog — run on the operator's chat answer, else refuse with the reason. */
155
+ const askOperator = (ctx: ExtensionContext, key: string, o: { target: string; what: string; whys: string[]; prefixed: boolean; edit: boolean }): string | null => {
156
+ const users = (() => {
157
+ try {
158
+ return operatorMessageCount(ctx.sessionManager?.getBranch());
159
+ } catch {
160
+ return null;
161
+ }
162
+ })();
163
+ const v = guardConfirmVerdict({ ...o, users, prev: guardAsks.get(key), worker: isWorkerSession(ctx) });
164
+ if (v.allow) return null;
165
+ if (v.record) guardAsks.set(key, v.record);
166
+ return v.reason;
167
+ };
151
168
  /** Gates that refused in a row, per session — what turns a failing check into friction (see isFriction). */
152
169
  const refusalStreak: RefusalStreak = new Map();
153
170
 
@@ -210,12 +227,108 @@ export default function devFlow(pi: ExtensionAPI) {
210
227
  return `${core}\n\n`;
211
228
  };
212
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
+
213
322
  pi.registerCommand("flow", {
214
323
  description: `dev-flow gates: ${GATE_HELP}`,
215
324
  handler: async (args, ctx) => {
216
325
  const cmd = parse(args);
217
326
  const root = await flowRoot(ctx.cwd);
218
- 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) });
219
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.
220
333
  // bare reflect is the exception: its whole output is instructions for the agent — displayed without a turn, they would never execute.
221
334
  const wake = cmd.length === 1 && cmd[0] === "reflect";
@@ -247,7 +360,7 @@ export default function devFlow(pi: ExtensionAPI) {
247
360
  // gh#190: --confirmed stands for the operator's chat answer — refuse it when no operator message came after the question
248
361
  const users = operatorMessageCount((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })());
249
362
  const selfGrant = grantCheck(params.args, sessionKey(ctx), users, grantLedger);
250
- 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) });
251
364
  grantRecord(params.args, sessionKey(ctx), users, res, grantLedger);
252
365
  if (!res.isError) maybeCompactNow(ctx, root);
253
366
  // two readers: the model gets every instruction, the operator's row renders the view (renderResult) —
@@ -362,7 +475,14 @@ export default function devFlow(pi: ExtensionAPI) {
362
475
  defaultBranch: cfg.defaultBranch,
363
476
  commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
364
477
  status: await git("git status --short"),
365
- checks: st.docs ? [] : cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
478
+ checks: st.docs
479
+ ? []
480
+ : await (async () => {
481
+ // green only when proven against this tree: a record with no fingerprint is not proof (gh#285)
482
+ const fp = wop === "review" ? await worktreeFingerprint(work) : null;
483
+ return cfg.checkList.map((c) => ({ name: c.name, command: c.cmd, green: !!fp && !!st.checks[c.name]?.ok && st.checks[c.name]?.wt === fp }));
484
+ })(),
485
+ scratchDir: ((d) => (mkdirSync(d, { recursive: true }), d))(featureTmpDir(dfDir(root), st.slug)),
366
486
  preamble: cfg.workerPreamble,
367
487
  docs: !!st.docs,
368
488
  guard: cfg.guard,
@@ -555,7 +675,9 @@ export default function devFlow(pi: ExtensionAPI) {
555
675
  'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (the verdict is advisory; that a review ran is recorded — run it in implement once flow check is green: flow verify requires a review on record before it asks Verified?); op "reflect" (any stage; flow finish runs it itself before cleanup) — a fresh read-only reviewer of this session\'s transcript and every worker transcript that returns classified reflection findings (docs / code / plugin) with a fold-or-drop recommendation each, for the operator to decide. The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Delegate an implement slice when it is in the plan, provable by flow check, needs no operator input mid-slice and is big enough (≈4+ files or heavy reading) to crowd this context; small work, small fixes, mid-debug work, operator-judged work and final integration stay inline (criteria: references/implement.md). In pi-web the worker appears in the session\'s Agents menu as a subagent (running while it works, then its final status); the opened transcript holds its report.',
556
676
  promptSnippet: 'flow_stage(op: "implement"|"review"|"reflect", note, label?) — optional fresh-session worker for a big implement slice, an independent review, or a reflection (flow finish runs the closing one itself); gates stay with you; in pi-web workers show up as subagents in the Agents menu',
557
677
  parameters: Type.Object({
558
- op: Type.String({ description: '"implement" (a worker edits + commits a slice), "review" (read-only reviewer, findings + verdict) or "reflect" (read-only reviewer of the session transcripts, reflection findings + fold/drop recommendations)' }),
678
+ // required in practice, optional in the schema: a missing op then reaches workerOpError, which says what to
679
+ // pass, instead of pi's bare "op: missing" refusal (gh#286)
680
+ op: Type.Optional(Type.String({ description: 'Required. "implement" (a worker edits + commits a slice), "review" (read-only reviewer, findings + verdict) or "reflect" (read-only reviewer of the session transcripts, reflection findings + fold/drop recommendations)' })),
559
681
  note: Type.String({ description: "The slice: what to do and anything from this conversation the worker must know (operator answers, decisions). Facts (plan path, commits, checks) are added for you." }),
560
682
  label: Type.Optional(Type.String({ description: "A few words naming this delegation, shown in the worker's session name." })),
561
683
  budgetMin: Type.Optional(Type.Number({ description: "Wall-clock budget in minutes (5-180). Default 60 implement; 30 review, +10 per 500 changed lines past 500 (up to 90); 20 reflect, +5 per 250 KB of transcript past 250 KB (up to 60). Past it the worker is interrupted." })),
@@ -581,6 +703,21 @@ export default function devFlow(pi: ExtensionAPI) {
581
703
  const root = await flowRoot(ctx.cwd);
582
704
  rebuildSession(ctx, root);
583
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
+ }
584
721
  });
585
722
  pi.on("session_tree", async (_event, ctx) => {
586
723
  if (!guardsAreMine()) return;
@@ -592,6 +729,8 @@ export default function devFlow(pi: ExtensionAPI) {
592
729
  WEB_CHIP_KEYS.delete(sessionKey(ctx)); // the session's UI is gone; a long-lived server must not keep its slot
593
730
  hollowStreak.delete(sessionKey(ctx));
594
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;
595
734
  if (!guardsAreMine()) return;
596
735
  const root = await flowRoot(ctx.cwd);
597
736
  if (!existsSync(dfDir(root))) return;
@@ -608,7 +747,20 @@ export default function devFlow(pi: ExtensionAPI) {
608
747
  // Idle backstop: long between-gate runs compact here instead of letting pi hit the threshold mid-work.
609
748
  pi.on("agent_settled", async (_event, ctx) => {
610
749
  if (!guardsAreMine()) return;
611
- 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);
612
764
  });
613
765
  // pi forcing a threshold compaction while a flow is bound means our safe-point pacing missed — rebuild the
614
766
  // summary here with flow-aware instructions and hand it back through the event's custom-compaction channel.
@@ -730,7 +882,8 @@ export default function devFlow(pi: ExtensionAPI) {
730
882
  const pv = guardPath(abs, ctx.cwd, cfg.guard);
731
883
  if (pv.block) return { block: true, reason: pv.block };
732
884
  if (pv.confirm) {
733
- const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
885
+ const rel = path.relative(ctx.cwd, abs) || abs;
886
+ const why = askOperator(ctx, key, { target: `edit:${abs}`, what: `Editing ${rel}`, whys: [pv.confirm], prefixed: false, edit: true });
734
887
  if (why) return { block: true, reason: why };
735
888
  }
736
889
  // only an unbound session's main-checkout write ever reads it — ask git just then (gh#175)
@@ -748,8 +901,17 @@ export default function devFlow(pi: ExtensionAPI) {
748
901
  // and the operator's deny outranks dev-flow's own stage verdicts
749
902
  const gv = guardBash(command, cfg.guard);
750
903
  if (gv.block) return { block: true, reason: gv.block };
751
- for (const r of gv.confirms) {
752
- const why = await askOperator(ctx, command, r.why || `project rule ${r.pattern}`);
904
+ // the playbook's merge style is enforced where the decision is actually made: gh/glab merging the PR.
905
+ // An explicit contradiction is a hard block, a merge with no style flag (the forge default decides)
906
+ // is a confirmation. No policy in the playbook → no new verdicts at all.
907
+ const mv = mergeStyleInvocation(command, cfg.release.merge);
908
+ if (mv.block) return { block: true, reason: mv.block };
909
+ // every confirm this call trips is one question to the operator, not one per rule (gh#289)
910
+ const whys = [...gv.confirms.map((r) => r.why || `project rule ${r.pattern}`), ...(mv.confirm ? [mv.confirm] : [])];
911
+ if (whys.length) {
912
+ const cp = confirmedPrefix(command);
913
+ const short = cp.target.length > 160 ? `${cp.target.slice(0, 160)}…` : cp.target;
914
+ const why = askOperator(ctx, key, { target: cp.target, what: `\`${short}\``, whys, prefixed: cp.prefixed, edit: false });
753
915
  if (why) return { block: true, reason: why };
754
916
  }
755
917
  // `flow` in a shell is a 127 with no pointer, so the mistake repeated — name the call that works
@@ -758,19 +920,9 @@ export default function devFlow(pi: ExtensionAPI) {
758
920
  if (mustStateTimeout) return { block: true, reason: requireTimeout(command)! };
759
921
  // a forced push rewrites history CI and other sessions already have. dev-flow asks the operator
760
922
  // itself so a project never needs a blunt `--force` deny of its own (#82, #83)
761
- if (forcePushInvocation(command)) {
762
- const why = await askOperator(ctx, command, `a forced push rewrites a pushed branch — CI and other sessions lose these commits (with the operator's word, prefix the push with ${ALLOW_REWRITE})`);
763
- if (why) return { block: true, reason: why };
764
- }
765
- // the playbook's merge style is enforced where the decision is actually made: gh/glab merging the PR.
766
- // An explicit contradiction is a hard block, a merge with no style flag (the forge default decides)
767
- // is a confirmation. No policy in the playbook → no new verdicts at all.
768
- const mv = mergeStyleInvocation(command, cfg.release.merge);
769
- if (mv.block) return { block: true, reason: mv.block };
770
- if (mv.confirm) {
771
- const why = await askOperator(ctx, command, mv.confirm);
772
- if (why) return { block: true, reason: why };
773
- }
923
+ // no dialog here either (gh#289): the refusal names the prefix that carries the operator's word
924
+ if (forcePushInvocation(command))
925
+ return { block: true, reason: needsOperator("a forced push rewrites a pushed branch — CI and other sessions lose these commits", "Force-push?", `ask the operator in chat; on their yes, prefix the push with ${ALLOW_REWRITE}`) };
774
926
  // shipping on the forge (PR merge, release page) is release-stage work for a bound feature
775
927
  if (/\b(?:gh|glab)\b/.test(command)) {
776
928
  const ro = releaseOrderInvocation(command, boundFeature(guardRoot, key)?.stage ?? null);
@@ -892,8 +1044,17 @@ export default function devFlow(pi: ExtensionAPI) {
892
1044
  return full;
893
1045
  };
894
1046
 
895
- pi.on("before_agent_start", async (_event, ctx) => {
1047
+ pi.on("before_agent_start", async (event, ctx) => {
896
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
+ }
897
1058
  hollowStreak.delete(sessionKey(ctx)); // a new prompt earns a fresh resume
898
1059
  // One [dev-flow] line per run, whatever number of copies of this package are installed. The same
899
1060
  // package can reach one runtime twice (a project pin beside the npm install) and pi dedupes
@@ -944,6 +1105,8 @@ export default function devFlow(pi: ExtensionAPI) {
944
1105
  if (ref) guidance.push(`Stage playbook: read ${path.join(SKILL_DIR, ref)} before gate work in this stage.`);
945
1106
  const prose = stageGuidance(cfg, state.stage);
946
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.`);
947
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).");
948
1111
  const pend = checklistPending(cfg, state, state.stage);
949
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.97.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": [