pi-dev-flow 0.84.0 → 0.85.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.85.0] - 2026-11-08
8
+
9
+ **`flow verify` deploys for review without a dialog, catches up with main first, and asks before taking another flow's dev port.**
10
+
11
+ ### Fixed
12
+ - **The agent's `flow` call never opens a dialog** (fixes #181). In pi-web a bare `flow verify` deployed, then sat in a Yes/No dialog inside the tool call: once for 87 minutes, during which nobody could talk to the agent. Another time the operator clicked Yes, the result did not say so, and the agent reported that the stage had advanced on its own. Now every gate the agent calls answers with `NEEDS-OPERATOR <Question?>` and the agent asks in chat. A `/flow` command you type still asks in a dialog, and its answer is labelled `(confirmed in dialog)`.
13
+ - **`flow verify` reviews the tree that ships.** A branch 18 commits behind main was deployed for review, without the two releases that had just shipped, and verified that way. Now `flow verify` fetches and rebases a branch that is behind before it deploys. A conflict aborts the rebase and leaves the branch as it was. `flow verify --confirmed` refuses when main moved since the review deploy.
14
+ - **The post-Verified? warning at `flow release` lists only the branch's own commits** (fixes #180). Commits merged in from main are a count (`+N merged in from main, not listed`).
15
+
16
+ ### Added
17
+ - **The bare `flow verify` is the review deploy.** It runs checks, build, `dev` and the health probe, then returns `deployed for review` with the question to ask. `flow verify --confirmed` records the answer.
18
+ - **Parallel flows no longer overwrite each other's dev deploy silently.** `flow verify` records who deployed on which port, and `flow status` shows it. When the port belongs to another live flow, verify asks first, with the free RAM and disk against the playbook's `instanceMem`/`instanceDisk`. The options are: run alongside on the next free port (`--port=<n>`), replace (`--replace`), or wait. New `## implement` keys: `port`, `parallelDev`, `instanceMem`, `instanceDisk`, `devDown` (run by `flow finish` for a side-port instance) and `servedBuild`. `dev`, `health` and `servedBuild` get `$DEV_FLOW_PORT`, `$DEV_FLOW_INSTANCE` and `$DEV_FLOW_SUFFIX`.
19
+ - **`servedBuild`** proves the deployed app serves the worktree's HEAD. Verify refuses when it doesn't.
20
+
7
21
  ## [0.84.0] - 2026-11-05
8
22
 
9
23
  **A yolo given early no longer ships commits nobody saw, and per-machine ignored files are writable without a flow.**
@@ -28,6 +28,21 @@ binding, so `flow status` prints the key and says so instead of leaving a shared
28
28
  guessed from a path. Dev-flow keeps no per-process session state beyond that keyed map, released on
29
29
  shutdown; the one other process-wide cache (`compile()` in `src/core.ts`) holds flag-less regexes,
30
30
  which carry no mutable state to leak between sessions.
31
+ **One dev stack, several flows.** A dev deploy is machine state, not branch state, so `flow verify`
32
+ keeps a small registry (`.dev-flow/dev-ports.json`: port → slug, commit, time) and `flow status` prints
33
+ it (`dev: port 8090 → <slug> @ <sha>`). Before deploying, verify checks whether its port was last
34
+ deployed by **another live flow**. If so it does not deploy: it returns `NEEDS-OPERATOR Dev port?` with
35
+ who holds the port (stage, commit, age), the available RAM and free disk against the playbook's
36
+ `instanceMem` / `instanceDisk`, and the options — run alongside on the next free port
37
+ (`flow verify --port=<n>`), replace that deploy (`--replace`), or wait. Running alongside is offered
38
+ only when the playbook allows it (`parallelDev` is not `no`, `dev`/`health` read `$DEV_FLOW_PORT`) and
39
+ the resources fit. A finished or aborted flow holds no port. `flow finish` stops a flow's
40
+ non-default-port instance with `devDown`.
41
+
42
+ **The review is of the tree that ships.** Parallel flows release while others are still implementing,
43
+ so `flow verify` rebases a branch that fell behind the default branch before it deploys for review,
44
+ and `flow verify --confirmed` refuses if the default branch moved again before the answer.
45
+
31
46
  Enforcement is by attribution: a write inside worktree X is judged
32
47
  by X's own feature stage no matter which session touches it; main-checkout code stays closed
33
48
  while your bound feature is in `plan`/`implement` and while any feature is unbound-and-ambiguous.
package/docs/gates.md CHANGED
@@ -4,8 +4,10 @@ Every gate, what it advances, and what makes it refuse.
4
4
 
5
5
  You normally type none of this: the agent runs the gates and you answer words in chat. `/flow <sub>` is
6
6
  your **manual surface** — read state when the agent is confused, or advance a gate yourself when it is
7
- stuck or claims a result it never ran. Same gates either way; an interactive run asks you in a dialog,
8
- so it needs no `--confirmed`.
7
+ stuck or claims a result it never ran. Same gates either way; a `/flow` command you type asks you in a dialog,
8
+ so it needs no `--confirmed`. The agent's own `flow` call never opens a dialog (#181): it returns
9
+ `NEEDS-OPERATOR <Question?>` and the agent asks you in chat. A dialog answer is labelled
10
+ `(confirmed in dialog)`, a chat answer `(confirmed by operator instruction)`.
9
11
 
10
12
  | Gate | Advances | Refuses unless |
11
13
  |---|---|---|
@@ -15,7 +17,7 @@ so it needs no `--confirmed`.
15
17
  | `test` | records a check | — (runs the `test` command/check, records pass/fail) |
16
18
  | `check` | records all tier-1 checks | — (runs every `flow-check`/test/health from project.md `## implement`); a `--docs` feature runs none of them and says `docs mode: project commands skipped` — a docs flow builds nothing, so a fresh checkout must not read as a failed deploy (#96) |
17
19
  | `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
18
- | `verify [--yolo]` | implement → pre-release | all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — except a **release-only flow** (#161): on a versioned project an empty branch over unreleased commits on the default branch (since the newest local version tag, or all of them before the first release) passes, the line says `release-only flow: N unreleased commit(s)`, and the version bump is the pre-release commit; with nothing unreleased the refusal says there is nothing to release; and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`); with **no `dev` command but a `health` probe configured the gate live-re-probes the app before asking** (`health: live re-probe PASS` — a killed server refuses with `live probe FAILED`, because process death dirties no worktree fingerprint and a green record alone cannot prove liveness: start the app and rerun), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
20
+ | `verify [--yolo] [--port=<n>\|--replace]` | implement → pre-release | **without `--confirmed` it is the review deploy**: it fetches and, when the branch is behind `origin/<default>` (or local `<default>` with no remote), **rebases** it — untracked files never block, uncommitted tracked edits and conflicts refuse (the rebase is aborted, the branch untouched); when the dev port (playbook `port`, or the whole stack when none is set) was last deployed by **another live flow** it refuses with `NEEDS-OPERATOR Dev port?`, the measured RAM/disk against `instanceMem`/`instanceDisk`, and the options: run alongside on the next free port (offered only when `parallelDev` is not `no`, `dev`/`health` read `$DEV_FLOW_PORT`, and the resources fit), `--replace`, or wait — nothing is built first; then it deploys and returns `deployed for review` with the chat question. **With `--confirmed`** it never rewrites history: a default branch that moved since refuses (re-run `flow verify`). With `servedBuild` set the served commit must be the worktree's HEAD. Otherwise: all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — except a **release-only flow** (#161): on a versioned project an empty branch over unreleased commits on the default branch (since the newest local version tag, or all of them before the first release) passes, the line says `release-only flow: N unreleased commit(s)`, and the version bump is the pre-release commit; with nothing unreleased the refusal says there is nothing to release; and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`); with **no `dev` command but a `health` probe configured the gate live-re-probes the app before asking** (`health: live re-probe PASS` — a killed server refuses with `live probe FAILED`, because process death dirties no worktree fingerprint and a green record alone cannot prove liveness: start the app and rerun), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
19
21
  | `release [--yolo|--no-version|--no-fold-check|--no-marker-check]` | pre-release → release | checks re-greened after the prep edits; `release.preflight` (when set) passes in the worktree — the build the tag will trigger, proven before anything ships; **the branch adds no merge-conflict marker lines** vs its merge base (#164: a hand-resolved merge that kept a `<<<<<<<`/`>>>>>>>` line is refused with `file:line`; `--no-marker-check` on the operator's word when the lines are meant); **commits after Verified?** are named in the Release? question and the approved line (#162: the operator's word covers the HEAD verify stamped — a warning, never a refusal); a **standing yolo** (given at an earlier checkpoint) does not answer Release? when such commits exist, nor ever under `yolo = until-release` in `## release` — the gate returns NEEDS-OPERATOR Release? (gh#176), while `--confirmed` (the operator's answer, a yolo said at Release? included) still passes; **the worktree holds no uncommitted paths** (gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix that never ships; the refusal lists the paths, and the approved line prints `commits: N ahead of <default>, M uncommitted path(s)` like verify's); with `versioning.file`: the manifest version parses and is **not tagged yet** (the bump must be ahead of the last release); with `release.changelog` the gate **proves the entry mechanically** (#97): a **heading names the version** (prose that mentions it, or a `1.2.0-beta` section when releasing `1.2.0`, is not an entry), **this branch touched the file** (an inherited changelog is not release prep), **every entry that was pending before the release survives inside the new section** — compared on normalized lines, so re-indenting a fold is free while rewording or deleting one is refused by naming the line — and **nothing is left under `Unreleased`**. The proofs guard the **baseline's** pending lines — they do not freeze the wording of the entry this flow writes, so a branch that landed as several iteration commits is free to state its result as one entry (see the changelog-writer rule in the pre-release reference). The pending baseline is the newest tag's changelog (what actually shipped), else the branch's merge base; when neither resolves, the two git-dependent proofs are skipped **with a printed advisory** rather than refusing a legal release for a topology reason, and the content proofs (the heading, its body) always run; tier-2 `## pre-release` checklist confirmed; the manifest version it validates is **stamped as the release's version of record** (`release-done` publishes that, whatever the checkouts say later); **one question** (Release?) — or `--confirmed`; `--no-version` (your call at Release?) ships this flow as **merge + changelog** — the bump/tag requirements and the tag checks at `release-done` are skipped for it, but the branch must still add its **own line under `Unreleased`** (a `--docs` flow is exempt — #163: a playbook/docs change owes no user-facing entry; one it writes is welcome, not proven) (editing an older section releases nothing) and it rides there until the next versioned release folds it (default: versioned); `--no-fold-check` is the operator-granted escape from the line-level fold proofs — one flow, stamped in the gate output, the heading and touched proofs stay; **stale session build** (loaded build behind the checkout): the gate prints both builds, lists what shipped between them (those proofs will not run this release) and folds *update (/reload, then re-run) or proceed with the old release?* into the Release? question — the operator's word, recorded in the release output, **never a block**: publishing under an older gate is a legitimate choice (hotfix, offline reload) |
20
22
  | `release-done` | records the release (the stage stays `release`) | **no question — the Release? answer covered the publication**; verify approval; the version published is the one `release` **stamped** from the manifest it validated (a main checkout still behind cannot republish the previous version), and it must not be older than the newest matching tag **on origin** (tag lists come from `git ls-remote`, so an unfetched clone does not decide what exists; when an origin exists but cannot be asked (offline, no ssh agent) **both release gates refuse** rather than answering with local tags); with `versioning.file`: that tag exists, is reachable from the default branch **and is on origin** (a local-only tag is not a release); with `release.artifact`: the published-artifact check runs (`{version}`/`{tag}` placeholders — the line it prints names the version it verified; skip once with `--no-artifact-check`, operator-instructed only) · creates the forge release from the tag, its body **the `release.changelog` entry for that version** — the changelog is the source of truth, and the tag's annotation stands in only when the changelog has no entry for the version, else nothing (and it says why — a body that is really a shell error is dropped, never shipped) — `gh` for GitHub, `glab` for GitLab) and then **proves the release exists**: it asks the forge (`gh release view <tag>` / `glab release view <tag>`) and refuses when nothing is there, because #51, #60 and #63 were three ways of ending `release recorded as complete` with nothing published — and when the changelog was the body it **reads the stored body back** and refuses a mismatch, so the release page and the changelog cannot drift (#97; normalized before comparing, skipped with a printed note on another forge). Skipping is deliberate and loud — `--no-release-create`, `release.releases = false` or `forge = self` each print that no forge release was created, and the view check is skipped for them; **with a `merge` policy** it also proves the merge that shipped matches it — branch ancestry plus what the forge says (`gh pr view` / `glab api`), so a squash under `merge = merge` (or a merge commit under `merge = squash`) refuses the release record, while a shape it cannot see prints an advisory instead (#97's split: an invisible topology never blocks a legal release); when the release went out on a stale build the operator acknowledged at the release gate, it prints that acknowledgement in place of the after-the-fact version-skew warning, and that warning prints the session vs disk version pair plus the duplicate-copy note when a second copy is registered (#117) |
21
23
  | `finish [--yolo] [--no-reflect] [--note=<text>] [slug]` | release → done — **first run the closing reflection**: while no reflection is recorded for the flow, finish starts the reflect worker before it touches anything and stops for the operator's fold/drop (or Finish? when nothing was found); the re-run with `--confirmed` does the cleanup. `--no-reflect --confirmed` skips it on the operator's explicit word (yolo never does); `--note=` hands the worker the operator's friction notes. Cleanup (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes (the refusal lists the paths, not just the count — gh#131); when the clean checkout trails `origin/<default>` the gate **fast-forwards local main** as it closes out (never a merge — anything that cannot fast-forward prints the operator's exact `git pull --ff-only` command); **one question** (Finish? — mentions unmerged-looking commits with the playbook's `merge` policy in mind, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; under `merge = merge`, commits that never reached the default branch are a **policy violation**: `yolo` does not answer it, only your explicit answer does; to abandon an unreleased feature use `abort` |
package/docs/playbook.md CHANGED
@@ -76,6 +76,24 @@ Prefer feature flags for risky paths.
76
76
  whose readiness lags its container start needs a wait, not a poll loop hand-written into the playbook.
77
77
  `healthWait = 0` restores the single shot.
78
78
 
79
+ **Dev port and parallel flows.** Two flows on one machine share one dev stack unless you say otherwise:
80
+
81
+ ```flow
82
+ port = 8090 # the default dev port — exported to dev/health/servedBuild as $DEV_FLOW_PORT
83
+ parallelDev = yes # can two instances run side by side? (no = only replace or wait are offered)
84
+ instanceMem = 2G # what one instance needs — checked against available RAM
85
+ instanceDisk = 5G # …and against free disk
86
+ dev = BFF_PORT=$DEV_FLOW_PORT COMPOSE_PROJECT_NAME=app$DEV_FLOW_SUFFIX docker compose up -d
87
+ devDown = COMPOSE_PROJECT_NAME=app$DEV_FLOW_SUFFIX docker compose down
88
+ servedBuild = curl -fsS http://127.0.0.1:$DEV_FLOW_PORT/version # must print the served commit
89
+ ```
90
+
91
+ `$DEV_FLOW_SUFFIX` is empty on the default port and `-<slug>` on any other, so a second instance gets its own
92
+ compose project. `flow verify` records who deployed on which port in `.dev-flow/dev-ports.json`; when the
93
+ port it would use belongs to another live flow it asks you first (see [concurrency](concurrency.md)).
94
+ `flow finish` runs `devDown` for an instance on a non-default port. `servedBuild` turns "something answers"
95
+ into "this branch answers": verify refuses when its output names no prefix of the worktree's HEAD.
96
+
79
97
  Your project's own safety rules are a `flow-guard` block in `## global` — the reason a project
80
98
  adopting dev-flow can delete its own guard extension:
81
99
 
@@ -20,7 +20,9 @@
20
20
  * Inactive (fully pass-through) in repos without a .dev-flow/ directory.
21
21
  */
22
22
  import { exec } from "node:child_process";
23
- import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
+ import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statfsSync, writeFileSync } from "node:fs";
24
+ import { createServer } from "node:net";
25
+ import { freemem } from "node:os";
24
26
  import path from "node:path";
25
27
  import { promisify } from "node:util";
26
28
  import { Type } from "@earendil-works/pi-ai";
@@ -147,6 +149,10 @@ import {
147
149
  releaseOrderInvocation,
148
150
  type BranchState,
149
151
  type Config,
152
+ type DevSlot,
153
+ formatSize,
154
+ servedBuildMatches,
155
+ sideBySide,
150
156
  type FeatureRef,
151
157
  type FlowState,
152
158
  type StageCheck,
@@ -385,7 +391,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
385
391
  }
386
392
 
387
393
  const GATE_HELP =
388
- "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
394
+ "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
389
395
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
390
396
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
391
397
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -629,6 +635,159 @@ function featureEnv(root: string, state: FlowState): Record<string, string> {
629
635
  return featureTmpEnv(dir);
630
636
  }
631
637
 
638
+ /** The port this flow's dev deploy uses: the operator's pick for it, else the playbook default. */
639
+ const devPortOf = (state: FlowState, cfg: Config): number | undefined => state.devPort ?? cfg.devPort;
640
+
641
+ /** featureEnv plus where this flow's dev instance lives: $DEV_FLOW_PORT, $DEV_FLOW_INSTANCE (the slug) and
642
+ * $DEV_FLOW_SUFFIX — "" on the default port, "-<slug>" on another — for a compose project name or container
643
+ * prefix that must not collide with the instance already running. */
644
+ function devEnv(root: string, state: FlowState, cfg: Config): Record<string, string> {
645
+ const port = devPortOf(state, cfg);
646
+ const side = state.devPort !== undefined && state.devPort !== cfg.devPort;
647
+ return { ...featureEnv(root, state), ...(port !== undefined ? { DEV_FLOW_PORT: String(port) } : {}), DEV_FLOW_INSTANCE: state.slug, DEV_FLOW_SUFFIX: side ? `-${state.slug}` : "" };
648
+ }
649
+
650
+ // ---------------------------------------------------------------- dev stack registry
651
+ // One machine, one dev port, several flows: who deployed last is what decides whether a verify may
652
+ // redeploy there or must ask first. Keyed by port ("default" when the playbook names none).
653
+ const devPortsFile = (root: string) => path.join(dfDir(root), "dev-ports.json");
654
+ const slotKey = (port: number | undefined) => (port === undefined ? "default" : String(port));
655
+
656
+ /** Live slots only: a slot whose flow finished (state.json gone) or was aborted holds nothing. */
657
+ function readDevPorts(root: string): Record<string, DevSlot> {
658
+ let raw: Record<string, DevSlot>;
659
+ try {
660
+ raw = JSON.parse(readFileSync(devPortsFile(root), "utf8")) as Record<string, DevSlot>;
661
+ } catch {
662
+ return {};
663
+ }
664
+ return Object.fromEntries(
665
+ Object.entries(raw).filter(([, v]) => {
666
+ const st = v?.slug ? readState(root, v.slug) : null;
667
+ return !!st && !st.aborted;
668
+ }),
669
+ );
670
+ }
671
+
672
+ function writeDevPorts(root: string, reg: Record<string, DevSlot>): void {
673
+ atomicWrite(devPortsFile(root), `${JSON.stringify(reg, null, "\t")}\n`);
674
+ }
675
+
676
+ function portFree(port: number): Promise<boolean> {
677
+ return new Promise((resolve) => {
678
+ const srv = createServer();
679
+ srv.once("error", () => resolve(false));
680
+ srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
681
+ });
682
+ }
683
+
684
+ async function nextFreePort(from: number, taken: Set<number>): Promise<number | null> {
685
+ for (let p = from + 1; p < Math.min(from + 50, 65536); p++) if (!taken.has(p) && (await portFree(p))) return p;
686
+ return null;
687
+ }
688
+
689
+ /** MemAvailable (what a new process can really get) where Linux reports it, else the OS free figure. */
690
+ function memAvailable(): number | null {
691
+ try {
692
+ const m = readFileSync("/proc/meminfo", "utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);
693
+ if (m) return Number(m[1]) * 1024;
694
+ } catch {
695
+ /* not Linux */
696
+ }
697
+ const f = freemem();
698
+ return Number.isFinite(f) ? f : null;
699
+ }
700
+
701
+ function diskFreeAt(dir: string): number | null {
702
+ try {
703
+ const st = statfsSync(dir);
704
+ return Number(st.bavail) * Number(st.bsize);
705
+ } catch {
706
+ return null;
707
+ }
708
+ }
709
+
710
+ function ago(iso: string): string {
711
+ const min = Math.round((Date.now() - Date.parse(iso)) / 60_000);
712
+ if (!Number.isFinite(min)) return "at an unknown time";
713
+ return min < 1 ? "just now" : min < 90 ? `${min} min ago` : `${Math.round(min / 60)} h ago`;
714
+ }
715
+
716
+ const portLabel = (port: number | undefined) => (port === undefined ? "the dev stack" : `port ${port}`);
717
+
718
+ /** Before a verify deploys: is the stack it would replace held by another live flow? Applies the
719
+ * operator's `--port=<n>` / `--replace` answer, or asks — with the measured resources — which to do. */
720
+ async function devSlotCheck(o: GateCtx, state: FlowState): Promise<RunResult | { note: string }> {
721
+ const { root, cfg, flag, rest } = o;
722
+ const portArg = flagValue(rest, "port");
723
+ if (portArg !== null) {
724
+ const n = Number(portArg);
725
+ if (!Number.isInteger(n) || n < 1 || n > 65535) return { text: `--port=${portArg} is not a port`, isError: true };
726
+ if (cfg.devPort === undefined) return { text: "--port needs a default `port` in the playbook's ## implement flow block — dev-flow exports the chosen one to dev/health as $DEV_FLOW_PORT", isError: true };
727
+ if (n === cfg.devPort) delete state.devPort;
728
+ else state.devPort = n;
729
+ writeState(root, state);
730
+ }
731
+ const port = devPortOf(state, cfg);
732
+ const reg = readDevPorts(root);
733
+ const slot = reg[slotKey(port)];
734
+ if (!slot || slot.slug === state.slug) return { note: "" };
735
+ if (flag("replace")) return { note: `dev: replaced ${slot.slug}'s deploy on ${portLabel(port)} (operator's answer)` };
736
+ const other = readState(root, slot.slug);
737
+ const taken = new Set(Object.keys(reg).map(Number).filter(Number.isFinite));
738
+ const nextPort = port !== undefined ? await nextFreePort(port, taken) : null;
739
+ const mem = memAvailable();
740
+ const disk = diskFreeAt(root);
741
+ const side = sideBySide({ cfg, nextPort, memAvail: mem, diskFree: disk });
742
+ const res = [
743
+ `RAM available ${mem !== null ? formatSize(mem) : "unknown"}${cfg.instanceMem !== undefined ? ` (one instance needs ${formatSize(cfg.instanceMem)})` : ""}`,
744
+ `disk free ${disk !== null ? formatSize(disk) : "unknown"}${cfg.instanceDisk !== undefined ? ` (one instance needs ${formatSize(cfg.instanceDisk)})` : ""}`,
745
+ ].join(", ");
746
+ const caveat = side.ok
747
+ ? cfg.parallelDev === undefined
748
+ ? " The playbook does not say whether two instances can share this machine (parallelDev = yes|no) — tell the operator that when you ask."
749
+ : ""
750
+ : ` Running alongside is not offered: ${side.why.join("; ")}.`;
751
+ const opts = [
752
+ ...(side.ok ? [`run alongside on port ${nextPort}: flow verify --port=${nextPort}`] : []),
753
+ `replace ${slot.slug}'s deploy: flow verify --replace`,
754
+ `wait until ${slot.slug} is done with it`,
755
+ ];
756
+ const held = `${portLabel(port)} is serving ${slot.slug} (stage ${other?.stage ?? "?"}${other?.pendingAsk ? `, waiting on ${other.pendingAsk}` : ""}, ${slot.head.slice(0, 7)}, deployed ${ago(slot.at)})`;
757
+ return { text: needsOperator(`${held} — this verify would replace it. Resources: ${res}.${caveat} Ask the operator which: ${opts.join(" | ")} — nothing was built or deployed yet.`, "Dev port?"), isError: true };
758
+ }
759
+
760
+ /** Before a review deploy: bring the branch up to date with the default branch, so the operator reviews
761
+ * the tree that will ship. Rebases a clean branch that is behind; refuses on a conflict (aborted, branch
762
+ * untouched) or on uncommitted work. With the operator's answer in hand (--confirmed) it never rewrites
763
+ * history: a default branch that moved since the review deploy sends the flow back to `flow verify`. */
764
+ async function catchUp(root: string, state: FlowState, cfg: Config, confirmed: boolean): Promise<RunResult | { note: string }> {
765
+ const cwd = gateCwd(root, state);
766
+ if (cwd === root) return { note: "" };
767
+ const d = cfg.defaultBranch;
768
+ const hasOrigin = !!(await originUrl(root));
769
+ let fetchNote = "";
770
+ if (hasOrigin && !(await sh(`git fetch -q origin ${sq(d)}`, cwd, 60_000)).ok) fetchNote = ` (fetch of origin/${d} failed — compared with the last fetched state)`;
771
+ const base = hasOrigin && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, cwd)).ok ? `origin/${d}` : d;
772
+ const r = await sh(`git rev-list --count HEAD..${sq(base)}`, cwd);
773
+ const behind = Number.parseInt(r.out.trim(), 10);
774
+ if (!r.ok || !Number.isFinite(behind)) return { note: `behind ${base}: unknown${fetchNote}` };
775
+ if (behind === 0) return { note: fetchNote ? `up to date with ${base}${fetchNote}` : "" };
776
+ if (confirmed)
777
+ return { text: `verify gate FAILED:\n- ${base} moved ${behind} commit(s) past this branch — the operator's answer would cover a tree that is not the one that ships. Run flow verify (it rebases and redeploys for review), then ask Verified? again`, isError: true };
778
+ // untracked build output (a deploy's artifacts) does not stop a rebase; uncommitted tracked edits do
779
+ const dirty = await sh("git status --porcelain --untracked-files=no", cwd);
780
+ if (dirty.ok && dirty.out.trim()) return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and has uncommitted changes — commit them, then re-run flow verify (it rebases before the review deploy)`, isError: true };
781
+ const rb = await sh(`git rebase ${sq(base)}`, cwd, 120_000);
782
+ if (!rb.ok) {
783
+ const conflicts = (await sh("git diff --name-only --diff-filter=U", cwd)).out.split("\n").filter(Boolean);
784
+ await sh("git rebase --abort", cwd);
785
+ return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and the rebase stopped on conflicts${conflicts.length ? ` (${conflicts.join(", ")})` : ""} — aborted, the branch is as it was. Rebase by hand in ${state.worktree} (git rebase ${base}), resolve, then re-run flow verify\n${tail(rb.out)}`, isError: true };
786
+ }
787
+ const pushed = hasOrigin && state.branch && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${state.branch}`)}`, cwd)).ok;
788
+ return { note: `rebased onto ${base} (was ${behind} commit(s) behind)${fetchNote}${pushed ? ` — origin/${state.branch} now differs: the next push needs --force-with-lease (dev-flow asks the operator)` : ""}` };
789
+ }
790
+
632
791
  /** Tier-1 checks the gate still has to see green. Entering a stage — and every edit of the worktree —
633
792
  * clears the records, so "run flow check first" cost three round trips to say what one could (#84).
634
793
  * `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
@@ -669,7 +828,7 @@ const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthP
669
828
  * deploy probe both do this). Returns an error result on failure, null when seeded or not configured. */
670
829
  async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{ text: string; isError: true } | null> {
671
830
  if (!cfg.commands.seedData) return null;
672
- const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, featureEnv(root, state));
831
+ const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, devEnv(root, state, cfg));
673
832
  state.checks.seedData = { ok: seed.ok, at: now() };
674
833
  writeState(root, state);
675
834
  return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
@@ -680,7 +839,7 @@ type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: Ru
680
839
  /** Seed (when configured), then run the health probe within the playbook's wait budget. */
681
840
  async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
682
841
  const seedFail = await seedStep(root, state, cfg);
683
- return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, featureEnv(root, state));
842
+ return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, devEnv(root, state, cfg));
684
843
  }
685
844
 
686
845
  /** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
@@ -1091,6 +1250,9 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1091
1250
  const { state, err } = needState(root, sess, slugArg);
1092
1251
  if (err) return err;
1093
1252
  const items = applicableItems(cfg, state!, "implement");
1253
+ // the operator reviews the tree that ships: catch up with the default branch before anything runs
1254
+ const caught = state!.stage === "implement" ? await catchUp(root, state!, cfg, flag("confirmed")) : { note: "" };
1255
+ if ("text" in caught) return caught;
1094
1256
  const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
1095
1257
  if (branch.commitsAhead === 0 && cfg.versioning.file) branch.unreleased = await unreleasedOnMain(gateCwd(root, state!), cfg.versioning.pattern);
1096
1258
  const branchLine = describeBranchState(branch, cfg.defaultBranch);
@@ -1105,9 +1267,14 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1105
1267
  // tier-1 gate first (tier-2 confirmation is recorded by this very command, so it is excluded here)
1106
1268
  const preGate = verifyGate({ ...state!, confirmations: { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } } }, cfg, branch);
1107
1269
  if (preGate.length) return { text: `verify gate FAILED:\n- ${preGate.join("\n- ")}\n${branchLine}`, isError: true };
1270
+ // a stack another flow is reviewing or releasing on is not this gate's to take — ask before deploying
1271
+ const slotted = cfg.commands.dev && !state!.docs ? await devSlotCheck(o, state!) : { note: "" };
1272
+ if ("text" in slotted) return slotted;
1108
1273
  // commands that take minutes and touch live services must say so (#38): a terse gate let the
1109
1274
  // agent tell the operator the dev deploy had never run, right after it recreated a container.
1110
1275
  const did: string[] = [];
1276
+ if (caught.note) did.push(caught.note);
1277
+ if (slotted.note) did.push(slotted.note);
1111
1278
  if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
1112
1279
  if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
1113
1280
  if (state!.docs) {
@@ -1115,7 +1282,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1115
1282
  did.push("docs mode: project commands skipped (build/dev/health)");
1116
1283
  } else {
1117
1284
  if (cfg.commands.build) {
1118
- const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, featureEnv(root, state!));
1285
+ const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
1119
1286
  state!.checks.build = { ok: res.ok, at: now() };
1120
1287
  writeState(root, state!);
1121
1288
  if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
@@ -1124,11 +1291,11 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1124
1291
  // deploy to dev before asking — the operator reviews the running dev app, not a promise
1125
1292
  const probe = healthProbe(cfg);
1126
1293
  if (cfg.commands.dev) {
1127
- const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, featureEnv(root, state!));
1294
+ const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
1128
1295
  state!.checks.dev = { ok: res.ok, at: now() };
1129
1296
  writeState(root, state!);
1130
1297
  if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
1131
- did.push(`dev ran (${cfg.commands.dev})`);
1298
+ did.push(`dev ran (${cfg.commands.dev})${devPortOf(state!, cfg) !== undefined ? ` on port ${devPortOf(state!, cfg)}` : ""}`);
1132
1299
  // the deploy is what must be proven, not just run: a container that came back unhealthy, or
1133
1300
  // still serves the previous build, must not pass on a health PASS recorded before it was
1134
1301
  // recreated. What "the expected version" means is the project's business — the probe runs in
@@ -1152,17 +1319,32 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1152
1319
  did.push(`health: live re-probe PASS (${probe}${triedNote(probed.attempts)})`);
1153
1320
  }
1154
1321
  }
1322
+ if (!state!.docs && cfg.commands.servedBuild) {
1323
+ // "something answers" is not "this branch answers": the served commit must be the worktree's HEAD
1324
+ const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
1325
+ const sb = await sh(cfg.commands.servedBuild, gateCwd(root, state!), 60_000, devEnv(root, state!, cfg));
1326
+ if (!sb.ok || !servedBuildMatches(sb.out, head))
1327
+ return { text: `served-build check FAILED (${cfg.commands.servedBuild}) — the app is up but does not serve this branch's HEAD ${head.slice(0, 12)}:\n${tail(sb.out)}`, isError: true };
1328
+ did.push(`serves ${head.slice(0, 7)} (HEAD)`);
1329
+ }
1330
+ if (!state!.docs && cfg.commands.dev) {
1331
+ const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
1332
+ writeDevPorts(root, { ...readDevPorts(root), [slotKey(devPortOf(state!, cfg))]: { slug: state!.slug, head, at: now() } });
1333
+ }
1155
1334
  const ran = [branchLine, ...did].join("; ");
1156
1335
  // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
1157
1336
  const yoloWord = takeYoloWord(state!);
1158
1337
  if (yoloWord) return { text: yoloWord, isError: true };
1159
- const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1338
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1160
1339
  const askPending = !flag("confirmed") && !state!.yolo;
1161
1340
  if (askPending) {
1162
1341
  markPendingAsk(root, state!, "Verified?"); // pending however it is asked — a chat question or a dialog
1163
- // these commands already ran — say so even on the way out
1342
+ // the agent's call never opens a dialog (#181): this is the review deploy — the app is up for the
1343
+ // operator, and the answer comes back in chat as flow verify --confirmed
1164
1344
  if (!ui.hasUI) {
1165
- return { text: `${needsOperator("verification needs the operator: confirm interactively, or re-run with --confirmed once the operator answered in chat.", "Verified?")}\n${ran}`, isError: true };
1345
+ const port = devPortOf(state!, cfg);
1346
+ const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : "live app re-probed for review";
1347
+ return { text: `${needsOperator(`${what} — look at the change in the running app yourself first (the playbook's self-check), then ask the operator Verified? in chat and run flow verify --confirmed once they answer. Keep it running until they answer.`, "Verified?")}\n${ran}` };
1166
1348
  }
1167
1349
  const ok = await ui.confirm("Operator verification", `Verified? All checks green${cfg.commands.dev && !state!.docs ? `; dev deploy is up for review (${cfg.commands.dev})` : ""} \u2014 does it work?`);
1168
1350
  if (!ok) {
@@ -1170,6 +1352,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1170
1352
  writeState(root, state!);
1171
1353
  return { text: "verification declined — stay in implement and fix what failed" };
1172
1354
  }
1355
+ audit = " (confirmed in dialog)";
1173
1356
  }
1174
1357
  state!.confirmations = { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } };
1175
1358
  const final = verifyGate(state!, cfg, branch);
@@ -1288,14 +1471,20 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1288
1471
  // so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
1289
1472
  let postVerify = "";
1290
1473
  if (state!.verifiedHead) {
1291
- const since = await sh(`git log --oneline --no-decorate ${sq(state!.verifiedHead)}..HEAD`, wtCwd);
1474
+ // gh#180: upstream work merged in after the verdict was approved on its own branch — only the branch's
1475
+ // own commits are news to the operator; the merged-in ones are a count, not a list to wade through
1476
+ const d = cfg.defaultBranch;
1477
+ const upstream = (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, wtCwd)).ok ? `origin/${d}` : (await sh(`git rev-parse --verify -q ${sq(`refs/heads/${d}`)}`, wtCwd)).ok ? d : "";
1478
+ const since = await sh(`git log --oneline --no-decorate ${upstream ? "--no-merges " : ""}${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`, wtCwd);
1292
1479
  const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
1480
+ const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
1481
+ const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
1293
1482
  // a release-only flow commits its bump and changelog after verify by design — only other files count
1294
1483
  const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
1295
1484
  const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
1296
1485
  const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
1297
1486
  if (commits.length && !prepOnly)
1298
- postVerify = `${commits.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${commits.slice(0, 6).join(" | ")}${commits.length > 6 ? ` …(${commits.length - 6} more)` : ""} — the verify verdict does not cover them: if behaviour changed, have the operator check the current build before Release?, and either way say in the PR body which commit the verdict was given over`;
1487
+ postVerify = `${commits.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${commits.slice(0, 6).join(" | ")}${commits.length > 6 ? ` …(${commits.length - 6} more)` : ""}${mergedIn ? ` (+${mergedIn} merged in from ${upstream}, not listed)` : ""} — the verify verdict does not cover them: if behaviour changed, have the operator check the current build before Release?, and either way say in the PR body which commit the verdict was given over`;
1299
1488
  }
1300
1489
  // a standing yolo (given at an earlier checkpoint) stops short of Release? when the playbook says so, or
1301
1490
  // when commits landed after Verified? — the word was given before those commits existed (gh#176).
@@ -1307,7 +1496,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1307
1496
  : postVerify
1308
1497
  ? "a yolo given earlier does not cover commits that landed after Verified? — ask Release? with them named"
1309
1498
  : "";
1310
- const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1499
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1311
1500
  const askPending = !flag("confirmed") && (!state!.yolo || !!yoloHeld);
1312
1501
  if (askPending) {
1313
1502
  markPendingAsk(root, state!, "Release?");
@@ -1320,6 +1509,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1320
1509
  writeState(root, state!);
1321
1510
  return { text: "release declined — keep preparing in pre-release" };
1322
1511
  }
1512
+ audit = " (confirmed in dialog)";
1323
1513
  }
1324
1514
  if (noVersion) state!.noVersion = true;
1325
1515
  state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
@@ -1593,6 +1783,21 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1593
1783
  return { text: "finish declined" };
1594
1784
  }
1595
1785
  }
1786
+ // a side-by-side dev instance (a port the operator picked at verify) is this flow's to stop; the default
1787
+ // port's stack stays up — it is the machine's shared app, and the next flow redeploys over it
1788
+ let devDownNote = "";
1789
+ if (state!.devPort !== undefined && state!.devPort !== cfg.devPort) {
1790
+ if (cfg.commands.devDown) {
1791
+ const down = await sh(cfg.commands.devDown, gateCwd(root, state!), 5 * 60_000, devEnv(root, state!, cfg));
1792
+ devDownNote = 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`;
1793
+ } else devDownNote = ` dev instance on port ${state!.devPort} is still running — the playbook has no devDown to stop it; stop it by hand.`;
1794
+ }
1795
+ const reg = readDevPorts(root);
1796
+ const mine = Object.keys(reg).filter((k) => reg[k].slug === state!.slug);
1797
+ if (mine.length) {
1798
+ for (const k of mine) delete reg[k];
1799
+ writeDevPorts(root, reg);
1800
+ }
1596
1801
  if (wt && existsSync(wt)) {
1597
1802
  const rm = await sh(`git worktree remove ${sq(wt)} && git branch -D ${sq(state!.branch)}`, root);
1598
1803
  if (!rm.ok) return { text: `worktree removal failed:\n${rm.out}\nif files are owned by another user (e.g. root-owned docker build output), remove ${state!.worktree} manually and rerun flow finish`, isError: true };
@@ -1636,7 +1841,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1636
1841
  // finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
1637
1842
  const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
1638
1843
  const nudgeNote = [nudge.fix, nudge.tidy].filter(Boolean).map((n) => ` ${n} — offer it to the operator.`).join("");
1639
- return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${reflectSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
1844
+ return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${devDownNote}${roadmapNote}${forgeSkipNote}${reflectSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
1640
1845
  }
1641
1846
 
1642
1847
  /** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
@@ -1915,7 +2120,7 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1915
2120
  const errs = approveGate(state!, cfg, planFiles, existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined, foreignWorktreeLinks(dfDir(root), state!.slug, mockupHtml));
1916
2121
  if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1917
2122
  const planItems = applicableItems(cfg, state!, "plan");
1918
- const audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
2123
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
1919
2124
  const askPending = !flag("confirmed");
1920
2125
  if (askPending) {
1921
2126
  markPendingAsk(root, state!, "Approve?");
@@ -1928,6 +2133,7 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1928
2133
  writeState(root, state!);
1929
2134
  return { text: "approval declined — keep iterating on the plan" };
1930
2135
  }
2136
+ audit = " (confirmed in dialog)";
1931
2137
  }
1932
2138
  // the operator's word at Approve?, recorded only once given: every later gate question is pre-confirmed; checks and guardrails stay
1933
2139
  if (flag("yolo")) state!.yolo = true;
@@ -1992,6 +2198,8 @@ async function gateStatus(o: GateCtx): Promise<RunResult> {
1992
2198
  ` next: ${nextHint(st, cfg)}`,
1993
2199
  ];
1994
2200
  });
2201
+ // who holds the dev stack: the one thing two parallel flows on one machine must not guess
2202
+ 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)}`);
1995
2203
  if (warn.length) lines.push(...warn);
1996
2204
  // which identity this session's state is keyed by: a claim fight is undiagnosable when the key
1997
2205
  // could be a session id or a shared directory and the output does not say which
@@ -2508,6 +2716,7 @@ export default function devFlow(pi: ExtensionAPI) {
2508
2716
  return String(input ?? "").trim().split(/\s+/).filter(Boolean);
2509
2717
  };
2510
2718
 
2719
+ const NO_DIALOGS: Ui = { hasUI: false, confirm: async () => false };
2511
2720
  const uiFrom = (ctx: ExtensionContext): Ui => ({
2512
2721
  hasUI: ctx.hasUI,
2513
2722
  confirm: async (title, message) => (ctx.hasUI ? ctx.ui.confirm(title, message) : Promise.resolve(false)),
@@ -2606,7 +2815,10 @@ export default function devFlow(pi: ExtensionAPI) {
2606
2815
  }),
2607
2816
  execute: async (id, params, signal, onUpdate, ctx) => {
2608
2817
  const root = await flowRoot(ctx.cwd);
2609
- const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
2818
+ // the agent's call never opens a dialog (#181): a dialog inside a tool call blocks the turn, so nobody
2819
+ // can talk to the agent while it waits, and the agent cannot see who answered. Gates answer with the
2820
+ // chat word to ask instead; the /flow slash command (a human at the keyboard) keeps its dialogs.
2821
+ const res = await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
2610
2822
  if (!res.isError) maybeCompactNow(ctx, root);
2611
2823
  return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
2612
2824
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.84.0",
3
+ "version": "0.85.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": [
@@ -42,8 +42,15 @@ feature).
42
42
  up to `healthWait` (default 30s) — a service needing a moment after its
43
43
  container starts is not a failed deploy; say so rather than declaring a
44
44
  healthy deploy broken. Walk the **tier-2 checklist** (`- [ ]`) with the
45
- operator honestly — it cannot be scripted. Keep the app **running** when
46
- you ask **Verified?** → `flow verify --confirmed` — the operator reviews
45
+ operator honestly — it cannot be scripted. **Verify is two steps.**
46
+ `flow verify` prepares the review: it rebases onto the default branch when
47
+ the branch is behind (a conflict aborts and hands it to you), deploys, and
48
+ returns `deployed for review` — it never opens a dialog. If another flow
49
+ holds the dev port it returns `NEEDS-OPERATOR Dev port?` with the free RAM
50
+ and disk instead of deploying: put the options to the operator and re-run
51
+ with their answer (`--port=<n>` alongside, or `--replace`). Then look at the
52
+ change yourself, keep the app **running** while you ask **Verified?**, and
53
+ record the answer with `flow verify --confirmed` — the operator reviews
47
54
  the live app, so never tear the test server down before the checkpoint is
48
55
  answered (with no `dev` deploy configured, `flow verify` live-re-probes
49
56
  `health` itself and refuses while nothing is answering). Checkpoint report: stage line **🔨 implement ·
@@ -132,7 +139,10 @@ runs past 15 min), re-runs the health probe **against what it just deployed**
132
139
  `healthWait`, then refuses the gate reporting its attempts — a pre-deploy PASS
133
140
  describes a container that no longer exists; no probe prints
134
141
  `health: none configured` and the doctor flags it), and demands all tier-1
135
- checks green before the single question. The operator's confirm covers the
142
+ checks green before the single question. With `servedBuild` set it also proves
143
+ the app serves the worktree's HEAD, not just that something answers. A
144
+ `--confirmed` run refuses when the default branch moved since the review
145
+ deploy: run `flow verify` again so the answer covers the tree that ships. The operator's confirm covers the
136
146
  tier-2 list as a set (hashed; edits reset it). A `--docs` feature prints
137
147
  `docs mode: project commands skipped` and asks only the verify question.
138
148
  Verify lands the feature in **pre-release**.
package/src/core.ts CHANGED
@@ -50,6 +50,7 @@ export interface FlowState {
50
50
  releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
51
51
  verifiedHead?: string; // HEAD the operator's Verified? was given over — release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
52
52
  reflectedAt?: string; // a reflect worker reported for this flow — finish runs one first while this is unset (only --no-reflect --confirmed skips it)
53
+ devPort?: number; // the port the operator chose for this flow's dev deploy when the default was held by another flow — finish stops it (devDown)
53
54
  aborted?: string; // flow abort on a feature whose worktree exists: the state is a deliberate abandoned-feature record (gh#138) — the doctor's git-consistency sweep must never flag its hand-removed worktree as drift
54
55
  }
55
56
 
@@ -71,6 +72,10 @@ export interface Commands {
71
72
  run?: string;
72
73
  /** Deploy to a dev/staging environment before verification — operator reviews the running dev app. */
73
74
  dev?: string;
75
+ /** Stop a dev instance this flow started on a non-default port (run by flow finish). */
76
+ devDown?: string;
77
+ /** Print the commit the deployed app serves — verify refuses when it is not the worktree's HEAD. */
78
+ servedBuild?: string;
74
79
  }
75
80
 
76
81
  /** How a merged feature branch lands on the default branch (playbook key `merge`).
@@ -106,6 +111,13 @@ export interface Config {
106
111
  versioning: Versioning;
107
112
  /** Seconds the post-deploy health probe may keep retrying before the gate gives up (0 = single shot). */
108
113
  healthWait: number;
114
+ /** The dev deploy's default port (playbook `port`). Unset: dev-flow cannot run a second instance, only name who holds the stack. */
115
+ devPort?: number;
116
+ /** Can two dev instances run side by side (playbook `parallelDev`)? undefined = the playbook does not say. */
117
+ parallelDev?: boolean;
118
+ /** Bytes one dev instance needs (playbook `instanceMem` / `instanceDisk`, e.g. 2G) — the side-by-side feasibility check. */
119
+ instanceMem?: number;
120
+ instanceDisk?: number;
109
121
  release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any"; /** `until-release`: a standing yolo never answers Release? (gh#176) */ yolo?: "all" | "until-release" };
110
122
  mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
111
123
  /** `inject` (default): the class default timeout is armed silently on every shell call.
@@ -192,6 +204,49 @@ export function toSeconds(raw: unknown): number | undefined {
192
204
  return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
193
205
  }
194
206
 
207
+ /** A playbook size (`2G`, `512M`, `1.5GB`, plain bytes) in bytes; undefined for junk. */
208
+ export function parseSize(raw: unknown): number | undefined {
209
+ const m = typeof raw === "string" ? raw.trim().match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i) : null;
210
+ if (typeof raw === "number" && Number.isFinite(raw) && raw >= 0) return Math.floor(raw);
211
+ if (!m) return undefined;
212
+ const mult = { "": 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 }[m[2].toLowerCase() as "" | "k" | "m" | "g" | "t"];
213
+ return Math.floor(Number(m[1]) * mult);
214
+ }
215
+
216
+ /** Bytes as the operator reads them: 9.1G, 512M. */
217
+ export function formatSize(n: number): string {
218
+ for (const [u, d] of [["T", 1024 ** 4], ["G", 1024 ** 3], ["M", 1024 ** 2], ["K", 1024]] as const) if (n >= d) return `${(n / d).toFixed(1).replace(/\.0$/, "")}${u}`;
219
+ return `${n}B`;
220
+ }
221
+
222
+ /** Does a `servedBuild` printout name this HEAD? Any hex token of 7+ characters that is a prefix of the full sha counts. */
223
+ export function servedBuildMatches(out: string, head: string): boolean {
224
+ const full = head.trim().toLowerCase();
225
+ if (full.length < 7) return false;
226
+ return (out.toLowerCase().match(/[0-9a-f]{7,40}/g) ?? []).some((t) => full.startsWith(t));
227
+ }
228
+
229
+ /** Who last deployed dev on a port (`.dev-flow/dev-ports.json`, key = port or "default"). */
230
+ export interface DevSlot {
231
+ slug: string;
232
+ head: string;
233
+ at: string;
234
+ }
235
+
236
+ /** What the clash question offers, from measured resources and the playbook's declared costs. */
237
+ export function sideBySide(o: { cfg: Config; nextPort: number | null; memAvail: number | null; diskFree: number | null }): { ok: boolean; why: string[] } {
238
+ const { cfg } = o;
239
+ const why: string[] = [];
240
+ if (cfg.devPort === undefined) why.push("the playbook names no `port`, so dev-flow cannot place a second instance");
241
+ if (cfg.parallelDev === false) why.push("the playbook says `parallelDev = no` (instances would share state)");
242
+ const dev = `${cfg.commands.dev ?? ""}\n${cfg.commands.health ?? ""}`;
243
+ if (cfg.devPort !== undefined && !/DEV_FLOW_PORT/.test(dev)) why.push("the playbook's `dev`/`health` commands do not read $DEV_FLOW_PORT, so a second instance would land on the same port");
244
+ if (o.nextPort === null && cfg.devPort !== undefined) why.push("no free port found above the default");
245
+ if (cfg.instanceMem !== undefined && o.memAvail !== null && o.memAvail < cfg.instanceMem) why.push(`RAM available ${formatSize(o.memAvail)} < ${formatSize(cfg.instanceMem)} one instance needs`);
246
+ if (cfg.instanceDisk !== undefined && o.diskFree !== null && o.diskFree < cfg.instanceDisk) why.push(`disk free ${formatSize(o.diskFree)} < ${formatSize(cfg.instanceDisk)} one instance needs`);
247
+ return { ok: why.length === 0, why };
248
+ }
249
+
195
250
  /**
196
251
  * Retry schedule for the health probe (#42): a service whose readiness lags its container start can
197
252
  * never pass a single shot, so the gate waits instead of failing the deploy. One immediate attempt
@@ -2113,7 +2168,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
2113
2168
  return `investigate, present your direction and proposed mode to the operator and clarify in chat, then write the plan into .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask the operator Approve? in chat and run flow approve --confirmed when they answer`;
2114
2169
  case "implement":
2115
2170
  if (state.docs) return `implement in the worktree ${state.worktree} — docs mode runs no project command (no build, no dev deploy, no health probe); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
2116
- return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
2171
+ return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then run flow verify — it rebases onto the default branch when behind and deploys for review (asking first when another flow holds the dev port) — look at the change yourself, then ask the operator Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
2117
2172
  case "pre-release":
2118
2173
  if (state.docs && (cfg.versioning.file || cfg.release.changelog))
2119
2174
  return `${cfg.release.review} → fix must-have/should-have → docs flow: it usually ships unversioned — ask the operator; with their word, flow release --no-version needs no bump, no tag and (docs mode) no changelog entry. Shipping it versioned instead:${cfg.release.changelog ? ` prepare ${cfg.release.changelog}` : ""}${cfg.versioning.file ? `${cfg.release.changelog ? " and" : ""} bump version in ${cfg.versioning.file}` : ""}. Then show the operator the PR summary, ask Release? and run flow release`;
package/src/projectmd.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { existsSync, readdirSync, readFileSync } from "node:fs";
9
9
  import path from "node:path";
10
- import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
10
+ import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, parseSize, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
11
11
 
12
12
  export const MD_STAGES = ["global", "plan", "implement", "pre-release", "release"] as const;
13
13
  export type MdStage = (typeof MD_STAGES)[number];
@@ -46,6 +46,12 @@ const KEYMAP: Record<string, Record<string, string>> = {
46
46
  health: "commands.health",
47
47
  dev: "commands.dev",
48
48
  healthWait: "healthWait", // seconds the post-deploy probe may keep retrying (#42)
49
+ port: "devPort", // the dev deploy's default port — exported to dev/health as $DEV_FLOW_PORT
50
+ parallelDev: "parallelDev", // yes | no — can two dev instances run side by side?
51
+ instanceMem: "instanceMem", // what one dev instance needs, e.g. 2G — the side-by-side check
52
+ instanceDisk: "instanceDisk",
53
+ devDown: "commands.devDown", // stops a flow's non-default-port instance at finish
54
+ servedBuild: "commands.servedBuild", // prints the commit the deployed app serves — verify proves it is HEAD
49
55
  },
50
56
  release: {
51
57
  versionFile: "versioning.file",
@@ -258,6 +264,13 @@ function mergeInto(c: Config, r: Record<string, unknown>): void {
258
264
  // playbook values arrive as strings; a junk healthWait must not make the gate wait forever
259
265
  const wait = toSeconds(r.healthWait);
260
266
  if (wait !== undefined) c.healthWait = wait;
267
+ const port = toSeconds(r.devPort);
268
+ if (port !== undefined && port > 0 && port < 65536) c.devPort = port;
269
+ if (typeof r.parallelDev === "string") c.parallelDev = /^(yes|true)$/i.test(r.parallelDev) ? true : /^(no|false)$/i.test(r.parallelDev) ? false : undefined;
270
+ const mem = parseSize(r.instanceMem);
271
+ if (mem !== undefined) c.instanceMem = mem;
272
+ const disk = parseSize(r.instanceDisk);
273
+ if (disk !== undefined) c.instanceDisk = disk;
261
274
  }
262
275
 
263
276
  /**
@@ -335,6 +348,7 @@ export function setPlaybookCheck(text: string, name: string, cmd: string): { tex
335
348
  const ANSWER_STAGE: Record<string, MdStage> = {
336
349
  defaultBranch: "global", forge: "global", worktreeDir: "global", branchPattern: "global", mainHook: "global", mockupGlobs: "global", bashTimeout: "global",
337
350
  setup: "implement", test: "implement", build: "implement", run: "implement", seedData: "implement", health: "implement", dev: "implement", healthWait: "implement",
351
+ port: "implement", parallelDev: "implement", instanceMem: "implement", instanceDisk: "implement", devDown: "implement", servedBuild: "implement",
338
352
  versionFile: "pre-release", versionTag: "pre-release", changelog: "pre-release", review: "pre-release",
339
353
  releases: "release", artifact: "release", preflight: "release", merge: "release", yolo: "release",
340
354
  };