pi-dev-flow 0.86.3 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.88.0] - 2026-11-09
8
+
9
+ **Recording a release waits for its CI, review fixes can be re-verified, and `--confirmed` needs your actual word.**
10
+
11
+ ### Fixed
12
+ - **A feature folder that lost its state file is no longer a dead end (gh#178).** If `.dev-flow/<slug>/` survived without `state.json` and had no `plan/`, the two commands sent you in a circle. `flow start` said "already exists, flow use it", and `flow use` said "no unfinished feature". Both now say the folder is a ghost and list what's in it. `flow start <slug> --confirmed` adopts it and keeps its files. A leftover `worktree/` is the one exception: a new start would collide with it, so `flow start` refuses and names the cleanup to run first.
13
+ - **`--confirmed` needs an actual operator message (gh#190).** `--confirmed` means "the operator answered in chat", but nothing checked that, so the agent could grant an operator-only option to itself. Two sessions showed it. In one, a `flow start --ui` refusal came straight back with `--confirmed`. In the other, a plain `flow start` was switched to `--ui --confirmed` without asking. The flow tool now counts your messages in the session and refuses two things. First, a `--confirmed` re-run of a gate that asked for your word, when you haven't sent a message since it asked. Second, turning on `--ui`, `--patch` or `--docs` for a feature this session started, when you haven't sent a message since the start. It doesn't judge what you said: one message after the question is enough. The refusal counts as friction for the closing reflection.
14
+ - **Review fixes can be verified before release (gh#187).** The pre-release review often turns up fixes that change behaviour, but `flow verify` refused at pre-release. Those fixes shipped under a Verified? you had given over the earlier build, and nothing could re-ask it. At pre-release, `flow verify` now redeploys the current tree and asks Verified? again. Your answer moves the verdict to that tree, and the flow stays in pre-release. A yolo given earlier doesn't answer this question, because it was given before the fixes existed.
15
+ - **The "commits after Verified?" warning no longer counts the release-prep commit.** The version bump and changelog entry always land after Verified?, so the warning fired on every versioned release. That made a real unverified fix look the same as routine release prep. The warning now leaves out a commit that touches the version file, or that touches only the version file and changelog. That includes bump commits that also rewrite an image tag elsewhere. The warning still names those commits, as "release prep … not counted". The same rule decides whether the closing reflection treats a post-Verified? commit as friction.
16
+ - **Recording a release waits for the publish CI instead of failing on it (gh#179).** The tag push is what starts the CI that publishes the artifact, so the artifact check in `flow release-done` (and in `flow finish`, which runs the same proofs) used to fail right after the tag with "not found". The agent then had to watch the CI run by hand and re-run the gate. On GitHub, a missing artifact now makes the gate look for the CI runs that the tag started. If one is still running, the gate waits for it, up to 15 minutes plus a minute's grace for a registry that lags the run, and then checks again. If a run failed, the refusal names it with its URL. If the run is still going when the wait ends, the refusal points at it. If the tag started no run at all, the gate says so after a minute. Without GitHub, or without `gh`, the check behaves as before.
17
+
18
+ ## [0.87.0] - 2026-11-09
19
+
20
+ **Fewer false alarms, more reflections where they matter, and a way to drop a roadmap item.**
21
+
22
+ ### Fixed
23
+ - **The "don't ask the operator to type commands" note stops firing on plain reports.** After a final reply, dev-flow checks whether the agent handed you a flow command to type and, if so, adds a hidden correction. In recent sessions every one of these corrections was wrong. The agent was only reporting what it had run, for example "`bun run build`, `docker compose up -d --no-deps`" or "`flow check`: PASS". Three things caused it: any `--flag` counted as a dev-flow flag, words inside inline code such as `bun run` counted as instructions to you, and stage workers hosted by pi-web were not recognised as workers. Now only dev-flow's own gate flags count, the check reads only the words outside code, each clause is judged separately, reflection report rows are skipped, and pi-web workers are excluded.
24
+ - **The closing reflection now runs on flows that had real friction.** Finish skips the reflection when a flow went smoothly, but it judged that too narrowly. A refusal made before `flow start` was dropped, because no feature existed yet to count it against. Code changes committed after you answered Verified? also didn't count. Both now count: the pre-start refusal goes to the feature that `start` creates, and a post-Verified? commit that touches more than the version bump and changelog counts when you answer Release?.
25
+
26
+ ### Added
27
+ - **`flow roadmap drop <n>`** (alias `remove`) deletes an open roadmap item and its brief. Before this, the only way to remove an idea you no longer wanted was `done`, which recorded it as shipped.
28
+
7
29
  ## [0.86.3] - 2026-11-09
8
30
 
9
31
  **dev-flow talks to you in outcomes, not internals.**
package/docs/gates.md CHANGED
@@ -11,18 +11,18 @@ so it needs no `--confirmed`. The agent's own `flow` call never opens a dialog (
11
11
 
12
12
  | Gate | Advances | Refuses unless |
13
13
  |---|---|---|
14
- | `start <slug> [--ui|--patch|--docs --confirmed] [--merge=squash\|merge\|rebase\|any] [--check-upstream]` | → plan | slug is new (binds the session); `--ui` and the relaxed modes are operator-granted in chat, anchored by `--confirmed` (`--ui` = the plan gate demands rendered mockups; on an existing feature still at plan, `start <slug> --ui --confirmed` from its bound session switches the flag on instead of refusing); `--patch` = chore release, no plan document, every gate unchanged; `--docs` = docs-only, no plan document and no tier-1 checks (worktree and release intact). Start prints the dev-flow build and stamps it into the feature state (`flow status` shows `flow=<ver>`), warns when **this session runs an older build than the checkout** (`--check-upstream` also asks npm for the published one), prints the playbook gaps `flow doctor` would report — and **refuses while the playbook has no `merge` policy**: it names the question (squash / merge / rebase / any), the style its own history suggests, and the re-run `--merge=<style> --confirmed`, which writes the answer into `## release` (single-line insert, validated, `.bak` kept, committed as a playbook chore only when the playbook is the only dirty path) and never asks again |
14
+ | `start <slug> [--ui|--patch|--docs --confirmed] [--merge=squash\|merge\|rebase\|any] [--check-upstream]` | → plan | slug is new (binds the session); a `.dev-flow/<slug>/` left without `state.json` is a **ghost** it names with its contents and adopts on `--confirmed`, keeping the files (a `plan/` becomes the draft) — except a leftover `worktree/`, which it refuses with the cleanup to run first (gh#178); `use <slug>` on a ghost says the same instead of "no unfinished feature"; `--ui` and the relaxed modes are operator-granted in chat, anchored by `--confirmed` (`--ui` = the plan gate demands rendered mockups; on an existing feature still at plan, `start <slug> --ui --confirmed` from its bound session switches the flag on instead of refusing); `--patch` = chore release, no plan document, every gate unchanged; `--docs` = docs-only, no plan document and no tier-1 checks (worktree and release intact). Start prints the dev-flow build and stamps it into the feature state (`flow status` shows `flow=<ver>`), warns when **this session runs an older build than the checkout** (`--check-upstream` also asks npm for the published one), prints the playbook gaps `flow doctor` would report — and **refuses while the playbook has no `merge` policy**: it names the question (squash / merge / rebase / any), the style its own history suggests, and the re-run `--merge=<style> --confirmed`, which writes the answer into `## release` (single-line insert, validated, `.bak` kept, committed as a playbook chore only when the playbook is the only dirty path) and never asks again |
15
15
  | `use <slug>` | — (binds this session to a feature) | slug unfinished — the binding is persisted to disk as a claim (`flow version` lists every dev-flow copy registered in the process, and a copy whose in-memory bindings never saw the bind attributes commands from the claim, so a two-sources setup does not misjudge your git) |
16
16
  | `approve [--yolo]` | plan → implement (creates worktree + branch) | `plan/plan.md` exists **by name** (a separate pre-plan/direction file does not open the gate — a preliminary direction belongs inside plan.md); if `--ui`, rendered mockup screenshots (per `mockupGlobs`, default `*.png`) exist under `plan/` — headless chromium renders embedded in plan.md, and the gate opens plan.md to prove it: every image file under `plan/` must appear in an embed (`![...](…)`, case-insensitive) and every `mockups/<screen>.html` must carry an embedded `<screen>-<width>.` shot, and no mockup may link (href/src/@import) into another feature's `.dev-flow/<other>/worktree/`; **one question** — or `--confirmed` after you answered in chat; **yolo** (your chat answer at **any** checkpoint question) → run that gate with `--yolo --confirmed` (`approve`/`verify`/`release`/`finish`): that question is answered and every later one (Verified?/Release?/Finish?) is pre-confirmed — the agent then runs the remaining gates back to back, honoring guidance attached to the yolo word (e.g. "yolo, create a patch version release") — checks and guardrails stay fully enforced. `commands.setup` runs in the worktree and is retried until it succeeds once (a worktree left behind by a failed setup is set up on the next `approve`, never silently reused); a `--docs` feature runs no project command at all and says `setup skipped (docs mode)` |
17
17
  | `test` | records a check | — (runs the `test` command/check, records pass/fail) |
18
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) |
19
19
  | `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
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 |
20
+ | `verify [--yolo] [--port=<n>\|--replace]` | implement → pre-release | **at pre-release it is the re-verify** (gh#187): after review fixes it runs the same build, deploy and probes over the current tree (no rebase), re-asks Verified? — a standing yolo never answers it — and on the answer moves the verdict (`verifiedHead`) to that tree, staying in 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 |
21
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) |
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) |
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; on GitHub a miss right after the tag push **waits for the CI runs that tag started** — up to 15 min, plus a minute's grace for a registry that lags the green run — then probes again, and a refusal names a failed or still-running run with its URL, gh#179) · 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) |
23
23
  | `finish [--yolo] [--no-reflect] [--note=<text>] [slug]` | release → done — **records an unrecorded release first** (published but `release-done` never ran: finish runs its proofs itself — that gate asks nothing, so it is not a separate step; its refusal is finish's) — **then 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); a flow with **no friction** (no gate refusal, no guard block, no `--note`) skips the worker unless the playbook sets `reflect = always`; 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` |
24
24
  | `reflect ["<note>"|list|tidy|move <n> --playbook|--code|done <n> ["<what>"]]` | — | `reflect "<note>"` queues a suggestion in **this project's** `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` (alias `--docs`) files it under `## playbook` — the fix lives only in `project.md`, a docs flow implements it; `--code` files it under `## code` — the fix touches project code, a patch flow implements it. `--plugin` **never writes**: dev-flow feedback is filed upstream, so it prints the recipe — `gh issue list --repo <dev-flow repo> --state all --search …` first, then `gh issue create` with a body ending `— reflection from <slug> <date>` (in the dev-flow repo itself plugin is code → `## code`). With no flag the wording guesses (plugin-shaped → the recipe; otherwise `## playbook`) and the echo prints why. `reflect list` numbers the open items with their section; `reflect move <n> --playbook|--code` re-files one; `reflect done <n> ["<what>"]` checks a fixed one off (`— fixed: <date> <slug> — <what>`) so doctor stops re-reporting it; a legacy `## plugin` row is flagged by list and doctor (file it upstream, check it off `— filed: gh#NNN`). `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items. **Nudges are timed, not constant**: `⚑ fix the open reflections now?` prints when an item recurred this session, is ≥ 14 days old, ≥ 3 playbook items wait, or a code item waits while between flows — at finish, in an unbound session and in doctor, never mid-feature; `↻ N closed reflection(s)` prints at ≥ 5 closed, closed ≥ open (≥ 3), or a closed item ≥ 30 days old. Bare `reflect` prints the **session-reflection protocol** (from the `/flow reflect` bar it additionally wakes the model): bound to a flow, delegate the review to `flow_stage` op `reflect`; unbound, review inline; re-check every open item against the playbook and **newer dev-flow versions** (`npm view pi-dev-flow version`; the operator performs updates); show the operator a numbered list with a fold/drop recommendation per finding and stop; fold docs/code → `reflect --playbook|--code`, fold plugin → the upstream issue, drop → nothing recorded |
25
- | `roadmap [add "<feature>" [--slug=<slug>] [--brief=<notes>\|--brief-file=<path>] \| pick <n> <slug> \| done <n> \| tidy]` | — | manages `.dev-flow/roadmap.md`, the gitignored backlog of future features (`- [ ]` checklist): bare prints the numbered open items, `add` appends one (`--slug=` stamps it like pick, `--brief=`/`--brief-file=` keeps notes under it as ` > ` lines, and a bound session records `— split from <slug>` — the spin-off route for a new feature surfaced mid-flow), `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it (start seeds `plan/plan.md` with the item and its brief) — **`finish` checks the stamped item off when that feature ships**; `done <n>` checks off by hand (items shipped outside a flow), `tidy` drops the checked lines. Never gates; the open count is surfaced in `status` and session context |
25
+ | `roadmap [add "<feature>" [--slug=<slug>] [--brief=<notes>\|--brief-file=<path>] \| pick <n> <slug> \| done <n> \| drop <n> \| tidy]` | — | manages `.dev-flow/roadmap.md`, the gitignored backlog of future features (`- [ ]` checklist): bare prints the numbered open items, `add` appends one (`--slug=` stamps it like pick, `--brief=`/`--brief-file=` keeps notes under it as ` > ` lines, and a bound session records `— split from <slug>` — the spin-off route for a new feature surfaced mid-flow), `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it (start seeds `plan/plan.md` with the item and its brief) — **`finish` checks the stamped item off when that feature ships**; `done <n>` checks off by hand (items shipped outside a flow), `drop <n>` (alias `remove`) deletes an open item and its brief that nobody wants any more — `done` would record it as shipped — `tidy` drops the checked lines. Never gates; the open count is surfaced in `status` and session context |
26
26
  | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — the state of an **aborted** feature is never a finding (its worktree cleanup is by design — gh#138) — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
27
27
  | `status [slug]` / `abort [slug]` | — | — |
28
28
  | `help` (`--help`, `-h`) | — | — (prints the gate help — answerable in any repo, at any stage, with no `.dev-flow/`) |
@@ -34,6 +34,7 @@ import { type Session, presentRun } from "../src/runtime/checks.ts";
34
34
  import { isSelfRepo } from "../src/runtime/setup.ts";
35
35
  import { foldView, pluginUpstream } from "../src/runtime/reflect.ts";
36
36
  import { type FlowHooks, runFlow } from "../src/runtime/gates.ts";
37
+ import { grantCheck, grantRecord, newGrantLedger, operatorMessageCount } from "../src/runtime/grants.ts";
37
38
  import { PIWEB_SUBAGENT, WORKER_TOOLS, piwebLiveClaim, piwebStamp, piwebWorkerMeta, reflectSeams, sessionHeaders, stageWorkerSpawn, workerName, workerSessions, workerTiming, writeTranscriptDigests } from "../src/runtime/workers.ts";
38
39
  export { compactionTakeover } from "../src/runtime/base.ts";
39
40
  export { reflectSeams, stageWorkerSpawn, workerTiming } from "../src/runtime/workers.ts";
@@ -139,6 +140,24 @@ export default function devFlow(pi: ExtensionAPI) {
139
140
  };
140
141
  };
141
142
 
143
+ /** Which gate asked for the operator's word, and when features started — per session (gh#190). */
144
+ const grantLedger = newGrantLedger();
145
+
146
+ /** A flow_stage worker: registered in this module's set, or — for a worker pi-web hosts, whose extension
147
+ * instance never saw the registration — stamped with pi-web's subagent entry. */
148
+ const isWorkerSession = (ctx: ExtensionContext): boolean => {
149
+ try {
150
+ if (workerSessions.has(ctx.sessionManager.getSessionId())) return true;
151
+ // SAFETY: narrow structural view of the SessionEntry union; only the custom entry's type is read
152
+ return (ctx.sessionManager?.getBranch() ?? []).some((e) => {
153
+ const ce = e as unknown as { type: string; customType?: string };
154
+ return ce.type === "custom" && ce.customType === PIWEB_SUBAGENT.meta;
155
+ });
156
+ } catch {
157
+ return false;
158
+ }
159
+ };
160
+
142
161
  /** Restore this session's binding from its branch history (survives resume/fork). */
143
162
  const rebuildSession = (ctx: ExtensionContext, root: string) => {
144
163
  let slug: string | null = null;
@@ -215,12 +234,18 @@ export default function devFlow(pi: ExtensionAPI) {
215
234
  // the agent's call never opens a dialog (#181): a dialog inside a tool call blocks the turn, so nobody
216
235
  // can talk to the agent while it waits, and the agent cannot see who answered. Gates answer with the
217
236
  // chat word to ask instead; the /flow slash command (a human at the keyboard) keeps its dialogs.
218
- const res = await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
237
+ // gh#190: --confirmed stands for the operator's chat answer — refuse it when no operator message came after the question
238
+ const users = operatorMessageCount((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })());
239
+ const selfGrant = grantCheck(params.args, sessionKey(ctx), users, grantLedger);
240
+ const res = selfGrant ? { text: selfGrant, isError: true } : await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
241
+ grantRecord(params.args, sessionKey(ctx), users, res, grantLedger);
219
242
  if (!res.isError) maybeCompactNow(ctx, root);
220
243
  // two readers: the model gets every instruction, the operator's row renders the view (renderResult) —
221
244
  // facts, the stage line and the question waiting on them, never a command to type
222
245
  // a refusal (not a question for the operator) is friction the closing reflection should look at
223
- if (res.isError && !res.text.startsWith(NEEDS_OPERATOR) && initiated(root)) noteFriction(root, sessionKey(ctx));
246
+ if (res.isError && (!res.text.startsWith(NEEDS_OPERATOR) || selfGrant) && initiated(root)) noteFriction(root, sessionKey(ctx));
247
+ // a start that bound a feature takes over the refusals this session hit before it existed
248
+ else if (!res.isError && params.args[0] === "start" && initiated(root)) noteFriction(root, sessionKey(ctx), 0);
224
249
  const { agent, view } = await presentRun(params.args, root, sessionKey(ctx), res);
225
250
  return { content: [{ type: "text", text: agent }], details: { view }, isError: res.isError };
226
251
  },
@@ -761,11 +786,7 @@ export default function devFlow(pi: ExtensionAPI) {
761
786
  const commandAskCorrection = (event: TurnEndEvent, ctx: ExtensionContext, root: string): TurnEndEventResult | undefined => {
762
787
  const e = event as { outcome?: string; toolResults?: unknown[]; message?: { role?: string; content?: unknown }; entries?: unknown[] };
763
788
  if (!initiated(root) || e.outcome !== "completed" || (e.toolResults?.length ?? 0) > 0 || e.message?.role !== "assistant") return undefined;
764
- try {
765
- if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined;
766
- } catch {
767
- /* not a worker */
768
- }
789
+ if (isWorkerSession(ctx)) return undefined;
769
790
  const parts = Array.isArray(e.message.content) ? (e.message.content as { type?: string; text?: string }[]) : [];
770
791
  const text = parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n");
771
792
  const hits = operatorCommandAsks(text);
@@ -790,11 +811,7 @@ export default function devFlow(pi: ExtensionAPI) {
790
811
  return undefined;
791
812
  }
792
813
  if (!initiated(root) || !boundFeature(root, key)) return undefined;
793
- try {
794
- if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined;
795
- } catch {
796
- /* not a worker */
797
- }
814
+ if (isWorkerSession(ctx)) return undefined;
798
815
  const streak = (hollowStreak.get(key) ?? 0) + 1;
799
816
  hollowStreak.set(key, streak);
800
817
  const resume = streak === 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.86.3",
3
+ "version": "0.88.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": [
@@ -23,7 +23,8 @@ criteria hold. Call it with an args array — `["start", "dark-mode"]`,
23
23
  chat — **Approve? / Verified? / Release? / Finish?** — mentioning that
24
24
  *yolo* is an answer, then stop. Their word (or a clear equivalent) in chat →
25
25
  run that gate with `--confirmed`. A structured question tool is not chat;
26
- never infer the answer. A gate returning `NEEDS-OPERATOR <Question?>` means:
26
+ never infer the answer — the flow tool refuses a `--confirmed` with no
27
+ operator message since the gate asked. A gate returning `NEEDS-OPERATOR <Question?>` means:
27
28
  ask exactly that, in chat. `/flow` is the operator's own override; mention it
28
29
  only when the session is demonstrably stuck or wrong (and `/reload` when
29
30
  `flow version` says this session runs an older build).
@@ -11,6 +11,10 @@ and settle the scheme with the operator; never invent one.
11
11
 
12
12
  1. **Review**: `/flow-review` the change; fix every **Must fix** and **Should
13
13
  fix**; `flow check` again if code changed.
14
+ - A fix that changes behaviour → `flow verify` again: it redeploys, then
15
+ ask **Verified?** over the fixed build and run `flow verify --confirmed`
16
+ on the answer (stays in pre-release; a standing yolo does not answer it).
17
+ Otherwise `flow release` warns that the fix shipped after Verified?.
14
18
  2. **Docs**: update them to match the change.
15
19
  3. **Changelog + bump** — manifest, changelog heading and tag must agree;
16
20
  commit the prep on the feature branch.
@@ -51,4 +51,5 @@ never gating.
51
51
  from the brief. A hand-made `.dev-flow/<slug>/plan/` is a ghost; `flow start
52
52
  <slug> --confirmed` adopts it.
53
53
  - Shipped outside a flow: `flow roadmap done <n>`; `flow roadmap tidy` drops
54
- checked lines.
54
+ checked lines. Not wanted any more (never built): `flow roadmap drop <n>` —
55
+ `done` would claim it shipped.
@@ -19,7 +19,8 @@ each step with the gate's stage line, **🚀 release · `<slug>`**; no `Done:` /
19
19
  `git push origin v<ver>`. Never `--follow-tags`.
20
20
  - CI builds from the tag? `release.preflight` proves that build at
21
21
  `flow release`; `release.artifact` makes the record step verify the
22
- published artifact.
22
+ published artifact. On GitHub it waits for the publish CI the tag
23
+ started (up to 15 min) — no hand-run `gh run watch` before it.
23
24
  - `--no-version` flow: no bump, no tag — publish the merge only.
24
25
  3. **Hand over to finish.** Once merged and tagged, the playbook continues in
25
26
  [finish.md](finish.md): `flow finish` records the release itself first
package/src/core.ts CHANGED
@@ -51,7 +51,7 @@ export interface FlowState {
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
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)
54
- friction?: number; // gate refusals and guard blocks this feature hit — finish skips the closing reflection at 0 (playbook reflect = on-friction)
54
+ friction?: number; // gate refusals, guard blocks and post-Verified? code changes this feature hit — finish skips the closing reflection at 0 (playbook reflect = on-friction)
55
55
  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
56
56
  }
57
57
 
@@ -372,7 +372,8 @@ export const isReleaseOnly = (cfg: Config, branch?: BranchState | null): boolean
372
372
  * committed the operator is asked to approve state no gate has ever seen. */
373
373
  export function verifyGate(state: FlowState, cfg: Config, branch?: BranchState | null): string[] {
374
374
  const errs: string[] = [];
375
- if (state.stage !== "implement") errs.push(`stage is "${state.stage}", verify only applies to "implement"`);
375
+ // pre-release: a re-verify after review fixes (gh#187) — the same proofs, over the tree that will ship
376
+ if (state.stage !== "implement" && state.stage !== "pre-release") errs.push(`stage is "${state.stage}", verify only applies to "implement" (or "pre-release", to re-ask Verified? after review fixes)`);
376
377
  // a release-only flow (#161) proves main's committed tree here; its version bump is the pre-release commit
377
378
  if (branch && branch.commitsAhead === 0 && !isReleaseOnly(cfg, branch))
378
379
  errs.push(
@@ -2083,6 +2084,23 @@ export function roadmapDone(text: string, n: number, stamp: string): string | nu
2083
2084
  return hit ? out.join("\n") : null;
2084
2085
  }
2085
2086
 
2087
+ /** Remove the nth open item (1-based, open items only) and its brief — an idea the operator no longer
2088
+ * wants, which `done` would record as shipped. Returns null when n is out of range. */
2089
+ export function roadmapDrop(text: string, n: number): { text: string; item: string } | null {
2090
+ let seen = 0;
2091
+ let item: string | null = null;
2092
+ let dropping = false;
2093
+ const out = text.split("\n").filter((l) => {
2094
+ if (isBriefLine(l)) return !dropping;
2095
+ dropping = false;
2096
+ if (!isOpenItem(l) || ++seen !== n) return true;
2097
+ item = l.trim().slice(6);
2098
+ dropping = true;
2099
+ return false;
2100
+ });
2101
+ return item === null ? null : { text: out.join("\n"), item };
2102
+ }
2103
+
2086
2104
  /** Check every open item stamped `(slug)` by a pick — flow finish closes the backlog item a picked feature ships.
2087
2105
  * shortcut: "(slug)" matches as substring — item prose literally containing "(fin)" closes when fin ships; only pick-minted stamps are meant to match. */
2088
2106
  export function roadmapDoneForSlug(text: string, slug: string, stamp: string): { text: string; count: number } {
@@ -2174,7 +2192,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
2174
2192
  case "pre-release": {
2175
2193
  const prep = [cfg.release.changelog ? `prepare ${cfg.release.changelog} (fold Unreleased lines verbatim)` : "", cfg.versioning.file ? `bump version in ${cfg.versioning.file}` : ""].filter(Boolean).join(" and ");
2176
2194
  if (state.docs && prep) return `${cfg.release.review}, fix must/should; a docs flow usually ships unversioned — ask the operator (flow release --no-version on their word); versioned instead: ${prep}; then ask Release? and run flow release`;
2177
- return `${cfg.release.review}, fix must/should, update docs${prep ? `, ${prep}` : ""}, flow check; show the PR summary, version and changelog, ask Release? and run flow release`;
2195
+ return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${prep ? `, ${prep}` : ""}, flow check; show the PR summary, version and changelog, ask Release? and run flow release`;
2178
2196
  }
2179
2197
  case "release":
2180
2198
  if (state.approvals.release) return `release recorded — commit and push any release chores in the main checkout (DEV_FLOW_ALLOW_MAIN=1 for the pre-commit hook), then flow finish (closing reflection first; its fold/drop answer is Finish?)`;
package/src/present.ts CHANGED
@@ -205,15 +205,27 @@ export function agentText(text: string, v: GateView): string {
205
205
  return v.stageLine ? `${text}\n${AGENT_MARK}stage line for your report (paste as is): ${v.stageLine}` : text;
206
206
  }
207
207
 
208
+ /** Flags only dev-flow's gates take. A generic CLI flag (`docker compose up -d --no-deps`, `gh pr merge --merge`)
209
+ * in a report of what the agent ran is not a dev-flow command handed to the operator. */
210
+ const GATE_FLAGS = "confirmed|ui|patch|docs|yolo|replace|port|no-version|no-fold-check|no-marker-check|no-artifact-check|no-release-create|no-reflect|check-upstream|answers|answers-file|write-file|brief|brief-file|playbook|note";
211
+ const ASK_COMMAND_RE = new RegExp(`(?:^|[\\s\`'"(*_])/?flow (?:${FLOW_VERBS})\\b|(?:^|[\\s\`])--(?:${GATE_FLAGS})\\b|\\bflow_stage\\b|(?:^|[\\s\`])/flow\\b`);
212
+ /** An imperative addressed to the operator: the verb opens a clause (or follows please/then/just), or a "you can" form. */
213
+ const ASK_VERB_RE = /(?:^|[:;,.!?(—–]\s*|\b(?:please|then|just|now|simply|and)\s+)(?:run|type|enter|use|try|send|invoke)\b|\byou (?:can|could|may|should|need to|might)\b|\bplease\b/i;
214
+
208
215
  /** Sentences in an assistant message that hand the operator a dev-flow command to type. */
209
216
  export function operatorCommandAsks(message: string): string[] {
210
217
  const hits: string[] = [];
211
218
  // fenced code is command output being shown, not a request
212
219
  const prose = message.replace(/```[\s\S]*?```/g, "");
213
- for (const sentence of prose.split(/(?<=[.!?])\s+|\n+/)) {
214
- if (!commandish(sentence)) continue;
215
- // addressed to the operator: an imperative or a "you can / please" form around the command
216
- if (/\b(you (can|could|may|should|need to|might)|please|type|run|enter|use|try|send|invoke)\b/i.test(sentence) && !/\bI('ll| will| am going to| ran|'m running| run)\b/.test(sentence)) hits.push(sentence.trim());
220
+ // a clause is the unit: "`flow verify` holds — you can use the QA agent" names a command and asks something else
221
+ for (const sentence of prose.split(/(?<=[.!?])\s+|\n+|\s[—–]\s|;\s/)) {
222
+ if (!ASK_COMMAND_RE.test(sentence)) continue;
223
+ // a reflection's report row (`F1 | fold | plugin | …`) describes a past session, it asks nothing
224
+ if (/^\s*[FO]\d+\s*\|/.test(sentence)) continue;
225
+ // the verb is read outside inline code (`bun run build` is a command named, not "run" said to the operator),
226
+ // with list bullets and emphasis markers dropped so a bullet's first word still opens its clause
227
+ const words = sentence.replace(/`[^`]*`/g, " ").replace(/^[\s>*_#-]*(?:\d+[.)]\s*)?/, "").replace(/[*_]+/g, "");
228
+ if (ASK_VERB_RE.test(words) && !/\bI('ll| will| am going to| ran|'m running| run)\b/.test(words)) hits.push(sentence.trim());
217
229
  }
218
230
  return hits;
219
231
  }
package/src/projectmd.ts CHANGED
@@ -464,6 +464,16 @@ export function ghostFeatureDirs(root: string): string[] {
464
464
  .map((d) => `.dev-flow/${d.name}`);
465
465
  }
466
466
 
467
+ /** A feature dir that survived without its state.json (gh#178): what is in it, and whether a stray
468
+ * worktree/ blocks adopting it (a git worktree a new start would collide with). Null when the dir is
469
+ * absent or a flow owns it. */
470
+ export function ghostInfo(root: string, slug: string): { entries: string[]; plan: boolean; worktree: boolean } | null {
471
+ const dir = path.join(root, ".dev-flow", slug);
472
+ if (!existsSync(dir) || existsSync(path.join(dir, "state.json"))) return null;
473
+ const entries = readdirSync(dir, { withFileTypes: true }).map((d) => (d.isDirectory() ? `${d.name}/` : d.name)).sort();
474
+ return { entries, plan: existsSync(path.join(dir, "plan")), worktree: existsSync(path.join(dir, "worktree")) };
475
+ }
476
+
467
477
  /**
468
478
  * Doctor: cheap file-level probes only — NEVER runs user commands.
469
479
  * Findings are advisory strings for `flow init` (fixer) and the status flag.
@@ -236,7 +236,7 @@ export async function releaseTags(root: string): Promise<string[] | null> {
236
236
  }
237
237
 
238
238
  export const GATE_HELP =
239
- "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)";
239
+ "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>|drop <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; drop <n> removes an item nobody wants any more (done would record it as shipped) — 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)";
240
240
  export const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
241
241
  export const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
242
242
  export const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -253,12 +253,23 @@ export function writeState(root: string, state: FlowState): void {
253
253
  atomicWrite(stateFile(root, state.slug), `${JSON.stringify(state, null, "\t")}\n`);
254
254
  }
255
255
 
256
- /** Count one refusal or guard block against the session's bound feature (best effort, never throws). */
257
- export function noteFriction(root: string, key: string): void {
256
+ /** Refusals a session hit before any feature was bound to it — a `flow start --ui` refused as operator-granted,
257
+ * then retried — belong to the feature that start creates next. */
258
+ const unboundFriction = new Map<string, number>();
259
+
260
+ /** Count one refusal or guard block against the session's bound feature (best effort, never throws).
261
+ * With nothing bound yet, the count waits for the feature the session starts next. */
262
+ export function noteFriction(root: string, key: string, by = 1): void {
258
263
  try {
259
264
  const st = boundFeature(root, key);
260
- if (!st) return;
261
- st.friction = (st.friction ?? 0) + 1;
265
+ if (!st) {
266
+ if (by) unboundFriction.set(key, (unboundFriction.get(key) ?? 0) + by);
267
+ return;
268
+ }
269
+ const total = by + (unboundFriction.get(key) ?? 0);
270
+ unboundFriction.delete(key);
271
+ if (!total) return;
272
+ st.friction = (st.friction ?? 0) + total;
262
273
  writeState(root, st);
263
274
  } catch {
264
275
  /* a counter must never fail the call it watches */
@@ -1,8 +1,8 @@
1
1
  /** dev-flow runtime — The gate runner and the gates that do not ship anything. Moved out of extensions/dev-flow.ts as is (exports added). */
2
2
  import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { approveGate, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapOpenCount, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState } from "../core.ts";
5
- import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
4
+ import { approveGate, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState } from "../core.ts";
5
+ import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, ghostInfo, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
6
6
  import { linkedTag } from "../fold.ts";
7
7
  import { detectProject } from "../detect.ts";
8
8
  import { AGENT_MARK } from "../present.ts";
@@ -278,10 +278,20 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
278
278
  if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --ui/--patch/--docs are operator-granted — ask the operator in chat, then add --confirmed", isError: true };
279
279
  // a ghost (plan/ but no state.json — typically a spin-off someone wrote by hand) is adopted, never a dead end:
280
280
  // "already exists, flow use it" sent the agent to use, which found no state, and doctor offered to delete it
281
- const ghost = existsSync(featDir(root, slugArg)) && !existsSync(stateFile(root, slugArg)) && existsSync(path.join(featDir(root, slugArg), "plan"));
282
- if (ghost && !flag("confirmed")) {
283
- const files = listFiles(path.join(featDir(root, slugArg), "plan"));
284
- return { text: `.dev-flow/${slugArg}/ is a ghost — plan/ (${files.join(", ") || "empty"}) but no state.json, so no flow owns it. Adopt it as this feature's draft plan: flow start ${slugArg} --confirmed (the operator agrees in chat), or delete the dir to start clean`, isError: true };
281
+ // gh#178: any feature dir without state.json is a ghost, not only one with a plan/ — a tmp/ or mockups
282
+ // left behind used to read as "already exists, flow use it", and flow use then found nothing
283
+ const gi = ghostInfo(root, slugArg);
284
+ if (gi?.worktree)
285
+ return { text: `.dev-flow/${slugArg}/ has a worktree/ but no state.json — a flow that lost its state; nothing can resume it, and a new start would collide with that worktree. Remove it first (git worktree remove --force .dev-flow/${slugArg}/worktree, or git worktree prune when git no longer lists it — after checking it holds nothing the operator wants), then flow start ${slugArg} --confirmed adopts the rest (${gi.entries.filter((e) => e !== "worktree/").join(", ") || "nothing else"})`, isError: true };
286
+ const ghost = !!gi;
287
+ if (gi && !flag("confirmed")) {
288
+ const files = gi.plan ? listFiles(path.join(featDir(root, slugArg), "plan")) : [];
289
+ return {
290
+ text: gi.plan
291
+ ? `.dev-flow/${slugArg}/ is a ghost — plan/ (${files.join(", ") || "empty"}) but no state.json, so no flow owns it. Adopt it as this feature's draft plan: flow start ${slugArg} --confirmed (the operator agrees in chat), or delete the dir to start clean`
292
+ : `.dev-flow/${slugArg}/ is a ghost — ${gi.entries.join(", ") || "empty"} but no state.json, so no flow owns it. Start ${slugArg} over it, keeping those files: flow start ${slugArg} --confirmed (the operator agrees in chat), or delete the dir to start clean`,
293
+ isError: true,
294
+ };
285
295
  }
286
296
  if (existsSync(featDir(root, slugArg)) && !ghost) {
287
297
  // --ui on the plan-stage feature this session drives: the operator asked for mockups after the start,
@@ -350,7 +360,7 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
350
360
  // the stamp is what ran, not what the disk claims (that mismatch is the warning above).
351
361
  const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), loadedVersion() ?? undefined);
352
362
  const planDir = path.join(featDir(root, slugArg), "plan");
353
- if (ghost) notes.push(`adopted ghost .dev-flow/${slugArg}/ — its plan/ (${listFiles(planDir).join(", ") || "empty"}) is this feature's draft`);
363
+ if (ghost) notes.push(gi!.plan ? `adopted ghost .dev-flow/${slugArg}/ — its plan/ (${listFiles(planDir).join(", ") || "empty"}) is this feature's draft` : `adopted ghost .dev-flow/${slugArg}/ — kept ${gi!.entries.join(", ") || "nothing (it was empty)"}`);
354
364
  mkdirSync(planDir, { recursive: true });
355
365
  // a roadmap item stamped for this slug carries its brief into the plan: the spin-off's context outlives the session that split it
356
366
  const picked = roadmapBriefFor(readRoadmap(root), slugArg);
@@ -558,13 +568,22 @@ export async function gateRoadmap(o: GateCtx): Promise<RunResult> {
558
568
  save(roadmapDone(text, idx, [new Date().toISOString().slice(0, 10), sess.slug].filter(Boolean).join(" "))!);
559
569
  return { text: `roadmap: item ${idx} marked done (${open - 1} open)` };
560
570
  }
571
+ case "drop":
572
+ case "remove":
573
+ case "delete": {
574
+ // not shipped, not wanted: gone from the backlog, so the done list never claims it was built
575
+ if (!validIdx) return { text: `drop: open item 1–${open} required — flow roadmap lists them`, isError: true };
576
+ const r = roadmapDrop(text, idx)!;
577
+ save(r.text);
578
+ return { text: `roadmap: item ${idx} dropped — "${r.item}" (${open - 1} open)` };
579
+ }
561
580
  case "tidy": {
562
581
  if (!done) return { text: `roadmap: nothing to tidy (${open} open, 0 done)` };
563
582
  save(roadmapTidy(text));
564
583
  return { text: `roadmap: dropped ${done} done item(s) — ${open} open` };
565
584
  }
566
585
  default:
567
- return { text: "usage: flow roadmap [list|add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy]", isError: true };
586
+ return { text: "usage: flow roadmap [list|add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy]", isError: true };
568
587
  }
569
588
  }
570
589
 
@@ -672,8 +691,13 @@ export async function gateUse(o: GateCtx): Promise<RunResult> {
672
691
  if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
673
692
  const st = readState(root, slugArg);
674
693
  if (!st) {
675
- const ghost = existsSync(path.join(featDir(root, slugArg), "plan"));
676
- return { text: ghost ? `.dev-flow/${slugArg}/ is a ghost — plan/ but no state.json, so there is nothing to resume: flow start ${slugArg} --confirmed adopts its plan as a new feature` : `no unfinished feature ${slugArg}`, isError: true };
694
+ const gi = ghostInfo(root, slugArg);
695
+ return {
696
+ text: gi
697
+ ? `.dev-flow/${slugArg}/ exists but has no state.json (a ghost: ${gi.entries.join(", ") || "empty"}) — there is nothing to resume. ${gi.worktree ? `Its worktree/ must go first (flow start ${slugArg} names the cleanup)` : `flow start ${slugArg} --confirmed adopts it as a new feature${gi.plan ? ", its plan/ as the draft" : ", keeping its files"}`}`
698
+ : `no unfinished feature ${slugArg}`,
699
+ isError: true,
700
+ };
677
701
  }
678
702
  const prior = readClaim(root, slugArg);
679
703
  const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
@@ -0,0 +1,65 @@
1
+ /** dev-flow runtime — `--confirmed` means "the operator said it in chat" (gh#190). The gates cannot read the
2
+ * chat, so on its own the flag is the agent's word: a refused `start --ui` came straight back with
3
+ * `--confirmed`, and a plain start was upgraded to `--ui --confirmed` with nobody asked. The flow tool can
4
+ * count the operator's messages in the session, which is enough to refuse the two shapes seen:
5
+ *
6
+ * A. a gate asked for the operator's word (NEEDS-OPERATOR, or an "operator-granted" refusal) and the same
7
+ * gate is re-run with --confirmed before any operator message arrived;
8
+ * B. a feature started in this session gets a mode flag (--ui/--patch/--docs) granted with --confirmed
9
+ * before any operator message arrived after the start.
10
+ *
11
+ * It never decides what the operator meant — one message after the question is all it asks for. A
12
+ * session it cannot read (no session manager) is not checked. Pure module: no pi imports. */
13
+ import { NEEDS_OPERATOR } from "../core.ts";
14
+
15
+ /** Operator messages in a session branch, or null when the branch cannot be read. */
16
+ export function operatorMessageCount(entries: readonly unknown[] | null | undefined): number | null {
17
+ if (!Array.isArray(entries)) return null;
18
+ let n = 0;
19
+ for (const e of entries) {
20
+ // SAFETY: narrow structural view of the SessionEntry union; only a user message is counted
21
+ const m = e as { type?: string; message?: { role?: string } };
22
+ if (m.type === "message" && m.message?.role === "user") n++;
23
+ }
24
+ return n;
25
+ }
26
+
27
+ export interface GrantLedger {
28
+ /** per session: the gate that last asked for the operator's word, and the operator-message count then */
29
+ asked: Map<string, { sub: string; users: number }>;
30
+ /** per session + slug: the operator-message count when start created the feature */
31
+ started: Map<string, number>;
32
+ }
33
+
34
+ export const newGrantLedger = (): GrantLedger => ({ asked: new Map(), started: new Map() });
35
+
36
+ const ASKS_FOR_WORD = /operator-granted|operator's (?:explicit )?word|the operator must grant/;
37
+ const MODE_FLAGS = ["--ui", "--patch", "--docs"];
38
+ const slugOf = (args: readonly string[]) => args.slice(1).find((a) => !a.startsWith("--")) ?? "";
39
+
40
+ /** The refusal for a `--confirmed` no operator message stands behind, or null when the call may run. */
41
+ export function grantCheck(args: readonly string[], key: string, users: number | null, ledger: GrantLedger): string | null {
42
+ if (users === null || !args.includes("--confirmed")) return null;
43
+ const sub = args[0] ?? "";
44
+ const asked = ledger.asked.get(key);
45
+ if (asked && asked.sub === sub && users <= asked.users)
46
+ return `${NEEDS_OPERATOR} no operator message since flow ${sub} asked for their word — --confirmed records the operator's answer in chat, it is not yours to give: ask in chat, stop, and re-run with --confirmed once they reply (gh#190)`;
47
+ if (sub === "start" && args.some((a) => MODE_FLAGS.includes(a))) {
48
+ const at = ledger.started.get(`${key}\u0000${slugOf(args)}`);
49
+ if (at !== undefined && users <= at)
50
+ return `${NEEDS_OPERATOR} ${args.filter((a) => MODE_FLAGS.includes(a)).join(" ")} on ${slugOf(args)} is operator-granted, and the operator has said nothing since it started — ask them in chat whether to turn it on, stop, and re-run with --confirmed once they reply (gh#190)`;
51
+ }
52
+ return null;
53
+ }
54
+
55
+ /** Note what a flow call's result means for later grants. */
56
+ export function grantRecord(args: readonly string[], key: string, users: number | null, res: { text: string; isError?: boolean }, ledger: GrantLedger): void {
57
+ if (users === null) return;
58
+ const sub = args[0] ?? "";
59
+ if (res.isError && (res.text.startsWith(NEEDS_OPERATOR) || ASKS_FOR_WORD.test(res.text))) {
60
+ ledger.asked.set(key, { sub, users });
61
+ return;
62
+ }
63
+ if (!res.isError && ledger.asked.get(key)?.sub === sub) ledger.asked.delete(key);
64
+ if (!res.isError && sub === "start" && /\bstarted at stage\b/.test(res.text)) ledger.started.set(`${key}\u0000${slugOf(args)}`, users);
65
+ }
@@ -94,11 +94,14 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
94
94
  writeDevPorts(root, { ...readDevPorts(root), [slotKey(devPortOf(state!, cfg))]: { slug: state!.slug, head, at: now() } });
95
95
  }
96
96
  const ran = [branchLine, ...did].join("; ");
97
- // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
97
+ // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones.
98
+ // A re-verify at pre-release (gh#187) exists to put the new tree in front of the operator: a yolo given
99
+ // before those commits existed never answers it.
100
+ const reverify = state!.stage === "pre-release";
98
101
  const yoloWord = takeYoloWord(state!);
99
102
  if (yoloWord) return { text: yoloWord, isError: true };
100
- let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
101
- const askPending = !flag("confirmed") && !state!.yolo;
103
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo && !reverify ? " (yolo: pre-confirmed)" : "";
104
+ const askPending = !flag("confirmed") && (!state!.yolo || reverify);
102
105
  if (askPending) {
103
106
  markPendingAsk(root, state!, "Verified?"); // pending however it is asked — a chat question or a dialog
104
107
  // the agent's call never opens a dialog (#181): this is the review deploy — the app is up for the
@@ -106,13 +109,13 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
106
109
  if (!ui.hasUI) {
107
110
  const port = devPortOf(state!, cfg);
108
111
  const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : "live app re-probed for review";
109
- return { text: `${needsOperator(`${what} — the app stays up until you answer`, "Verified?", "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.")}\n${ran}` };
112
+ return { text: `${needsOperator(`${what}${reverify ? ` — a re-verify over the review fixes since ${state!.verifiedHead?.slice(0, 7) ?? "the last Verified?"}` : ""} — the app stays up until you answer`, "Verified?", "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.")}\n${ran}` };
110
113
  }
111
114
  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?`);
112
115
  if (!ok) {
113
116
  delete state!.pendingAsk;
114
117
  writeState(root, state!);
115
- return { text: "verification declined — stay in implement and fix what failed" };
118
+ return { text: `verification declined — stay in ${reverify ? "pre-release" : "implement"} and fix what failed` };
116
119
  }
117
120
  audit = " (confirmed in dialog)";
118
121
  }
@@ -126,9 +129,12 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
126
129
  const vHead = await sh("git rev-parse HEAD", gateCwd(root, state!));
127
130
  if (vHead.ok && vHead.out.trim()) state!.verifiedHead = vHead.out.trim();
128
131
  else delete state!.verifiedHead;
132
+ const before = state!.stage;
129
133
  state!.stage = "pre-release";
130
134
  delete state!.pendingAsk;
131
135
  writeState(root, state!);
136
+ if (before === "pre-release")
137
+ return { text: `re-verified${audit} over ${state!.verifiedHead?.slice(0, 7) ?? "the current tree"} — the Verified? word now covers the review fixes; still in pre-release.\n${ran}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
132
138
  return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
133
139
  }
134
140
 
@@ -232,21 +238,31 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
232
238
  // #162: Verified? was answered over one tree; commits after it ship under that word unless someone says
233
239
  // so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
234
240
  let postVerify = "";
241
+ let unverifiedChange = false;
235
242
  if (state!.verifiedHead) {
236
243
  // gh#180: upstream work merged in after the verdict was approved on its own branch — only the branch's
237
244
  // own commits are news to the operator; the merged-in ones are a count, not a list to wade through
238
245
  const d = cfg.defaultBranch;
239
246
  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 : "";
240
- const since = await sh(`git log --oneline --no-decorate ${upstream ? "--no-merges " : ""}${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`, wtCwd);
241
- const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
247
+ const range = `${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`;
248
+ // one record per commit: "<sha> <subject>" then the files it touched (\x1e starts a record)
249
+ const since = await sh(`git log --no-decorate --name-only --format=%x1e%h%x20%s ${upstream ? "--no-merges " : ""}${range}`, wtCwd);
250
+ const commits = since.ok
251
+ ? since.out.split("\x1e").map((rec) => rec.split("\n").map((l) => l.trim()).filter(Boolean)).filter((r) => r.length).map(([line, ...files]) => ({ line, files }))
252
+ : [];
242
253
  const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
243
254
  const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
244
- // a release-only flow commits its bump and changelog after verify by design — only other files count
255
+ // gh#187: the release-prep commit (the bump, the changelog entry, whatever else the bump rewrites — an
256
+ // image tag in a compose file) lands after Verified? by design and no container verdict could cover
257
+ // it. It is the commit that touches the version file, or one that touches nothing but prep files.
245
258
  const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
246
- const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
247
- const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
248
- if (commits.length && !prepOnly)
249
- 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`;
259
+ const isPrep = (c: { files: string[] }) => (!!cfg.versioning.file && c.files.includes(cfg.versioning.file)) || (c.files.length > 0 && c.files.every((f) => prepFiles.has(f)));
260
+ const prep = commits.filter(isPrep);
261
+ const changed = commits.filter((c) => !isPrep(c));
262
+ // changed code shipping under an earlier word is friction the closing reflection should look at
263
+ unverifiedChange = changed.length > 0;
264
+ if (changed.length)
265
+ postVerify = `${changed.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${changed.slice(0, 6).map((c) => c.line).join(" | ")}${changed.length > 6 ? ` …(${changed.length - 6} more)` : ""}${prep.length ? ` (release prep ${prep.map((c) => c.line.split(" ")[0]).join(", ")} not counted)` : ""}${mergedIn ? ` (+${mergedIn} merged in from ${upstream}, not listed)` : ""} — the verify verdict does not cover them: if behaviour changed, re-run flow verify (at pre-release it redeploys and re-asks Verified? over the current tree) before Release?, and either way say in the PR body which commit the verdict was given over`;
250
266
  }
251
267
  // a standing yolo (given at an earlier checkpoint) stops short of Release? when the playbook says so, or
252
268
  // when commits landed after Verified? — the word was given before those commits existed (gh#176).
@@ -274,6 +290,7 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
274
290
  audit = " (confirmed in dialog)";
275
291
  }
276
292
  if (noVersion) state!.noVersion = true;
293
+ if (unverifiedChange) state!.friction = (state!.friction ?? 0) + 1;
277
294
  state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
278
295
  state!.approvals["pre-release"] = now();
279
296
  state!.stage = "release";
@@ -294,6 +311,66 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
294
311
  return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}${postVerify ? ` Warning: ${postVerify}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
295
312
  }
296
313
 
314
+ /** How long release-done waits on the publish CI a tag push started; a seam so tests run in milliseconds. */
315
+ export const artifactWait = {
316
+ budgetMs: 15 * 60_000,
317
+ pollMs: 20_000,
318
+ /** a tag pushed seconds ago may not have a run yet: look this long before deciding there is none */
319
+ appearMs: 60_000,
320
+ sleep: (ms: number) => new Promise<void>((r) => setTimeout(r, ms)),
321
+ clock: () => Date.now(),
322
+ runs: (tag: string, root: string): Promise<TagRun[] | null> => tagRuns(tag, root),
323
+ };
324
+
325
+ export interface TagRun { status: string; conclusion: string; url: string; workflowName: string }
326
+
327
+ /** The workflow runs a tag push started (GitHub names the tag as the run's branch); null when gh cannot say. */
328
+ async function tagRuns(tag: string, root: string): Promise<TagRun[] | null> {
329
+ const r = await sh(`gh run list --branch ${sq(tag)} --event push --limit 20 --json status,conclusion,url,workflowName`, root, 30_000);
330
+ if (!r.ok) return null;
331
+ try {
332
+ const rows = JSON.parse(r.out) as TagRun[];
333
+ return Array.isArray(rows) ? rows : null;
334
+ } catch {
335
+ return null;
336
+ }
337
+ }
338
+
339
+ /** Probe the release artifact; when it is missing and the tag's CI is still running, wait for that CI
340
+ * (bounded) and probe again. `waited` says what the wait saw, for the gate's note or its refusal. */
341
+ export async function awaitArtifact(cmd: string, tag: string, root: string): Promise<{ ok: boolean; out: string; waited: string }> {
342
+ const start = artifactWait.clock();
343
+ const mins = () => `${Math.max(1, Math.round((artifactWait.clock() - start) / 60_000))} min`;
344
+ let greenAt: number | null = null; // a registry can answer "not found" for a minute after the run that pushed to it went green
345
+ for (let round = 0; ; round++) {
346
+ const art = await sh(cmd, root);
347
+ if (art.ok) return { ...art, waited: round ? `after waiting ${mins()} for the publish CI ${tag} started` : "" };
348
+ const runs = await artifactWait.runs(tag, root);
349
+ if (runs === null) return { ...art, waited: "" }; // gh cannot say: the plain probe result stands
350
+ const elapsed = artifactWait.clock() - start;
351
+ const pending = runs.filter((r) => r.status !== "completed");
352
+ if (!runs.length && elapsed >= artifactWait.appearMs)
353
+ return { ...art, waited: `no CI run was started by ${tag} — publish by hand, or check that the publish workflow triggers on tags` };
354
+ if (runs.length && !pending.length) {
355
+ const failed = runs.filter((r) => r.conclusion !== "success" && r.conclusion !== "skipped" && r.conclusion !== "neutral");
356
+ if (!failed.length && greenAt === null) greenAt = artifactWait.clock();
357
+ if (!failed.length && artifactWait.clock() - (greenAt ?? 0) < artifactWait.appearMs) {
358
+ await artifactWait.sleep(artifactWait.pollMs);
359
+ continue;
360
+ }
361
+ return {
362
+ ...art,
363
+ waited: failed.length
364
+ ? `the CI ${tag} started did not pass — ${failed.map((r) => `${r.workflowName}: ${r.conclusion || "?"} (${r.url})`).join(", ")}; fix and re-publish, then re-run release-done`
365
+ : `every CI run ${tag} started finished green, yet the artifact is missing — check where the publish workflow pushes`,
366
+ };
367
+ }
368
+ if (elapsed >= artifactWait.budgetMs)
369
+ return { ...art, waited: `the publish CI is still running after ${mins()} (${pending.map((r) => `${r.workflowName}: ${r.url}`).join(", ")}) — re-run release-done once it finishes` };
370
+ await artifactWait.sleep(artifactWait.pollMs);
371
+ }
372
+ }
373
+
297
374
  export async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
298
375
  const { root, sess, cfg, flag, slugArg } = o;
299
376
  const { state, err } = needState(root, sess, slugArg);
@@ -331,9 +408,11 @@ export async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
331
408
  if (flag("no-artifact-check")) artNote = "Artifact check skipped (--no-artifact-check).";
332
409
  else {
333
410
  const cmd = cfg.release.artifact.replaceAll("{version}", manifestVer!).replaceAll("{tag}", expectedTag);
334
- const art = await sh(cmd, root);
335
- if (art.ok) artNote = `Artifact verified for ${manifestVer}.`;
336
- else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
411
+ // the tag push is what starts the publish CI: a miss right after it is usually "not yet" — only a
412
+ // tag that is really on the forge has a run worth waiting for (gh#179)
413
+ const art = forgeName === "github" && !errs.length ? await awaitArtifact(cmd, expectedTag, root) : { ...(await sh(cmd, root)), waited: "" };
414
+ if (art.ok) artNote = `Artifact verified for ${manifestVer}${art.waited ? ` ${art.waited}` : ""}.`;
415
+ else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}${art.waited ? `\n${art.waited}` : ""}`);
337
416
  }
338
417
  }
339
418
  // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
@@ -530,7 +609,8 @@ export async function gateFinishCore(o: GateCtx): Promise<RunResult> {
530
609
  // --no-reflect skips it; yolo never does (it answers checkpoints, it does not waive the review).
531
610
  const skipReflect = flag("no-reflect");
532
611
  if (skipReflect && !flag("confirmed")) return { text: "--no-reflect is the operator's word — ask them whether to skip the closing reflection, then re-run with --no-reflect --confirmed", isError: true };
533
- // a flow that never hit a refusal or a guard block, with no friction note from the operator, has nothing
612
+ // a flow that never hit a refusal, a guard block or a change shipped after Verified?, with no friction note
613
+ // from the operator, has nothing
534
614
  // for the reflection worker to find — skip the worker run unless the playbook says reflect = always
535
615
  const note = flagValue(o.rest, "note") ?? "";
536
616
  const quiet = !state!.reflectedAt && !skipReflect && cfg.release.reflect !== "always" && !(state!.friction ?? 0) && !note.trim();
@@ -538,7 +618,7 @@ export async function gateFinishCore(o: GateCtx): Promise<RunResult> {
538
618
  state!.reflectedAt = now();
539
619
  writeState(root, state!);
540
620
  }
541
- const quietNote = quiet ? " closing reflection skipped: no refusals or guard blocks this flow (playbook reflect = always runs it anyway)." : "";
621
+ const quietNote = quiet ? " closing reflection skipped: no refusals, guard blocks or unverified changes this flow (playbook reflect = always runs it anyway)." : "";
542
622
  if (!state!.reflectedAt && !skipReflect) {
543
623
  const skipHint = "or — only on the operator's explicit word — flow finish --no-reflect --confirmed";
544
624
  if (!o.hooks.reflect) return { text: `finish: no reflection recorded for ${state!.slug} and no reflect worker available here — run flow_stage(op: "reflect") first, ${skipHint}`, isError: true };