pi-dev-flow 0.99.2 → 0.100.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.1] - 2026-12-04
8
+
9
+ **Jira sync works with a scoped API token.**
10
+
11
+ ### Fixed
12
+ - **Jira sync works with a scoped API token.** dev-flow sent the token to Atlassian's MCP server as Basic `email:token`. With a scoped token, which is the kind the setup asks for, the server accepted the connection but saw no site, so every call failed with *Cloud id … isn't explicitly granted by the user*. That broke `flow jira init`, linking and creating issues, status moves, mirrored questions and the reply watch. It also broke the `atlassian` tools given to the agent. dev-flow now sends the token as `Bearer`. It keeps Basic as a fallback for a plain token, using whichever one can see the site. The scheme that worked is saved with the login. Jira REST calls still use Basic.
13
+
14
+ ## [0.100.0] - 2026-12-03
15
+
16
+ **Flows on one machine no longer deploy over each other at verify.**
17
+
18
+ ### Fixed
19
+ - **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.
20
+
7
21
  ## [0.99.2] - 2026-12-03
8
22
 
9
23
  **The approved plan reaches the linked Jira issue in every case.**
@@ -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
@@ -6,8 +6,8 @@ It talks to Atlassian's official **Rovo MCP server** (`https://mcp.atlassian.com
6
6
 
7
7
  ## Setup
8
8
 
9
- 1. **Create a scoped API token for the Atlassian MCP app** at id.atlassian.com → Security → API tokens → *Create API token with scopes*. Give it `read:jira:agent-interface` and `write:jira:agent-interface`; `search:jira:agent-interface` is optional. An org admin must have turned on API-token authentication for the Rovo MCP server (Atlassian Administration → Rovo MCP server). A plain token (*Create API token*) does not work: with one, the MCP server offers only its search tool.
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.
9
+ 1. **Create a scoped API token for the Atlassian MCP app** at id.atlassian.com → Security → API tokens → *Create API token with scopes*. Give it `read:jira:agent-interface` and `write:jira:agent-interface`; `search:jira:agent-interface` is optional. An org admin must have turned on API-token authentication for the Rovo MCP server (Atlassian Administration → Rovo MCP server). A plain token (*Create API token*) does not work: with one, the MCP server offers only its search tool. dev-flow sends a scoped token as `Authorization: Bearer <token>`. A scoped token sent as Basic `email:token` gets through the handshake, but every call fails with *Cloud id … isn't explicitly granted*.
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`. Login also records which auth scheme worked (`auth = bearer` or `basic`), so later sessions skip the check. You can use environment variables instead: `JIRA_SITE`, `JIRA_EMAIL` and `JIRA_API_TOKEN` override the file, and `JIRA_AUTH=bearer|basic` pins the scheme.
11
11
  3. **Ask the agent to set up Jira sync.** It runs `flow jira init`, which asks you one question at a time:
12
12
  - **Jira project?** Which project this repo syncs with.
13
13
  - **Issue types?** The types a flow may start from, such as Story or Bug.
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
@@ -36,7 +36,7 @@ import { foldView, pluginUpstream } from "../src/runtime/reflect.ts";
36
36
  import { type FlowHooks, runFlow } from "../src/runtime/gates.ts";
37
37
  import { JiraWatch } from "../src/runtime/jira-watch.ts";
38
38
  import { mirrorClosingMessage, disarmWatch, jiraSeams, resetJiraClients } from "../src/runtime/jira.ts";
39
- import { basicAuth, loadCreds, normSite, saveCreds } from "../src/jira/creds.ts";
39
+ import { loadCreds, mcpAuth, normSite, saveAuth, saveCreds } from "../src/jira/creds.ts";
40
40
  import { JiraClient, MCP_URL } from "../src/jira/client.ts";
41
41
  import type { Relay } from "../src/jira/sync.ts";
42
42
  import { grantCheck, grantRecord, isFriction, lastOperatorText, newGrantLedger, operatorMessageCount, type RefusalStreak } from "../src/runtime/grants.ts";
@@ -288,13 +288,24 @@ export default function devFlow(pi: ExtensionAPI) {
288
288
  return "";
289
289
  };
290
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;
291
+ * project — the issue, its links, its history. A server of the same name in mcp.json wins. With no stored
292
+ * auth scheme the token is probed first (Bearer, then Basic) and the one that works is remembered. */
293
+ const registerAtlassianMcp = async (cfg: ReturnType<typeof loadProject>["cfg"]) => {
294
+ if (!cfg.jira || !pi.registerMcpServer) return;
294
295
  const creds = loadCreds(cfg.jira.site, jiraSeams.env ?? process.env, jiraSeams.credsFile);
295
296
  if (!creds) return;
297
+ let scheme = creds.auth;
298
+ if (!scheme) {
299
+ try {
300
+ const picked = await new JiraClient(creds, { fetch: jiraSeams.fetch }).authScheme();
301
+ scheme = picked.scheme;
302
+ if (picked.verified && creds.source === "file") saveAuth(creds, scheme, jiraSeams.credsFile);
303
+ } catch {
304
+ scheme = "bearer"; // unreachable now: the scoped token's scheme
305
+ }
306
+ }
296
307
  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})` });
308
+ pi.registerMcpServer("atlassian", { url: MCP_URL, headers: { Authorization: mcpAuth(creds, scheme) }, exposure: "deferred", description: `Atlassian Jira/Confluence on ${creds.site} (dev-flow Jira sync: project ${cfg.jira.project})` });
298
309
  } catch {
299
310
  /* another extension owns the name, or no MCP support: the sync itself does not need it */
300
311
  }
@@ -313,9 +324,10 @@ export default function devFlow(pi: ExtensionAPI) {
313
324
  const probe = new JiraClient({ site: normSite(site), email: email.trim(), token: token.trim(), source: "file" }, { fetch: jiraSeams.fetch });
314
325
  const me = await probe.me();
315
326
  if (!me.ok) return `not saved — the Atlassian MCP server refused the token: ${me.error}`;
316
- saveCreds(site, email, token, jiraSeams.credsFile);
327
+ const auth = await probe.authScheme();
328
+ saveCreds(site, email, token, jiraSeams.credsFile, auth.verified ? auth.scheme : undefined);
317
329
  resetJiraClients();
318
- if (cfg) registerAtlassianMcp(cfg);
330
+ if (cfg) await registerAtlassianMcp(cfg);
319
331
  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
332
  };
321
333
 
@@ -707,7 +719,7 @@ export default function devFlow(pi: ExtensionAPI) {
707
719
  if (!initiated(root)) return;
708
720
  const cfg = loadProject(dfDir(root)).cfg;
709
721
  if (!cfg.jira) return;
710
- registerAtlassianMcp(cfg);
722
+ void registerAtlassianMcp(cfg);
711
723
  // a question asked before this session (or before a restart) is caught up now, then watched again
712
724
  const st = boundFeature(root, sessionKey(ctx));
713
725
  if (st?.jira?.watch && !isWorkerSession(ctx)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.99.2",
3
+ "version": "0.100.1",
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. */
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { readFileSync } from "node:fs";
13
13
  import path from "node:path";
14
- import { basicAuth, type JiraCreds } from "./creds.ts";
14
+ import { basicAuth, type JiraAuth, type JiraCreds, mcpAuth } from "./creds.ts";
15
15
  import { type FetchLike, McpClient, type McpTool, resultText, resultValue } from "./mcp.ts";
16
16
  import type { StatusInfo } from "./config.ts";
17
17
 
@@ -158,7 +158,10 @@ export const mimeOf = (file: string) => MIME[path.extname(file).toLowerCase()] ?
158
158
 
159
159
  export class JiraClient {
160
160
  readonly creds: JiraCreds;
161
- readonly mcp: McpClient;
161
+ private readonly mcpUrl: string;
162
+ private mcpP: Promise<McpClient> | undefined;
163
+ /** the MCP auth scheme in use, once picked; `verified` when the site was seen through it */
164
+ private picked: { scheme: JiraAuth; verified: boolean } | undefined;
162
165
  private readonly fetchFn: FetchLike;
163
166
  private cloudIdP: Promise<string> | undefined;
164
167
  private cloudIdFixed: string | undefined;
@@ -169,7 +172,60 @@ export class JiraClient {
169
172
  this.creds = creds;
170
173
  this.fetchFn = opts.fetch ?? (globalThis.fetch as unknown as FetchLike);
171
174
  this.cloudIdFixed = opts.cloudId;
172
- this.mcp = new McpClient(opts.mcpUrl ?? MCP_URL, { authorization: basicAuth(creds) }, this.fetchFn);
175
+ this.mcpUrl = opts.mcpUrl ?? MCP_URL;
176
+ }
177
+
178
+ /** The MCP session, with the auth scheme picked on first use. */
179
+ private mcp(): Promise<McpClient> {
180
+ this.mcpP ??= this.pickAuth().catch((e) => {
181
+ this.mcpP = undefined;
182
+ throw e;
183
+ });
184
+ return this.mcpP;
185
+ }
186
+
187
+ /** Which Authorization the MCP server honours for this token. A scoped token works only as Bearer; sent as
188
+ * Basic the server still lists its tools but sees no site ("Cloud id … isn't explicitly granted"). So each
189
+ * scheme is tried until getAccessibleAtlassianResources returns a site; a stored scheme is used as is. */
190
+ private async pickAuth(): Promise<McpClient> {
191
+ const make = (s: JiraAuth) => new McpClient(this.mcpUrl, { authorization: mcpAuth(this.creds, s) }, this.fetchFn);
192
+ if (this.creds.auth) {
193
+ this.picked = { scheme: this.creds.auth, verified: false };
194
+ return make(this.creds.auth);
195
+ }
196
+ let fallback: { c: McpClient; scheme: JiraAuth } | undefined;
197
+ let err: unknown;
198
+ for (const scheme of ["bearer", "basic"] as const) {
199
+ const c = make(scheme);
200
+ try {
201
+ const tools = await c.listTools();
202
+ const t = tools.find((x) => (TOOLS.resources as readonly string[]).includes(x.name));
203
+ if (!t) {
204
+ // nothing to check with: the first scheme the server accepts
205
+ this.picked = { scheme, verified: false };
206
+ return c;
207
+ }
208
+ const r = await c.callTool(t.name, {});
209
+ if (!r.isError && arr(resultValue(r), "resources").length) {
210
+ this.picked = { scheme, verified: true };
211
+ return c;
212
+ }
213
+ fallback ??= { c, scheme };
214
+ } catch (e) {
215
+ err ??= e;
216
+ }
217
+ }
218
+ if (fallback) {
219
+ this.picked = { scheme: fallback.scheme, verified: false };
220
+ return fallback.c;
221
+ }
222
+ throw err;
223
+ }
224
+
225
+ /** The MCP auth scheme this client uses, after connecting; `verified` when it proved to reach a site. */
226
+ async authScheme(): Promise<{ scheme: JiraAuth; verified: boolean }> {
227
+ await this.mcp();
228
+ return this.picked!;
173
229
  }
174
230
 
175
231
  get site() {
@@ -180,7 +236,7 @@ export class JiraClient {
180
236
  }
181
237
 
182
238
  private async tool(op: Op): Promise<McpTool | undefined> {
183
- const tools = await this.mcp.listTools();
239
+ const tools = await (await this.mcp()).listTools();
184
240
  for (const n of TOOLS[op]) {
185
241
  const t = tools.find((x) => x.name === n);
186
242
  if (t) return t;
@@ -207,7 +263,7 @@ export class JiraClient {
207
263
  if (!t) return { ok: false, error: `the Atlassian MCP server offers no ${TOOLS[op].join("/")} tool` };
208
264
  const needsCloud = t.inputSchema?.properties && "cloudId" in t.inputSchema.properties;
209
265
  const args = this.args(t, { ...(needsCloud ? { cloudId: await this.cloudId() } : {}), ...logical });
210
- const r = await this.mcp.callTool(t.name, args);
266
+ const r = await (await this.mcp()).callTool(t.name, args);
211
267
  if (r.isError) return { ok: false, error: `${t.name}: ${resultText(r).slice(0, 400)}` };
212
268
  return { ok: true, value: resultValue(r), via: "mcp" };
213
269
  } catch (e) {
@@ -223,8 +279,8 @@ export class JiraClient {
223
279
  try {
224
280
  const t = await this.tool("resources");
225
281
  if (t) {
226
- const r = await this.mcp.callTool(t.name, {});
227
- const hit = arr(resultValue(r)).map(rec).find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
282
+ const r = await (await this.mcp()).callTool(t.name, {});
283
+ const hit = arr(resultValue(r), "resources").map(rec).find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
228
284
  if (hit?.cloudId ?? hit?.id) return str(hit.cloudId ?? hit.id);
229
285
  }
230
286
  } catch {
@@ -248,7 +304,8 @@ export class JiraClient {
248
304
  return this.gateway ?? `https://${this.creds.site}/rest/api/3`;
249
305
  }
250
306
 
251
- /** Jira REST with the same token — only for what the MCP server cannot do. */
307
+ /** Jira REST with the same token (always Basic `email:token`, scoped or not) — only for what the MCP
308
+ * server cannot do. */
252
309
  private async rest(method: string, p: string, body?: unknown, extra: Record<string, string> = {}): Promise<JiraResult<unknown>> {
253
310
  try {
254
311
  const headers: Record<string, string> = { authorization: basicAuth(this.creds), accept: "application/json", ...extra };
package/src/jira/creds.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  /**
2
- * Jira credentials — a Cloud API token sent as HTTP Basic `email:token` (the Atlassian Rovo MCP server's
3
- * API-token auth). They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by
2
+ * Jira credentials — a Cloud API token for the Atlassian Rovo MCP server. A scoped token (the kind the MCP
3
+ * server needs) is sent as `Authorization: Bearer <token>`; Basic `email:token` is the fallback for a plain
4
+ * token. The scheme that worked is stored as `auth` next to the token, so later sessions skip the probe.
5
+ * Jira's REST API always takes Basic `email:token`. They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by
4
6
  * `/flow jira login`; `JIRA_EMAIL` / `JIRA_API_TOKEN` (and optionally `JIRA_SITE`) override the file.
5
7
  * Never printed, never written to project.md or to a comment.
6
8
  */
@@ -8,11 +10,17 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "n
8
10
  import os from "node:os";
9
11
  import path from "node:path";
10
12
 
13
+ /** How the token goes to the MCP server: `Bearer <token>` or Basic `email:token`. */
14
+ export type JiraAuth = "bearer" | "basic";
15
+ export const isJiraAuth = (v: unknown): v is JiraAuth => v === "bearer" || v === "basic";
16
+
11
17
  export interface JiraCreds {
12
18
  site: string; // acme.atlassian.net
13
19
  email: string;
14
20
  token: string;
15
21
  source: "env" | "file";
22
+ /** the MCP auth scheme known to work; unset → probed (Bearer first) */
23
+ auth?: JiraAuth;
16
24
  }
17
25
 
18
26
  export const credsPath = (home = os.homedir()) => path.join(process.env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent"), "dev-flow", "jira.json");
@@ -25,7 +33,7 @@ export const normSite = (s: string) =>
25
33
  .replace(/\/.*$/, "")
26
34
  .toLowerCase();
27
35
 
28
- type Store = { sites?: Record<string, { email: string; token: string }> };
36
+ type Store = { sites?: Record<string, { email: string; token: string; auth?: JiraAuth }> };
29
37
 
30
38
  function readStore(file: string): Store {
31
39
  try {
@@ -39,19 +47,33 @@ function readStore(file: string): Store {
39
47
  export function loadCreds(site?: string, env: NodeJS.ProcessEnv = process.env, file = credsPath()): JiraCreds | null {
40
48
  const want = site ? normSite(site) : env.JIRA_SITE ? normSite(env.JIRA_SITE) : undefined;
41
49
  if (env.JIRA_EMAIL && env.JIRA_API_TOKEN && (want || env.JIRA_SITE))
42
- return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env" };
50
+ return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env", ...(isJiraAuth(env.JIRA_AUTH) ? { auth: env.JIRA_AUTH } : {}) };
43
51
  const sites = readStore(file).sites ?? {};
44
52
  const key = want ?? Object.keys(sites)[0];
45
53
  const hit = key ? sites[key] : undefined;
46
- return hit && key ? { site: key, email: hit.email, token: hit.token, source: "file" } : null;
54
+ return hit && key ? { site: key, email: hit.email, token: hit.token, source: "file", ...(isJiraAuth(hit.auth) ? { auth: hit.auth } : {}) } : null;
47
55
  }
48
56
 
49
- export function saveCreds(site: string, email: string, token: string, file = credsPath()): void {
57
+ export function saveCreds(site: string, email: string, token: string, file = credsPath(), auth?: JiraAuth): void {
50
58
  mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
51
59
  const store = existsSync(file) ? readStore(file) : {};
52
- store.sites = { ...(store.sites ?? {}), [normSite(site)]: { email: email.trim(), token: token.trim() } };
60
+ store.sites = { ...(store.sites ?? {}), [normSite(site)]: { email: email.trim(), token: token.trim(), ...(auth ? { auth } : {}) } };
61
+ writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
62
+ chmodSync(file, 0o600);
63
+ }
64
+
65
+ /** Remember the MCP auth scheme that worked for a stored login (no-op when the site or token changed). */
66
+ export function saveAuth(creds: Pick<JiraCreds, "site" | "token">, auth: JiraAuth, file = credsPath()): void {
67
+ if (!existsSync(file)) return;
68
+ const store = readStore(file);
69
+ const hit = store.sites?.[creds.site];
70
+ if (!hit || hit.token !== creds.token || hit.auth === auth) return;
71
+ hit.auth = auth;
53
72
  writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
54
73
  chmodSync(file, 0o600);
55
74
  }
56
75
 
57
76
  export const basicAuth = (c: Pick<JiraCreds, "email" | "token">) => `Basic ${Buffer.from(`${c.email}:${c.token}`).toString("base64")}`;
77
+
78
+ /** The MCP server's Authorization header for `scheme` (default: the stored one, else Bearer). */
79
+ export const mcpAuth = (c: Pick<JiraCreds, "email" | "token" | "auth">, scheme: JiraAuth = c.auth ?? "bearer") => (scheme === "bearer" ? `Bearer ${c.token}` : basicAuth(c));
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
@@ -59,7 +59,7 @@ export async function gateJiraInit(root: string, cfg: Config, rest: string[], fl
59
59
  if (!creds) return { text: needsOperator(noCreds(siteArg ?? cfg.jira?.site), "Jira login?", "ask the operator to run /flow jira login (never ask them to paste the token into the chat); once they say it is done, re-run flow jira init"), isError: true };
60
60
  const client = clientFor(creds, cfg.jira?.site === creds.site ? cfg.jira.cloudId : undefined);
61
61
  const me = await client.me();
62
- if (!me.ok) return { text: `Jira authentication failed on ${creds.site} (${creds.source === "env" ? "JIRA_EMAIL/JIRA_API_TOKEN" : "stored login"}): ${me.error}\nThe Atlassian MCP server takes a Cloud API token as Basic email:token only when an org admin enabled API-token authentication for it (Atlassian Administration → Rovo MCP server). Check the email and token (/flow jira login re-enters them).`, isError: true };
62
+ if (!me.ok) return { text: `Jira authentication failed on ${creds.site} (${creds.source === "env" ? "JIRA_EMAIL/JIRA_API_TOKEN" : "stored login"}): ${me.error}\nThe Atlassian MCP server needs a scoped API token (read:jira:agent-interface, write:jira:agent-interface; sent as Bearer), and an org admin must have enabled API-token authentication for it (Atlassian Administration → Rovo MCP server). Check the token (/flow jira login re-enters it).`, isError: true };
63
63
  const head = `Jira: authenticated as ${me.value.displayName} on ${creds.site} (Atlassian MCP server)`;
64
64
 
65
65
  const project = flagValue(rest, "project") ?? cfg.jira?.project;
@@ -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