pi-dev-flow 0.99.1 → 0.100.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,20 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.100.0] - 2026-12-03
8
+
9
+ **Flows on one machine no longer deploy over each other at verify.**
10
+
11
+ ### Fixed
12
+ - **Flows on one machine no longer deploy over each other at verify.** `flow verify` used to check who held the dev stack and record itself as the holder only after the build, deploy and health probe, minutes later. Two verifies in that gap both deployed to the same port, and each one's probe could catch the other's container. Now a verify holds a per-port lock from that check until its deploy is proven and recorded, and `flow status` shows the port as *deploying now*. A second verify goes alongside when `parallelDev = yes` and a second instance fits. Otherwise it waits for the first one to finish, up to `devLockWait` seconds (a new playbook key, default 900). Registry writes are locked too, so two flows recording themselves at once no longer drop an entry.
13
+
14
+ ## [0.99.2] - 2026-12-03
15
+
16
+ **The approved plan reaches the linked Jira issue in every case.**
17
+
18
+ ### Fixed
19
+ - **The approved plan now reaches the linked Jira issue in every case.** It used to go only with a mirrored Approve? question. That question is mirrored only when the agent closes its turn on it in a flow that is already linked. When an answer like "approve minor, yes to Jira" created the issue and approved in one go, the plan never got to the issue. Now every approval of a linked flow posts the plan, with `plan.md` and the mockups attached, unless the identical copy is already there. A flow linked after approval gets its plan posted when the link is made.
20
+
7
21
  ## [0.99.1] - 2026-12-03
8
22
 
9
23
  **Jira attachments work with the token the Atlassian MCP server needs.**
@@ -48,6 +48,13 @@ instance fits the measured RAM and disk. Otherwise verify doesn't deploy. Instea
48
48
  - **wait**.
49
49
 
50
50
  `--port` and `--replace` count as your answer, so the agent can only use them after you reply.
51
+
52
+ Only one verify at a time builds, deploys and probes on a port. Verify takes the port's lock
53
+ (`.dev-flow/dev-lock-<port>.json`) before it checks who holds the stack and keeps it until the deploy
54
+ is proven and recorded. Meanwhile `flow status` shows the port as **deploying now**. A second verify
55
+ that finds the lock taken goes alongside on the next free port when `parallelDev = yes` and a second
56
+ instance fits. Otherwise it waits for the first deploy to finish, for up to `devLockWait` seconds
57
+ (default 900), and then fails without building anything. A lock whose process has died is taken over.
51
58
  Finished and aborted flows hold no port. `flow finish` stops an extra-port instance with `devDown`.
52
59
  Playbook setup is in [playbook → Dev port](playbook.md#dev-port-and-parallel-flows).
53
60
 
package/docs/jira.md CHANGED
@@ -40,6 +40,7 @@ status.Story.done = Done
40
40
  - **No issue yet?** When you start a flow without naming an issue, the agent offers three choices: create a new issue in the synced project, link an existing one, or go without. The agent shows you the summary, type and description before anything is created (`flow jira create`), and links the new issue to the flow. Starting with `--no-jira` skips the offer.
41
41
  - **Issues for roadmap items.** Ask the agent to create issues for roadmap items (`flow jira create --roadmap=2,5`). You see the list first. Each item's text becomes the summary and its brief the description, and the item is stamped with its key (`- [ ] Dark mode [DEV-14]`). When that item is picked and started, the flow links to its issue automatically.
42
42
  - **Questions go to the issue.** When the agent stops to ask you something, its message is also posted as a comment. At **Approve?** it attaches `plan.md` and the mockups. Any screenshot the message names by path is attached as well. The same message is never posted twice, and the same file never uploaded twice.
43
+ - **The approved plan always reaches the issue.** When the plan is approved, dev-flow posts it to the issue with `plan.md` and the mockups attached. This covers approvals that never passed through a mirrored question: you approved in chat, or the issue was created or linked at the moment you approved. If the identical plan was already posted with the Approve? question, the approval comment just says so. A flow linked to an issue after approval gets its plan posted at link time.
43
44
  - **Answering in Jira:**
44
45
  - **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
46
  - **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.
package/docs/playbook.md CHANGED
@@ -98,6 +98,7 @@ Prefer feature flags for risky paths.
98
98
  | `seedData` | runs before the health probe |
99
99
  | `health` | the health probe. After a deploy, `verify` re-runs it and refuses if it fails. |
100
100
  | `healthWait` | seconds the probe keeps retrying, every 2s (default 30; `0` = try once) |
101
+ | `devLockWait` | seconds `verify` waits for another flow's deploy on the same port to finish (default 900) |
101
102
  | `servedBuild` | prints the commit the running app serves. `verify` checks it's this branch's HEAD. |
102
103
 
103
104
  The health probe runs in the worktree, so it can compare the app's build stamp with
@@ -120,7 +121,8 @@ servedBuild = curl -fsS http://127.0.0.1:$DEV_FLOW_PORT/version
120
121
 
121
122
  `$DEV_FLOW_SUFFIX` is empty on the default port and `-<slug>` on any other, so a second instance gets
122
123
  its own compose project. The deploy output shows what the variables resolved to.
123
- `flow finish` runs `devDown` for an instance on a non-default port. See
124
+ `flow finish` runs `devDown` for an instance on a non-default port. Two verifies never deploy on one
125
+ port at once: the second waits up to `devLockWait` seconds, or goes alongside when `parallelDev = yes`. See
124
126
  [concurrency](concurrency.md#sharing-one-dev-stack).
125
127
 
126
128
  ## Guard rules
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.99.1",
3
+ "version": "0.100.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": [
package/src/core.ts CHANGED
@@ -196,6 +196,8 @@ export interface Config {
196
196
  versioning: Versioning;
197
197
  /** Seconds the post-deploy health probe may keep retrying before the gate gives up (0 = single shot). */
198
198
  healthWait: number;
199
+ /** Seconds a verify waits for another flow's deploy on the same port to finish before it gives up (playbook `devLockWait`). */
200
+ devLockWait: number;
199
201
  /** The dev deploy's default port (playbook `port`). Unset: dev-flow cannot run a second instance, only name who holds the stack. */
200
202
  devPort?: number;
201
203
  /** Can two dev instances run side by side (playbook `parallelDev`)? undefined = the playbook does not say. */
@@ -230,6 +232,7 @@ export const DEFAULTS: Config = {
230
232
  prose: {},
231
233
  versioning: { pattern: "v{version}" },
232
234
  healthWait: 30,
235
+ devLockWait: 900,
233
236
  release: { review: "/flow-review", changelog: "CHANGELOG.md", releases: true },
234
237
  mainHook: true,
235
238
  bashTimeout: "inject",
@@ -322,6 +325,8 @@ export interface DevSlot {
322
325
  slug: string;
323
326
  head: string;
324
327
  at: string;
328
+ /** Set while the flow's verify builds and deploys it, under the port's lock (`.dev-flow/dev-lock-<key>.json`). */
329
+ deploying?: boolean;
325
330
  }
326
331
 
327
332
  /** What the clash question offers, from measured resources and the playbook's declared costs. */
package/src/projectmd.ts CHANGED
@@ -53,6 +53,7 @@ const KEYMAP: Record<string, Record<string, string>> = {
53
53
  health: "commands.health",
54
54
  dev: "commands.dev",
55
55
  healthWait: "healthWait", // seconds the post-deploy probe may keep retrying (#42)
56
+ devLockWait: "devLockWait", // seconds a verify waits for another flow's deploy on its port to finish
56
57
  port: "devPort", // the dev deploy's default port — exported to dev/health as $DEV_FLOW_PORT
57
58
  parallelDev: "parallelDev", // yes | no — can two dev instances run side by side?
58
59
  instanceMem: "instanceMem", // what one dev instance needs, e.g. 2G — the side-by-side check
@@ -349,6 +350,8 @@ function mergeInto(c: Config, r: Record<string, unknown>): void {
349
350
  // playbook values arrive as strings; a junk healthWait must not make the gate wait forever
350
351
  const wait = toSeconds(r.healthWait);
351
352
  if (wait !== undefined) c.healthWait = wait;
353
+ const lockWait = toSeconds(r.devLockWait);
354
+ if (lockWait !== undefined) c.devLockWait = lockWait;
352
355
  const port = toSeconds(r.devPort);
353
356
  if (port !== undefined && port > 0 && port < 65536) c.devPort = port;
354
357
  if (typeof r.parallelDev === "string") c.parallelDev = /^(yes|true)$/i.test(r.parallelDev) ? true : /^(no|false)$/i.test(r.parallelDev) ? false : undefined;
@@ -432,7 +435,7 @@ export function setPlaybookCheck(text: string, name: string, cmd: string): { tex
432
435
  /** Where each setup answer lives. `check.<name>` is a flow-check block; everything else a flow key. */
433
436
  const ANSWER_STAGE: Record<string, MdStage> = {
434
437
  defaultBranch: "global", forge: "global", worktreeDir: "global", branchPattern: "global", mainHook: "global", mockupGlobs: "global", bashTimeout: "global",
435
- setup: "implement", test: "implement", build: "implement", run: "implement", seedData: "implement", health: "implement", dev: "implement", healthWait: "implement",
438
+ setup: "implement", test: "implement", build: "implement", run: "implement", seedData: "implement", health: "implement", dev: "implement", healthWait: "implement", devLockWait: "implement",
436
439
  port: "implement", parallelDev: "implement", instanceMem: "implement", instanceDisk: "implement", devDown: "implement", servedBuild: "implement",
437
440
  versionFile: "pre-release", versionTag: "pre-release", changelog: "pre-release", review: "pre-release",
438
441
  releases: "release", artifact: "release", preflight: "release", merge: "release", yolo: "release", reflect: "release",
@@ -1,9 +1,9 @@
1
1
  /** dev-flow runtime — Dev deploy, health probes, tier-1 checks and branch facts. Moved out of extensions/dev-flow.ts as is (exports added). */
2
- import { existsSync, readFileSync, statfsSync } from "node:fs";
2
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, rmSync, statfsSync, statSync, writeSync } from "node:fs";
3
3
  import { createServer } from "node:net";
4
4
  import { freemem } from "node:os";
5
5
  import path from "node:path";
6
- import { skipsChecks, AGENT_MARK, checkFingerprint, DEFAULTS, failTail, freshenChecks, healthProbe, prepOnlyChange, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
6
+ import { skipsChecks, AGENT_MARK, checkFingerprint, DEFAULTS, failTail, freshenChecks, healthProbe, prepOnlyChange, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, pidAlive, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
7
7
  import { loadProject } from "../projectmd.ts";
8
8
  import { agentText, presentGate, type GateView, type StageFacts } from "../present.ts";
9
9
  import { atomicWrite, boundFeature, buildSkew, dfDir, featDir, featureEnv, sweepScratch, flagValue, gateCwd, initiated, mergeBase, now, originUrl, readState, runHealthProbe, sh, tail, worktreeAbs, writeState } from "./base.ts";
@@ -39,12 +39,10 @@ export async function releaseDevSlot(root: string, state: FlowState, cfg: Config
39
39
  note = down.ok ? ` dev instance on port ${state.devPort} stopped (${cfg.commands.devDown}).` : ` dev instance on port ${state.devPort} did NOT stop (${cfg.commands.devDown}) — stop it by hand:\n${tail(down.out)}\n`;
40
40
  } else note = ` dev instance on port ${state.devPort} is still running — the playbook has no devDown to stop it; stop it by hand.`;
41
41
  }
42
- const reg = readDevPorts(root);
43
- const mine = Object.keys(reg).filter((k) => reg[k].slug === state.slug);
44
- if (mine.length) {
45
- for (const k of mine) delete reg[k];
46
- writeDevPorts(root, reg);
47
- }
42
+ await updateDevPorts(root, (reg) => {
43
+ for (const k of Object.keys(reg)) if (reg[k].slug === state.slug) delete reg[k];
44
+ });
45
+ releaseDevLock(root, slotKey(devPortOf(state, cfg)), state.slug);
48
46
  return note;
49
47
  }
50
48
 
@@ -67,6 +65,163 @@ export function writeDevPorts(root: string, reg: Record<string, DevSlot>): void
67
65
  atomicWrite(devPortsFile(root), `${JSON.stringify(reg, null, "\t")}\n`);
68
66
  }
69
67
 
68
+ // ---------------------------------------------------------------- dev stack lock
69
+ // The registry says who deployed last; it cannot stop two verifies from deploying at once. A verify holds its
70
+ // port's lock from the holder check until the deploy is proven and recorded — minutes in which nobody else may
71
+ // build, recreate or probe that stack. The lock is a file created only if absent (O_EXCL), so taking it is one
72
+ // atomic step across sessions and processes.
73
+ export interface DevLock {
74
+ slug: string;
75
+ pid: number;
76
+ at: string;
77
+ }
78
+ /** A lock older than this is a leftover whose pid was reused, never a deploy still running. */
79
+ export const DEV_LOCK_MAX_MS = 3 * 60 * 60_000;
80
+ export const DEV_LOCK_POLL_MS = 2_000;
81
+ export const devLockFile = (root: string, key: string) => path.join(dfDir(root), `dev-lock-${key}.json`);
82
+
83
+ function readLockFile(file: string): DevLock | null {
84
+ try {
85
+ return JSON.parse(readFileSync(file, "utf8")) as DevLock;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ /** Whether a lock still guards a running verify: its process is alive and it is not impossibly old. */
92
+ export function lockLive(lock: DevLock | null, alive: (pid: number) => boolean = pidAlive): boolean {
93
+ if (!lock) return false;
94
+ const age = Date.now() - Date.parse(lock.at);
95
+ return alive(lock.pid) && Number.isFinite(age) && age < DEV_LOCK_MAX_MS;
96
+ }
97
+
98
+ /** Who holds the port's deploy lock right now — null when nobody (or only a dead leftover) does. */
99
+ export function devLockHolder(root: string, key: string): DevLock | null {
100
+ const lock = readLockFile(devLockFile(root, key));
101
+ return lockLive(lock) ? lock : null;
102
+ }
103
+
104
+ function createExclusive(file: string, text: string): boolean {
105
+ let fd: number;
106
+ try {
107
+ fd = openSync(file, "wx");
108
+ } catch (e) {
109
+ if ((e as NodeJS.ErrnoException).code === "EEXIST") return false;
110
+ throw e;
111
+ }
112
+ try {
113
+ writeSync(fd, text);
114
+ } finally {
115
+ closeSync(fd);
116
+ }
117
+ return true;
118
+ }
119
+
120
+ /** Take the port's deploy lock for a flow. A dead holder's lock, or one left by this same flow (a crashed
121
+ * earlier run — a live claim keeps two sessions off one flow), is broken and taken. */
122
+ export function tryDevLock(root: string, key: string, slug: string): { ok: true } | { ok: false; heldBy: DevLock } {
123
+ const file = devLockFile(root, key);
124
+ for (let attempt = 0; attempt < 2; attempt++) {
125
+ if (createExclusive(file, `${JSON.stringify({ slug, pid: process.pid, at: now() })}\n`)) return { ok: true };
126
+ const held = readLockFile(file);
127
+ // unreadable and fresh: another verify is between creating the file and writing it
128
+ if (!held && fileAgeMs(file) < 5_000) return { ok: false, heldBy: { slug: "another flow", pid: 0, at: now() } };
129
+ if (held && held.slug !== slug && lockLive(held)) return { ok: false, heldBy: held };
130
+ rmSync(file, { force: true });
131
+ }
132
+ return { ok: false, heldBy: readLockFile(file) ?? { slug: "another flow", pid: 0, at: now() } };
133
+ }
134
+
135
+ function fileAgeMs(file: string): number {
136
+ try {
137
+ return Date.now() - statSync(file).mtimeMs;
138
+ } catch {
139
+ return Number.POSITIVE_INFINITY;
140
+ }
141
+ }
142
+
143
+ /** Give the port's deploy lock back — only when this flow still holds it. */
144
+ export function releaseDevLock(root: string, key: string, slug: string): void {
145
+ const file = devLockFile(root, key);
146
+ if (readLockFile(file)?.slug === slug) rmSync(file, { force: true });
147
+ }
148
+
149
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
150
+
151
+ /** Change the registry under its own short lock: two flows recording themselves at once must not drop each
152
+ * other's entry (a bare read-modify-write did). */
153
+ export async function updateDevPorts(root: string, change: (reg: Record<string, DevSlot>) => void): Promise<void> {
154
+ const lock = `${devPortsFile(root)}.lock`;
155
+ const deadline = Date.now() + 5_000;
156
+ for (;;) {
157
+ if (createExclusive(lock, `${JSON.stringify({ slug: "registry", pid: process.pid, at: now() })}\n`)) break;
158
+ // the registry lock lives for milliseconds: a dead holder, an old file or a wait this long is a leftover
159
+ const held = readLockFile(lock);
160
+ const stale = held ? !pidAlive(held.pid) || Date.now() - Date.parse(held.at) > 10_000 : fileAgeMs(lock) > 1_000;
161
+ if (stale || Date.now() > deadline) rmSync(lock, { force: true });
162
+ else await sleep(20);
163
+ }
164
+ try {
165
+ const reg = readDevPorts(root);
166
+ change(reg);
167
+ writeDevPorts(root, reg);
168
+ } finally {
169
+ rmSync(lock, { force: true });
170
+ }
171
+ }
172
+
173
+ /** Take the deploy lock for the port this flow's verify will use, waiting up to `devLockWait` for another
174
+ * flow's deploy there to finish — or, with `parallelDev = yes` and room for a second instance, moving to the
175
+ * next free port instead of waiting. Returns the lock's key, or the gate's failure when the wait ran out. */
176
+ export async function acquireDevLock(o: GateCtx, state: FlowState, pollMs = DEV_LOCK_POLL_MS): Promise<{ key: string; note: string } | RunResult> {
177
+ const { root, cfg, flag } = o;
178
+ const start = Date.now();
179
+ let waitedFor: string | null = null;
180
+ let moved: string | null = null;
181
+ for (;;) {
182
+ const port = devPortOf(state, cfg);
183
+ const key = slotKey(port);
184
+ const got = tryDevLock(root, key, state.slug);
185
+ if (got.ok) {
186
+ const waited = waitedFor ? `dev: waited ${Math.round((Date.now() - start) / 1000)}s for ${waitedFor}'s deploy on ${portLabel(port)} to finish` : "";
187
+ return { key, note: [moved, waited].filter(Boolean).join("; ") };
188
+ }
189
+ // mid-deploy elsewhere: run alongside when the playbook allows and a second instance fits — never with
190
+ // --port (the operator named the port) or --replace (the operator wants this stack)
191
+ if (port !== undefined && cfg.parallelDev === true && !flag("replace") && flagValue(o.rest, "port") === null) {
192
+ const nextPort = await nextFreePort(port, takenPorts(root));
193
+ const side = sideBySide({ cfg, nextPort, memAvail: memAvailable(), diskFree: diskFreeAt(root) });
194
+ if (side.ok && nextPort !== null) {
195
+ state.devPort = nextPort;
196
+ writeState(root, state);
197
+ moved = `dev: ${got.heldBy.slug} is deploying on ${portLabel(port)} — deployed alongside on port ${nextPort} (parallelDev = yes)`;
198
+ continue;
199
+ }
200
+ }
201
+ if (Date.now() - start >= cfg.devLockWait * 1000)
202
+ return {
203
+ text: `verify gate FAILED:\n- ${got.heldBy.slug} has been deploying on ${portLabel(port)} (started ${ago(got.heldBy.at)}) and is still at it after ${cfg.devLockWait}s (devLockWait) — nothing of this flow was built or deployed. Rerun flow verify once it is done (flow status shows it), or ask the operator about another port (flow verify --port=<n>).`,
204
+ isError: true,
205
+ };
206
+ waitedFor = got.heldBy.slug;
207
+ await sleep(pollMs);
208
+ }
209
+ }
210
+
211
+ /** Ports in use by a recorded deploy or held by a running one — never offered as the side-by-side port. */
212
+ export function takenPorts(root: string): Set<number> {
213
+ const keys = Object.keys(readDevPorts(root));
214
+ try {
215
+ for (const f of readdirSync(dfDir(root))) {
216
+ const m = f.match(/^dev-lock-(\d+)\.json$/);
217
+ if (m && devLockHolder(root, m[1])) keys.push(m[1]);
218
+ }
219
+ } catch {
220
+ /* no .dev-flow yet */
221
+ }
222
+ return new Set(keys.map(Number).filter(Number.isFinite));
223
+ }
224
+
70
225
  export function portFree(port: number): Promise<boolean> {
71
226
  return new Promise((resolve) => {
72
227
  const srv = createServer();
@@ -135,7 +290,7 @@ export async function devSlotCheck(o: GateCtx, state: FlowState): Promise<RunRes
135
290
  // of the deploy — the holder's own verify redeploys before it asks again.
136
291
  if (!other || other.pendingAsk !== "Verified?")
137
292
  return { note: `dev: replaced ${slot.slug}'s deploy on ${portLabel(port)} — ${other ? `it is at ${other.stage}, not waiting on its Verified?` : "that flow is gone"}, so nobody was reviewing it` };
138
- const taken = new Set(Object.keys(reg).map(Number).filter(Number.isFinite));
293
+ const taken = takenPorts(root);
139
294
  const nextPort = port !== undefined ? await nextFreePort(port, taken) : null;
140
295
  const mem = memAvailable();
141
296
  const disk = diskFreeAt(root);
@@ -8,7 +8,7 @@ import { namesReleaseCall } from "./grants.ts";
8
8
  import { detectProject } from "../detect.ts";
9
9
  import { AGENT_MARK } from "../present.ts";
10
10
  import { GATE_HELP, SELF_BUILD, refreshDocsCode, type Ui, manifestAt, recordReleaseCall, buildSkew, copyWarning, currentBranch, dfDir, featDir, featureEnv, flagValue, gateCwd, gitConsistency, initiated, loadedVersion, mergeHistoryEvidence, needState, now, originUrl, publishedVersion, readClaim, readReflections, readReflectionsText, readRoadmap, readState, roadmapFile, sh, stateFile, tail, unfinishedStates, writePlaybookMergePolicy, writeState } from "./base.ts";
11
- import { type RunResult, type Session, ago, behindNote, releaseDevSlot, pendingChecks, probeHealth, readDevPorts, runChecks, stampChecks, triedNote } from "./checks.ts";
11
+ import { type RunResult, type Session, ago, behindNote, devLockHolder, releaseDevSlot, pendingChecks, probeHealth, readDevPorts, runChecks, stampChecks, triedNote } from "./checks.ts";
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";
@@ -641,7 +641,10 @@ export async function gateStatus(o: GateCtx): Promise<RunResult> {
641
641
  ];
642
642
  });
643
643
  // who holds the dev stack: the one thing two parallel flows on one machine must not guess
644
- for (const [k, v] of Object.entries(readDevPorts(root))) lines.push(`dev ${k === "default" ? "stack" : `port ${k}`} → ${v.slug} @ ${v.head.slice(0, 7)}, deployed ${ago(v.at)}`);
644
+ for (const [k, v] of Object.entries(readDevPorts(root))) {
645
+ const busy = v.deploying && devLockHolder(root, k)?.slug === v.slug;
646
+ lines.push(`dev ${k === "default" ? "stack" : `port ${k}`} → ${v.slug} @ ${v.head.slice(0, 7)}, ${busy ? `deploying now (started ${ago(v.at)})` : `deployed ${ago(v.at)}`}`);
647
+ }
645
648
  if (warn.length) lines.push(...warn);
646
649
  // which identity this session's state is keyed by: a claim fight is undiagnosable when the key
647
650
  // could be a session id or a shared directory and the output does not say which
@@ -205,6 +205,11 @@ export async function linkFlow(root: string, cfg: Config, slug: string, key: str
205
205
  writeState(root, { ...state, jira: link });
206
206
  const moved = await moveToStage(root, cfg, slug, state.stage);
207
207
  if (moved) lines.push(moved);
208
+ // linked after the plan was approved: the issue gets the plan it would have seen at Approve?
209
+ if (state.stage !== "plan") {
210
+ const posted = await postApprovedPlan(root, cfg, slug);
211
+ if (posted) lines.push(posted);
212
+ }
208
213
  return { lines };
209
214
  }
210
215
 
@@ -250,6 +255,10 @@ export async function syncStageMoves(root: string, cfg: Config, before: Map<stri
250
255
  if (!stage) continue;
251
256
  const line = await moveToStage(root, cfg, slug, stage, st?.jira ?? b.link);
252
257
  if (line) out.push(line);
258
+ if (st && b.stage === "plan" && stage === "implement") {
259
+ const posted = await postApprovedPlan(root, cfg, slug);
260
+ if (posted) out.push(posted);
261
+ }
253
262
  if (!st) {
254
263
  const c = jiraClient(cfg.jira);
255
264
  if (!("error" in c)) await c.client.comment(b.link.key, formatComment({ slug, text: `dev-flow feature \`${slug}\` finished.` }));
@@ -258,6 +267,48 @@ export async function syncStageMoves(root: string, cfg: Config, before: Map<stri
258
267
  return out;
259
268
  }
260
269
 
270
+ /** The approved plan on the issue, however the approval came: the Approve? question is mirrored only when the
271
+ * agent closes its turn on it in a linked flow, and an approval given in chat — or a link made at approval
272
+ * time — never reaches that point. Attaches plan.md and the mockups not already attached; the comment carries
273
+ * the plan itself unless an unchanged copy is already on the issue. Returns a gate-output line. */
274
+ export async function postApprovedPlan(root: string, cfg: Config, slug: string): Promise<string | null> {
275
+ const st = readState(root, slug);
276
+ if (!cfg.jira || !st?.jira) return null;
277
+ const planMd = path.join(featDir(root, slug), "plan", "plan.md");
278
+ if (!existsSync(planMd)) return null; // patch/docs: no plan document
279
+ const c = jiraClient(cfg.jira);
280
+ if ("error" in c) return `${AGENT_MARK}jira: the approved plan was not posted to ${st.jira.key} — ${c.error}`;
281
+ const link = st.jira;
282
+ const plan = readFileSync(planMd, "utf8");
283
+ const hashes = new Set(link.attached ?? []);
284
+ const already = hashes.has(sha1(plan)); // the Approve? mirror attached this very plan
285
+ const mock = path.join(featDir(root, slug), "plan", "mockups");
286
+ const files = [planMd, ...(existsSync(mock) ? readdirSync(mock).filter((f) => /\.(png|jpe?g|gif|webp)$/i.test(f)).map((f) => path.join(mock, f)) : [])];
287
+ const attached: string[] = [];
288
+ const failed: string[] = [];
289
+ for (const f of files) {
290
+ const h = sha1(readFileSync(f));
291
+ if (hashes.has(h)) continue;
292
+ const r = await c.client.upload(link.key, f);
293
+ if (r.ok) {
294
+ attached.push(path.basename(f));
295
+ hashes.add(h);
296
+ } else failed.push(`${path.basename(f)} (${r.error})`);
297
+ }
298
+ const call = st.versionChoice ? ` Release call: ${st.versionChoice}.` : "";
299
+ const mode = st.patch ? " (patch)" : st.docs ? " (docs)" : "";
300
+ const body = already
301
+ ? `Plan approved${mode} — the copy posted with the question is the one approved.${call}`
302
+ : `**Plan approved${mode}** — implementation starts.${call}\n\n${plan.length > 24_000 ? `_(the plan is long — see the attached plan.md)_` : plan.trim()}`;
303
+ const r = await c.client.comment(link.key, formatComment({ slug, text: body, attachments: attached }));
304
+ const fresh = readState(root, slug) ?? st;
305
+ const next: JiraLink = { ...(fresh.jira ?? link), attached: [...hashes] };
306
+ if (r.ok && r.value) next.posted = [...next.posted, r.value];
307
+ writeState(root, { ...fresh, jira: next });
308
+ if (!r.ok) return `${AGENT_MARK}jira: the approved plan was not posted to ${link.key}: ${r.error}`;
309
+ return `Jira ${link.key}: approved plan posted${attached.length ? ` with ${attached.join(", ")}` : ""}${failed.length ? ` (not attached: ${failed.join("; ")})` : ""}`;
310
+ }
311
+
261
312
  // ---------------------------------------------------------------- outbound: the closing-message mirror
262
313
 
263
314
  const IMG = /(?:^|[\s(`'"[])((?:\.{0,2}\/|\/)?[\w@.\-/]+\.(?:png|jpe?g|gif|webp))(?=$|[\s)`'",\]:;])/gi;
@@ -5,7 +5,7 @@ import { foldCallError, nonBehaviourPath, skipsChecks, applicableItems, changelo
5
5
  import type { Config, FlowState } from "../core.ts";
6
6
  import { AGENT_MARK } from "../present.ts";
7
7
  import { manifestAt, recordReleaseCall, refreshDocsCode, buildSkew, copyWarning, currentBranch, featDir, flagValue, forgeMergeStyle, forgeOf, gateCwd, mergeBase, needState, now, originUrl, readReflectionsText, readRoadmap, readState, releaseTags, roadmapFile, sh, tail, worktreeAbs, writeState } from "./base.ts";
8
- import { type RunResult, ago, releaseDevSlot, keepThroughPrep, branchState, catchUp, describeBranchState, devEnv, devPortOf, devSlotCheck, healthRerunsAfterDeploy, pendingChecks, probeHealth, readDevPorts, runChecks, slotKey, triedNote, unreleasedOnMain, worktreeFingerprint, writeDevPorts } from "./checks.ts";
8
+ import { type RunResult, acquireDevLock, ago, releaseDevLock, releaseDevSlot, updateDevPorts, keepThroughPrep, branchState, catchUp, describeBranchState, devEnv, devPortOf, devSlotCheck, healthRerunsAfterDeploy, pendingChecks, probeHealth, readDevPorts, runChecks, slotKey, triedNote, unreleasedOnMain, worktreeFingerprint } from "./checks.ts";
9
9
  import { type GateCtx, markPendingAsk } from "./gates.ts";
10
10
  import { applyReflectFindings, closeLinkedReflections } from "./reflect.ts";
11
11
  import { gatePublishes, prBodyOwed, publishRelease } from "./publish.ts";
@@ -20,7 +20,35 @@ function versionQuestion(root: string, state: FlowState, cfg: Config): { ask: st
20
20
  return releaseCallQuestion(manifestAt(gateCwd(root, state), cfg.versioning.file), cfg.versioning.file, state.docs);
21
21
  }
22
22
 
23
+ /** The port lock a verify holds while it deploys, and whose registry entry it marked `deploying`. */
24
+ interface DevHold {
25
+ key?: string;
26
+ slug?: string;
27
+ }
28
+
29
+ /** Let go of the dev stack a verify reserved: clear its `deploying` mark (a failed deploy stays recorded as
30
+ * this flow's, replaceable like any deploy nobody is reviewing) and give the port lock back. Idempotent. */
31
+ async function settleDevHold(root: string, hold: DevHold): Promise<void> {
32
+ const slug = hold.slug;
33
+ if (!slug) return;
34
+ await updateDevPorts(root, (reg) => {
35
+ for (const v of Object.values(reg)) if (v.slug === slug) delete v.deploying;
36
+ });
37
+ if (hold.key !== undefined) releaseDevLock(root, hold.key, slug);
38
+ delete hold.key;
39
+ delete hold.slug;
40
+ }
41
+
23
42
  export async function gateVerify(o: GateCtx): Promise<RunResult> {
43
+ const hold: DevHold = {};
44
+ try {
45
+ return await verifyRun(o, hold);
46
+ } finally {
47
+ await settleDevHold(o.root, hold);
48
+ }
49
+ }
50
+
51
+ async function verifyRun(o: GateCtx, hold: DevHold): Promise<RunResult> {
24
52
  const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
25
53
  const { state, err } = needState(root, sess, slugArg);
26
54
  if (err) return err;
@@ -58,13 +86,32 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
58
86
  if (owed) return { text: `verify gate FAILED:\n- the review comes before Verified?, so the operator's word covers the reviewed tree and review fixes never re-ask it — ${owed}\n${branchLine}`, isError: true };
59
87
  }
60
88
  // a stack another flow is reviewing or releasing on is not this gate's to take — ask before deploying
61
- const slotted = cfg.commands.dev && !state!.docs ? await devSlotCheck(o, state!) : { note: "" };
62
- if ("text" in slotted) return slotted;
89
+ // two verifies on one machine must not build and deploy the same stack at once: hold the port's lock from
90
+ // this check until the deploy is proven and recorded (the holder check and the record were minutes apart)
91
+ const locked: string[] = [];
92
+ let slotNote = "";
93
+ if (cfg.commands.dev && !state!.docs) {
94
+ for (;;) {
95
+ const got = await acquireDevLock(o, state!);
96
+ if ("text" in got) return got;
97
+ hold.key = got.key;
98
+ hold.slug = state!.slug;
99
+ if (got.note) locked.push(got.note);
100
+ const slotted = await devSlotCheck(o, state!);
101
+ if ("text" in slotted) return slotted;
102
+ if (slotted.note) slotNote = slotted.note; // a recheck on the port it moved to finds it free: keep why it moved
103
+ // the check moved this flow (--port, or alongside a deploy under review): lock that port instead
104
+ if (slotKey(devPortOf(state!, cfg)) === got.key) break;
105
+ releaseDevLock(root, got.key, state!.slug);
106
+ delete hold.key;
107
+ }
108
+ }
63
109
  // commands that take minutes and touch live services must say so (#38): a terse gate let the
64
110
  // agent tell the operator the dev deploy had never run, right after it recreated a container.
65
111
  const did: string[] = [];
66
112
  if (caught.note) did.push(caught.note);
67
- if (slotted.note) did.push(slotted.note);
113
+ did.push(...locked);
114
+ if (slotNote) did.push(slotNote);
68
115
  if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
69
116
  if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
70
117
  // The operator's answer arrives over the deploy `flow verify` just put up for them. When the tree is the
@@ -103,6 +150,11 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
103
150
  // deploy to dev before asking — the operator reviews the running dev app, not a promise
104
151
  const probe = healthProbe(cfg);
105
152
  if (cfg.commands.dev) {
153
+ // reserve the stack in the registry now: flow status names who is deploying, not who deployed last
154
+ const headNow = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
155
+ await updateDevPorts(root, (reg) => {
156
+ reg[slotKey(devPortOf(state!, cfg))] = { slug: state!.slug, head: headNow, at: now(), deploying: true };
157
+ });
106
158
  const env = devEnv(root, state!, cfg);
107
159
  const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, env);
108
160
  state!.checks.dev = { ok: res.ok, at: now() };
@@ -144,8 +196,12 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
144
196
  }
145
197
  if (!state!.docs && cfg.commands.dev && !standing) {
146
198
  const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
147
- writeDevPorts(root, { ...readDevPorts(root), [slotKey(devPortOf(state!, cfg))]: { slug: state!.slug, head, at: now() } });
199
+ await updateDevPorts(root, (reg) => {
200
+ reg[slotKey(devPortOf(state!, cfg))] = { slug: state!.slug, head, at: now() };
201
+ });
148
202
  }
203
+ // proven and recorded: the next verify may look at this stack (and ask before replacing it)
204
+ await settleDevHold(root, hold);
149
205
  const ran = [branchLine, ...did].join("; ");
150
206
  // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones.
151
207
  // A re-verify at pre-release (gh#187) exists to put the new tree in front of the operator: a yolo given