pi-dev-flow 0.53.2 → 0.55.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,25 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.55.0] - 2026-10-22
8
+
9
+ ### Changed
10
+
11
+ - **A stale session build is a question at `flow release`, not a stop.** Gates execute the dev-flow build the session loaded at start, and the checkout moves past it with every release — and shipping from behind had already cost releases: 0.53.0 and 0.53.1 were both published under 0.52.2 code (so #97's changelog proofs never fired and the release pages took tag annotations), and the 0.54.0 release itself ran under loaded 0.53.0, so its own new proofs (merge shape, artifact freshness) never fired in-session. The old answer was prose — *stop and ask the operator to `/reload` before publishing* — a refusal with no gate behind it, and a refusal is the wrong shape: publishing under an older gate is a legitimate operator choice (hotfix, offline reload), exactly the emergency the relaxed modes exist for. Now, when the loaded build is **behind** the checkout's, `flow release` prints both builds, lists the changelog versions that shipped between them (the proofs that will not run this release), and folds *update (`/reload`, then re-run) or proceed with the old release?* into the Release? question — still exactly one checkpoint. The decision is stamped into the release (`staleBuild`) and `release-done` repeats the acknowledgement in place of its bare after-the-fact warning, which stays as the backstop for headless runs; a session build **ahead** of the checkout's manifest is asked nothing, because no proof is missing there. `DEV_FLOW_LOADED_VERSION` lets the smoke suite stand in for an old session — the override can only ever make a gate more cautious, never lift a proof.
12
+
13
+ ## [0.54.0] - 2026-10-22
14
+
15
+ ### Added
16
+
17
+ - **The playbook says how a merged PR lands, and the gates hold it to that.** Every repo has a merge style; almost none has ever written it down, so the answer was whatever the last click chose — and dev-flow could only react afterwards, asking at `flow finish` whether commits missing from the default branch were a squash merge. `merge = squash | merge | rebase` (or `any` for "no policy, stop asking") now lives under `## release`, and four places read it. **`flow init` suggests it from your own history** — a first-parent log counts merge commits against `(#NN)` squash commits and asks with that evidence (`merge history: 17 merge commit(s), 6 squash(es) — the most recent PR landed as merge`) instead of asking blind. **`flow start` asks once and writes the answer**: while the key is unset the gate refuses with the question, the suggestion and the exact re-run, and `flow start <slug> --merge=<style> --confirmed` inserts one line into `## release` — a surgical insert, not a draft regeneration, so hand-written prose and checklist items cannot be dropped, validated before the write with `.bak` kept, committed as the playbook chore only when the playbook is the only dirty path. **The guard enforces the style where the decision is made**: `gh pr merge --squash` against `merge = merge` is a hard block, a merge carrying no style flag (the forge default decides) needs the operator, and a local `git merge --squash` only ever confirms, because folding main into a branch is ordinary work. **`release-done` proves what actually shipped** matched it — branch ancestry for `merge`, plus what the forge itself reports (`gh pr list --json squashCommit,rebaseCommit,mergeCommit`, GitLab through `glab api`) for the two styles that erase ancestry — so a squash under a merge policy refuses to record the release, while a shape dev-flow cannot see (`forge = self`, no CLI, unfetched branch) prints an advisory instead: an invisible topology never blocks a legal release. Only a human clicking the button in the Web UI stays beyond its reach — that needs the forge's own require-a-merge-strategy setting, and docs say so plainly.
18
+ - **`flow start` preflights before it creates anything.** It warns when this session runs an older dev-flow build than the checkout (the gates execute the loaded code, so `/reload` first), prints the playbook gaps `flow doctor` would report instead of promising them later, and stamps the build as before. `flow start --check-upstream` and `flow version --check-upstream` add the published npm version, opt-in so both stay instant and offline by default.
19
+
20
+ ### Changed
21
+
22
+ - **`flow finish` reads unmerged-looking commits against the policy**: commits that never reached the default branch are *expected* under `squash`/`rebase` instead of a shrug, and a **violation** under `merge` — one `yolo` cannot answer for, only the operator can. The verdict needs measurable ancestry, so a local-only repo is never accused of squashing.
23
+ - **`flow doctor` gains two findings**: a playbook with no merge policy (the one knob a repo can silently lack), and a `squash`/`rebase` policy on `forge = self`, which is unprovable by construction.
24
+ - The release hint and the skill now spell the playbook's style at the stage where the PR is merged (`gh pr merge --squash`), and the guard-rule examples in the docs no longer claim "PRs squash-merge" — this repo merge-commits, and an example that contradicts the playbook it documents teaches the wrong lesson.
25
+
7
26
  ## [0.53.2] - 2026-10-22
8
27
 
9
28
  ### Fixed
package/README.md CHANGED
@@ -57,7 +57,8 @@ package — so keep the one you actually update from.
57
57
  Then, once per project repo, `/flow init`. It reads the repo (default branch and forge from git,
58
58
  package manager, test/build/run conventions, version manifest) and writes **`.dev-flow/project.md`
59
59
  — your playbook**: the commands that count as checks, the manual checklist, the version and tag
60
- convention, and any hard safety rules of your own. It asks about everything detection could not
60
+ convention, how a merged PR lands (`merge = squash | merge | rebase`), and any hard safety rules of your
61
+ own. It asks about everything detection could not
61
62
  decide (self-hosted forge? Docker artifacts? what "healthy" means?) and installs a `pre-commit` hook
62
63
  that blocks direct main commits. Run `/flow init` again later and it becomes a **doctor**: drift in
63
64
  your playbook, dead commands, config problems — it never rewrites your hand edits without asking.
package/docs/gates.md CHANGED
@@ -9,21 +9,21 @@ so it needs no `--confirmed`.
9
9
 
10
10
  | Gate | Advances | Refuses unless |
11
11
  |---|---|---|
12
- | `start <slug> [--ui] [--patch|--docs --confirmed]` | → plan | slug is new (binds the session); relaxed modes are operator-granted in chat, anchored by `--confirmed`: `--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>`) |
12
+ | `start <slug> [--ui] [--patch|--docs --confirmed] [--merge=squash\|merge\|rebase\|any] [--check-upstream]` | → plan | slug is new (binds the session); relaxed modes are operator-granted in chat, anchored by `--confirmed`: `--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 |
13
13
  | `use <slug>` | — (binds this session to a feature) | slug unfinished |
14
14
  | `approve [--yolo]` | plan → implement (creates worktree + branch) | `plan/*.md` exists; if `--ui`, rendered mockup screenshots (per `mockupGlobs`, default `*.png`) exist under `plan/` — headless chromium renders embedded in plan.md; **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)` |
15
15
  | `test` | records a check | — (runs the `test` command/check, records pass/fail) |
16
16
  | `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
17
  | `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
18
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 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 — 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`), 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
- | `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; 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 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`** (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 |
20
- | `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 |
21
- | `finish [--yolo] [slug]` | release → done (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; **one question** (Finish? — mentions unmerged-looking squash-merge commits, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; to abandon an unreleased feature use `abort` |
19
+ | `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; 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 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`** (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
+ | `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 |
21
+ | `finish [--yolo] [slug]` | release → done (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; **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` |
22
22
  | `reflect ["<note>"]` | — | `reflect "<note>"` queues a suggestion in `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). Bare `reflect` prints the full **session-reflection protocol** for the agent (from the `/flow reflect` bar it additionally wakes the model, so the protocol executes immediately): review the whole session log, re-check every open item against the current playbook and **newer dev-flow versions** (`npm view pi-dev-flow version` vs the running version — dev-flow ships from npm; recommend `pi install npm:pi-dev-flow` + `/reload`, the operator performs updates), dedupe new findings against the open ones, then report playbook vs plugin items to the operator and ask whether to fix now — plugin items: search upstream issues first (`gh issue list --repo <upstream> --state all --search …`; an author-addressed match is reported back, no match → `gh issue create` with a detailed description and a suggested fix), playbook items: `flow doctor` routes each to the docs flow that implements it |
23
23
  | `roadmap [add "<feature>" \| 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, `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it — **`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 |
24
24
  | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — **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). 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 |
25
25
  | `status [slug]` / `abort [slug]` | — | — |
26
26
  | `help` (`--help`, `-h`) | — | — (prints the gate help — answerable in any repo, at any stage, with no `.dev-flow/`) |
27
- | `version` | — | — (prints dev-flow's **own** version and the directory it was loaded from — which copy this session runs, this checkout vs an installed `pi-dev-flow`; when the checkout has moved past the build this session loaded it says so and names both, because the gates execute the loaded code — `/reload` to run the newer one; answerable in any repo, at any stage, with no `.dev-flow/`) |
27
+ | `version [--check-upstream]` | — | — (prints dev-flow's **own** version and the directory it was loaded from — which copy this session runs, this checkout vs an installed `pi-dev-flow`; when the checkout has moved past the build this session loaded it says so and names both, because the gates execute the loaded code — `/reload` to run the newer one; `--check-upstream` adds the published npm version; answerable in any repo, at any stage, with no `.dev-flow/`) |
28
28
 
29
29
  `--confirmed` is the operator-presence flag: pass it only after the operator literally answered the stage question in chat — one checkpoint per stage, no second dialog.
package/docs/headless.md CHANGED
@@ -38,5 +38,8 @@ The contract a headless driver (a session with no UI) relies on:
38
38
  - **Edits invalidate checks.** Any worktree write clears recorded checks and the tier-2
39
39
  confirmation — re-run `flow check` before `verify` after the last edit.
40
40
  - **Version skew.** Gates execute the dev-flow build the session loaded at start; `flow version`
41
- reports when the checkout has moved ahead of it (and `release-done` stamps a warning into
42
- its output when the session shipped from behind) — reload the session before publishing.
41
+ reports when the checkout has moved ahead of it. `flow release` turns the skew into a question —
42
+ update (`/reload`, then re-run) or proceed with the old release — never a block: publishing under
43
+ an older gate is a legitimate choice. The operator's proceed is stamped into the release and
44
+ `release-done` repeats the acknowledgement (its after-the-fact warning stays for a release that
45
+ went out without the question being answered).
package/docs/playbook.md CHANGED
@@ -49,9 +49,9 @@ adopting dev-flow can delete its own guard extension:
49
49
  ````markdown
50
50
  ## global
51
51
  ```flow-guard
52
- deny \bgit\b[^\n]*\bpush\b[^\n]*--force(?!\w) :: history stays linear — PRs squash-merge
52
+ deny \bgit\b[^\n]*\bpush\b[^\n]*--force(?!\w) :: history stays linear — the playbook sets the merge style
53
53
  deny \bgit\b[^\n]*\bworktree\s+prune\b :: it prunes other sessions' worktrees
54
- confirm \bgit\b[^\n]*\bbranch\s+(?:-D\b|--delete\b) :: deletes a squash-merged branch git cannot see as merged
54
+ confirm \bgit\b[^\n]*\bbranch\s+(?:-D\b|--delete\b) :: deletes a merged branch git cannot see as merged
55
55
  confirm \bdocker\b[^\n]*\bcompose\b[^\n]*\brestart\b :: drops a permanent upstream connection
56
56
  protect docker/.env* :: gitignored live secrets — and any backup copied beside them
57
57
  forbid docker/secrets :: gitignored secret storage
@@ -108,13 +108,42 @@ ran, verify re-runs the health probe (`commands.health` or a `flow-check` block
108
108
  build" means stays the project's own assertion: the probe runs with the worktree as cwd, so it can
109
109
  wait for readiness and compare the served build stamp with `git rev-parse HEAD`. No probe → the
110
110
  gate prints `health: none configured` and `flow doctor` flags the combination. The pre-release and release stages take
111
- `versionFile`/`versionTag` (defaults `v{version}`; accepted under either section). `## global` also takes
111
+ `versionFile`/`versionTag` (defaults `v{version}`; accepted under either section) and
112
+ `merge = squash | merge | rebase | any` — how a merged PR lands on the default branch (see below). `## global` also takes
112
113
  `forge = github | gitlab | self` — the release machinery's target; when unset it is detected from the
113
114
  `origin` URL at the moment of use (GitHub gets `gh`, GitLab gets `glab`, self-hosted stays forge-neutral:
114
115
  no automatic release creation, merge proof by ancestry only), and `release.releases = false` skips
115
116
  automatic release creation entirely (the legacy `github` key still parses, with a rename warning).
116
117
  A leftover `project.json` is no longer read — the doctor tells you to fold it in and delete it.
117
118
 
119
+ ### The merge policy (`merge = squash | merge | rebase | any`)
120
+
121
+ The one knob a repo can silently lack: a squash and a merge commit look identical right up until someone
122
+ needs to know which one the release contains. Three things read the key:
123
+
124
+ | policy | `main` gains | provable with git alone |
125
+ |---|---|---|
126
+ | `merge` | a merge commit plus the branch's own commits | **yes** — the branch is an ancestor of `origin/<default>` |
127
+ | `squash` | one new commit | no — ask the forge (`gh`/`glab`) |
128
+ | `rebase` | the branch's commits, replayed with new SHAs | no — same |
129
+
130
+ - **`flow init` asks** with evidence from your own history (`merge history: 6 merge commit(s), 3 squash(es)
131
+ — the most recent PR landed as squash`), and **`flow start` refuses until it is set**: the agent asks you
132
+ in chat, re-runs with `--merge=<style> --confirmed`, and the answer is inserted as a single line under
133
+ `## release` (validated before the write, `.bak` kept, committed as a playbook chore when the playbook is
134
+ the only dirty path). `any` is the explicit opt-out: no policy, no asking.
135
+ - **the guard enforces it where the decision is made** — `gh pr merge --squash` against `merge = merge` is
136
+ blocked outright, and a merge that carries no style flag (so the forge default decides) needs your
137
+ confirmation; a local `git merge --squash` only ever confirms, because merging main into a branch is
138
+ ordinary work.
139
+ - **`release-done` proves what actually landed** matched the policy (branch ancestry plus what the forge
140
+ reports), and `flow finish` says whether commits missing from the default branch are expected (squash,
141
+ rebase) or a violation (merge — where `yolo` does not answer for you). A shape dev-flow cannot see —
142
+ `forge = self`, no CLI, an unfetched branch — prints an advisory instead of refusing a legal release.
143
+
144
+ What it cannot do is bind a human clicking the merge button in the Web UI: only the forge's own
145
+ require-a-merge-strategy setting does that, and setting it stays your step in the forge, not dev-flow's.
146
+
118
147
  `flow init` is the dialogue around this file: **fresh repo** → prints the setup brief (detection report
119
148
  plus one question per undetected knob — forge, version convention, releases, artifacts, checks, prose),
120
149
  the agent asks you each question, fills the draft and writes your answers back validated
@@ -32,6 +32,7 @@ import {
32
32
  appendRoadmapItem,
33
33
  bashFlowGuard,
34
34
  changelogEntry,
35
+ changelogVersionsBetween,
35
36
  normalizeReleaseBody,
36
37
  pendingEntryLines,
37
38
  pickReleaseNotes,
@@ -39,6 +40,7 @@ import {
39
40
  checklistPending,
40
41
  checkoutTarget,
41
42
  claimBlocks,
43
+ classifyMergeHistory,
42
44
  cmpVersions,
43
45
  cleanupAssess,
44
46
  compactionReflectionLine,
@@ -54,6 +56,9 @@ import {
54
56
  guardPath,
55
57
  healthProbe,
56
58
  healthRetry,
59
+ mergeShapeProof,
60
+ mergeStyleInvocation,
61
+ parseMergeStyle,
57
62
  investigationBrief,
58
63
  parseLsRemoteTags,
59
64
  parsePushRefs,
@@ -103,14 +108,19 @@ import {
103
108
  type PushRef,
104
109
  type SessionClaim,
105
110
  } from "../src/core.ts";
106
- import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd } from "../src/projectmd.ts";
111
+ import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
107
112
  import { bashTimeout, requireTimeout } from "../src/timeouts.ts";
108
113
  import { detectProject } from "../src/detect.ts";
109
114
 
110
115
  const execAsync = promisify(exec);
111
116
 
112
- /** The dev-flow build this session actually loaded — see sessionRunsOlderBuild. */
113
- const LOADED_VERSION = pluginVersion(import.meta.dirname).version;
117
+ /** The dev-flow build this session actually loaded — see sessionRunsOlderBuild. Read at call time, and
118
+ * DEV_FLOW_LOADED_VERSION can stand in for it (the smoke suite runs gates in-process and needs to
119
+ * pretend it is an old session): the override can only ever make a gate more cautious — it never
120
+ * lifts a proof, it turns a release into a warn-and-ask. */
121
+ function loadedVersion(): string | null {
122
+ return process.env.DEV_FLOW_LOADED_VERSION?.trim() || pluginVersion(import.meta.dirname).version;
123
+ }
114
124
 
115
125
  interface Ui {
116
126
  hasUI: boolean;
@@ -135,6 +145,81 @@ async function sh(command: string, cwd: string): Promise<{ ok: boolean; out: str
135
145
 
136
146
  const dfDir = (root: string) => path.join(root, ".dev-flow");
137
147
 
148
+ /** A `--merge=squash` style flag, or null when absent. Returned as the raw string: the caller validates it
149
+ * with parseMergeStyle so a typo is reported instead of ignored. */
150
+ function flagValue(rest: string[], name: string): string | null {
151
+ for (const a of rest) {
152
+ const m = a.match(new RegExp(`^--${name}=(.+)$`));
153
+ if (m) return m[1];
154
+ }
155
+ return null;
156
+ }
157
+
158
+ /** One cheap first-parent log tells the operator what their repo actually does when a PR merges: merge
159
+ * commits or one squashed commit per PR. `flow init` and `flow start` ask with this evidence instead of
160
+ * asking blind; null when there is no default-branch log to read. */
161
+ async function mergeHistoryEvidence(root: string, defaultBranch: string): Promise<{ note: string; recent: "squash" | "merge" | "rebase" | null } | null> {
162
+ const log = await sh(`git log --first-parent -n 40 --format=%p|%s ${sq(`origin/${defaultBranch}`)} 2>/dev/null || git log --first-parent -n 40 --format=%p|%s ${sq(defaultBranch)} 2>/dev/null`, root);
163
+ if (!log.ok || !log.out.trim()) return null;
164
+ const c = classifyMergeHistory(log.out.split("\n"));
165
+ return { note: c.note, recent: c.recent };
166
+ }
167
+
168
+ /** How the forge says the PR landed, when it can be asked — the only way to tell a squash from a rebase,
169
+ * because both erase the branch's ancestry. null = unaskable (self-hosted, no CLI, no merged PR found). */
170
+ async function forgeMergeStyle(root: string, forge: string, branch: string): Promise<"squash" | "merge" | "rebase" | null> {
171
+ if (!branch) return null;
172
+ // sh() folds stderr into stdout, so a CLI error can arrive where the JSON was expected: parse defensively
173
+ const json = (out: string): unknown | null => {
174
+ try {
175
+ return JSON.parse(out);
176
+ } catch {
177
+ return null;
178
+ }
179
+ };
180
+ if (forge === "github") {
181
+ const pr = await sh(`gh pr list --state merged --head ${sq(branch)} --json number,squashCommit,rebaseCommit,mergeCommit --jq '.[0]'`, root);
182
+ if (!pr.ok || !pr.out.trim() || pr.out.trim() === "null") return null;
183
+ const parsed = json(pr.out.trim()) as { squashCommit?: string | null; rebaseCommit?: string | null; mergeCommit?: string | null } | null;
184
+ return parsed?.squashCommit ? "squash" : parsed?.rebaseCommit ? "rebase" : parsed?.mergeCommit ? "merge" : null;
185
+ }
186
+ if (forge === "gitlab") {
187
+ const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${branch}&state=merged&per_page=1`)}`, root);
188
+ if (!mr.ok || !mr.out.trim() || mr.out.trim() === "[]") return null;
189
+ const list = json(mr.out.trim()) as { squash_commit_sha?: string | null; merge_commit_sha?: string | null }[] | null;
190
+ const parsed = Array.isArray(list) ? list[0] : null;
191
+ return parsed?.squash_commit_sha ? "squash" : parsed?.merge_commit_sha ? "merge" : null;
192
+ }
193
+ return null;
194
+ }
195
+
196
+ /**
197
+ * Write the merge policy into the playbook with a single-line insert — never a draft regeneration, which
198
+ * cannot reproduce hand-written prose and checklist items and would drop them. Validated before it is
199
+ * written and kept as `.bak`, exactly like `flow init --write`. The commit is the playbook chore the guard
200
+ * already blesses, and only when the playbook is the only dirty path: a gate never sweeps someone else's
201
+ * work into a chore commit.
202
+ */
203
+ async function writePlaybookMergePolicy(root: string, style: string): Promise<{ note: string } | { err: string }> {
204
+ const mdFile = path.join(dfDir(root), "project.md");
205
+ if (!existsSync(mdFile)) return { err: "no .dev-flow/project.md to write the policy into — run flow init first" };
206
+ const ins = setPlaybookKey(readFileSync(mdFile, "utf8"), "release", "merge", style);
207
+ if ("error" in ins) return { err: ins.error };
208
+ const parsed = parseProjectMd(ins.text);
209
+ if (parsed.hard.length) return { err: `refusing to write project.md — the result would not parse:\n- ${parsed.hard.join("\n- ")}` };
210
+ copyFileSync(mdFile, `${mdFile}.bak`);
211
+ writeFileSync(mdFile, ins.text);
212
+ const dirty = await sh("git status --porcelain", root);
213
+ const onlyPlaybook = dirty.ok && dirty.out.trim().split("\n").every((l) => l.trim().endsWith(" .dev-flow/project.md"));
214
+ const tracked = (await sh("git ls-files --error-unmatch .dev-flow/project.md", root)).ok;
215
+ let note = `merge = ${style} written to .dev-flow/project.md (${ins.where}; previous copy kept as project.md.bak)`;
216
+ if (tracked && onlyPlaybook) {
217
+ const commit = await sh(`git add .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(`playbook: merge policy = ${style}`)}`, root);
218
+ note += commit.ok ? " — committed as a playbook chore" : ` — commit failed (${tail(commit.out)}); commit it yourself`;
219
+ } else note += `. ${GIT_TRACK_NOTE}`;
220
+ return { note };
221
+ }
222
+
138
223
  /**
139
224
  * Run the health probe with the playbook's wait budget (#42). A service whose readiness lags its
140
225
  * container start can never pass a single shot, and hand-writing a poll loop into every playbook was
@@ -162,7 +247,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
162
247
  }
163
248
 
164
249
  const GATE_HELP =
165
- "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui] [--force] [--patch|--docs --confirmed] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there); bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned)";
250
+ "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui] [--force] [--patch|--docs --confirmed] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — start preflights the playbook before creating anything: it prints playbook gaps and warns when the session runs an older dev-flow build, and it refuses until a merge policy is set (ask the operator squash / merge / rebase / any in chat, then re-run with --merge=<style> --confirmed — the answer is written into project.md and enforced from then on: gh/glab merges that contradict it are blocked, and release-done proves what actually landed); version prints the loaded build (--check-upstream also asks the registry for the published one) — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there); bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned); when the session runs an older dev-flow build than the checkout, release names both builds, lists what the running code can no longer prove, and asks the operator update (/reload) or proceed with the old release — an operator decision recorded in state and repeated by release-done, never a block";
166
251
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
167
252
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
168
253
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -450,9 +535,11 @@ function isSelfRepo(root: string): boolean {
450
535
  }
451
536
 
452
537
  /** The questions `flow init` asks before writing a playbook — detection fills what it can, the operator answers the rest (the agent relays them). */
453
- function setupQuestions(det: { partial: { defaultBranch: string; versioning?: { file: string }; forge?: string }; missing: string[] }): string[] {
538
+ function setupQuestions(det: { partial: { defaultBranch: string; versioning?: { file: string }; forge?: string; merge?: string }; missing: string[] }): string[] {
454
539
  const q = [det.partial.forge ? `git forge: detected "${det.partial.forge}" from the origin URL — github, gitlab or self-hosted? (global key forge)` : "git forge: no origin remote to detect from — github, gitlab or self-hosted? (global key forge)"];
455
540
  q.push(det.partial.versioning ? `version manifest: detected ${det.partial.versioning.file} — keep it? tag pattern v{version}?` : "versioning: no manifest found — which file holds the version (VERSION recommended), and the tag pattern?");
541
+ // the merge style is inferable from history and worth asking with that evidence: a repo almost always has one
542
+ q.push(`${det.partial.merge ? `${det.partial.merge} —` : "merge history: nothing to read a style from —"} how should a merged PR land on the default branch: squash, merge (a merge commit), rebase, or any (no policy)? it is written as merge = <style> under ## release and the gates enforce it.`);
456
543
  q.push("releases: should release-done create the forge release automatically via gh/glab (releases = yes), or is publishing manual (no)?");
457
544
  q.push("artifacts: do you publish anything to a registry (e.g. a container image to Docker Hub)? then release.artifact needs a verify command (e.g. docker buildx imagetools inspect <image>:{version}); the push itself belongs to ## release prose.");
458
545
  q.push(`tier-1 checks: ${det.missing.length ? `not detected: ${det.missing.join(", ")} —` : "detected test/build/run —"} which commands run tests, the build? any lint/typecheck? each extra becomes a flow-check block under ## implement.`);
@@ -480,7 +567,7 @@ function reflectNote(root: string, sess: Session, note: string[]): RunResult {
480
567
  async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Promise<RunResult> {
481
568
  const [sub = "status", ...rest] = args;
482
569
  // help and version are questions about the plugin, not the repo: answerable with no .dev-flow/ at all
483
- if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, LOADED_VERSION) : `usage: flow <sub> — ${GATE_HELP}` };
570
+ if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, loadedVersion()) : `usage: flow <sub> — ${GATE_HELP}` };
484
571
  if (!existsSync(dfDir(root)) && sub !== "init" && sub !== "version") return { text: "no .dev-flow/ in this repo — run flow init first", isError: true };
485
572
  const cfg = loadProject(dfDir(root)).cfg;
486
573
  const flag = (name: string) => rest.includes(`--${name}`);
@@ -505,6 +592,7 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
505
592
  const det = detectProject(root, branch);
506
593
  const origin = await sh("git remote get-url origin", root);
507
594
  det.partial.forge = origin.ok && origin.out.trim() ? detectForge(origin.out) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
595
+ det.partial.merge = (await mergeHistoryEvidence(root, branch))?.note; // "what do you actually do when a PR merges", read off the log
508
596
  const loaded = loadProject(dfDir(root));
509
597
  const draftFresh = buildDraft(det);
510
598
  const draftRefresh = buildDraft(det, loaded.cfg);
@@ -571,6 +659,11 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
571
659
  // doctor mode: cheap consistency probes only — never runs project commands
572
660
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
573
661
  findings.push(...(await gitConsistency(root, loaded.cfg)));
662
+ // a repo that never said how a PR merges gets the evidence next to the finding, so the answer is a choice and not a guess
663
+ if (!loaded.cfg.release.merge) {
664
+ const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
665
+ if (ev?.recent) findings.push(`${ev.note} — write it into the playbook: merge = ${ev.recent} under ## release (or let the next flow start ask and write it)`);
666
+ }
574
667
  for (const l of readReflections(root)) findings.push(`open reflection: ${l.slice(6)}`);
575
668
  if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
576
669
  else {
@@ -616,7 +709,7 @@ ${mdDigest(draftRefresh)}`))
616
709
  }
617
710
 
618
711
  case "start": {
619
- if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] (slug: lowercase, dashes); --patch/--docs are operator-granted modes — ask the operator in chat, then add --confirmed", isError: true };
712
+ if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs are operator-granted modes — ask the operator in chat, then add --confirmed", isError: true };
620
713
  if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
621
714
  // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
622
715
  if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
@@ -625,13 +718,52 @@ ${mdDigest(draftRefresh)}`))
625
718
  // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
626
719
  const curBr = await currentBranch(root);
627
720
  if (curBr !== cfg.defaultBranch && !flag("force")) return { text: `main checkout is on ${curBr}, not ${cfg.defaultBranch} — check out ${cfg.defaultBranch} first (git checkout ${cfg.defaultBranch} && git pull) or flow use an unfinished feature; --force to override`, isError: true };
628
- // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling
721
+ // --- preflight: is this session running the current build, and is the playbook complete? ---
722
+ const notes: string[] = [];
629
723
  const self = pluginVersion(import.meta.dirname);
724
+ const behind = sessionRunsOlderBuild(loadedVersion(), self.version);
725
+ if (behind) notes.push(`warning: this session runs dev-flow ${behind}, the checkout has ${self.version} — /reload before trusting what a gate prints`);
726
+ if (flag("check-upstream")) {
727
+ const pub = await sh("npm view pi-dev-flow version", root);
728
+ const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
729
+ notes.push(newest ? `published dev-flow: ${newest} (this build: ${self.version ?? "?"})${self.version && newest !== self.version ? " — an update is available" : ""}` : "could not read the published dev-flow version (offline?)");
730
+ }
731
+ // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
732
+ const gaps = doctorFindings(root, cfg, loadProject(dfDir(root)).md).filter((x) => !x.startsWith("no merge policy"));
733
+ if (gaps.length) notes.push(`playbook gaps (${gaps.length}) — advisory, flow doctor reviews and routes them:\n${gaps.slice(0, 5).map((g) => ` ${g}`).join("\n")}`);
734
+ // the merge policy is the one blocking gap: it decides the shape of the default branch and nobody can
735
+ // reconstruct it afterwards. Ask once in chat (a checkpoint word like any other), write the answer, continue.
736
+ const styleArg = flagValue(rest, "merge");
737
+ const style = styleArg === null ? null : parseMergeStyle(styleArg);
738
+ if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
739
+ // with no playbook at all there is nothing to ask about: writing the playbook is `flow init`'s job, and
740
+ // a repo that never ran init must not be refused a feature by a merge-policy question
741
+ const hasPlaybook = existsSync(path.join(dfDir(root), "project.md"));
742
+ if (!hasPlaybook) notes.push("no .dev-flow/project.md yet — flow init writes the playbook (it now asks for the merge policy too)");
743
+ if (hasPlaybook && (!cfg.release.merge || (style && style !== cfg.release.merge))) {
744
+ if (!style) {
745
+ const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
746
+ return {
747
+ text: needsOperator(
748
+ `the playbook has no merge policy — ask the operator how a merged PR should land on ${cfg.defaultBranch}: squash, merge (a merge commit), rebase, or any (no policy).${ev ? ` ${ev.note}${ev.recent ? ` Detected suggestion: ${ev.recent}.` : ""}` : ""} Then re-run: flow start ${slugArg} --merge=<style> --confirmed (the answer is written into .dev-flow/project.md)`,
749
+ "Merge policy?",
750
+ ),
751
+ isError: true,
752
+ };
753
+ }
754
+ if (!flag("confirmed")) return { text: `writing merge = ${style} changes the operator playbook — the operator must answer it in chat first, then re-run with --confirmed`, isError: true };
755
+ const written = await writePlaybookMergePolicy(root, style);
756
+ if ("err" in written) return { text: written.err, isError: true };
757
+ // the flow that just wrote the policy must see it: nextHint and the merge guard read this config
758
+ cfg.release.merge = style;
759
+ notes.push(written.note);
760
+ }
761
+ // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling
630
762
  const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), self.version ?? undefined);
631
763
  mkdirSync(path.join(featDir(root, slugArg), "plan"), { recursive: true });
632
764
  writeState(root, state);
633
765
  sess.bind(slugArg);
634
- return { text: `feature ${slugArg} started at stage plan (ui=${state.ui}${state.patch ? ", patch" : state.docs ? ", docs" : ""}${self.version ? `, dev-flow ${self.version}` : ""}).\n${nextHint(state, cfg)}` };
766
+ return { text: `feature ${slugArg} started at stage plan (ui=${state.ui}${state.patch ? ", patch" : state.docs ? ", docs" : ""}${self.version ? `, dev-flow ${self.version}` : ""}).${notes.length ? `\n${notes.join("\n")}` : ""}\n${nextHint(state, cfg)}` };
635
767
  }
636
768
 
637
769
  case "status": {
@@ -743,8 +875,14 @@ ${mdDigest(draftRefresh)}`))
743
875
  case "version": {
744
876
  // the plugin's own version — separate from the project's versioning.file version the release gates use
745
877
  const self = pluginVersion(import.meta.dirname);
746
- const behind = sessionRunsOlderBuild(LOADED_VERSION, self.version);
878
+ const behind = sessionRunsOlderBuild(loadedVersion(), self.version);
747
879
  const head = self.version ? `dev-flow ${self.version} (pi-dev-flow at ${self.dir})` : `dev-flow version unknown — no pi-dev-flow package.json above ${self.dir}`;
880
+ // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
881
+ if (flag("check-upstream")) {
882
+ const pub = await sh("npm view pi-dev-flow version", root);
883
+ const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
884
+ return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
885
+ }
748
886
  return { text: behind ? `${head} — but this session runs ${behind}; /reload to run ${self.version}` : head };
749
887
  }
750
888
 
@@ -969,10 +1107,32 @@ ${mdDigest(draftRefresh)}`))
969
1107
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
970
1108
  const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
971
1109
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
1110
+ // a stale session build is the operator's decision, never a block: publishing under an older gate is a
1111
+ // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1112
+ // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
1113
+ // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
1114
+ const selfBuild = pluginVersion(import.meta.dirname);
1115
+ const behind = sessionRunsOlderBuild(loadedVersion(), selfBuild.version);
1116
+ // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
1117
+ // has every proof the checkout would run, and asking about it would be noise.
1118
+ const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
1119
+ let staleAsk = "";
1120
+ let staleNote = "";
1121
+ if (stale) {
1122
+ const clPath = path.join(selfBuild.dir, "CHANGELOG.md");
1123
+ const missing = existsSync(clPath) && selfBuild.version ? changelogVersionsBetween(readFileSync(clPath, "utf8"), behind, selfBuild.version) : [];
1124
+ staleAsk =
1125
+ ` This session runs dev-flow ${behind}, the checkout ships ${selfBuild.version ?? "?"} — gate proofs shipped between the two will NOT run. ` +
1126
+ (missing.length
1127
+ ? `Shipped since ${behind}: ${missing.slice(0, 8).join(", ")}${missing.length > 8 ? ` …(${missing.length} total)` : ""} — see ${clPath}. `
1128
+ : `What shipped between them is not readable from the checkout's CHANGELOG.md — read it before deciding. `) +
1129
+ `Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
1130
+ staleNote = `released under dev-flow ${behind} (checkout ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
1131
+ }
972
1132
  const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
973
1133
  if (!flag("confirmed") && !state!.yolo) {
974
- if (!ui.hasUI) return { text: needsOperator("release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat", "Release?"), isError: true };
975
- const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${state!.noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${state!.noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.`);
1134
+ if (!ui.hasUI) return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}`, "Release?"), isError: true };
1135
+ const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${state!.noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${state!.noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}`);
976
1136
  if (!ok) return { text: "release declined — keep preparing in pre-release" };
977
1137
  }
978
1138
  state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
@@ -989,8 +1149,9 @@ ${mdDigest(draftRefresh)}`))
989
1149
  // the version of record is fixed here, from the manifest this gate validated: release-done must not
990
1150
  // re-read a checkout that may still be behind (#52)
991
1151
  if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
1152
+ if (stale) state!.staleBuild = `${behind} (checkout ${selfBuild.version ?? "?"})`;
992
1153
  writeState(root, state!);
993
- 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}\n${nextHint(state!, cfg)}` };
1154
+ 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}.` : ""}\n${nextHint(state!, cfg)}` };
994
1155
  }
995
1156
 
996
1157
  case "release-done": {
@@ -1041,10 +1202,25 @@ ${mdDigest(draftRefresh)}`))
1041
1202
  else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
1042
1203
  }
1043
1204
  }
1205
+ // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
1206
+ // refuses the release record; what dev-flow cannot see stays an advisory — the split the changelog
1207
+ // proofs learned (#97): an invisible topology never blocks a legal release.
1208
+ let mergeNote = "";
1209
+ if (cfg.release.merge && cfg.release.merge !== "any" && state!.branch) {
1210
+ const br = state!.branch;
1211
+ await sh(`git fetch -q origin ${sq(br)} 2>/dev/null; git fetch -q origin ${sq(cfg.defaultBranch)} 2>/dev/null`, root);
1212
+ const refsOk = hasOrigin && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${br}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1213
+ // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1214
+ // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1215
+ const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1216
+ const forgeProof = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1217
+ const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeProof, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1218
+ if (proof.errors.length) errs.push(...proof.errors);
1219
+ else mergeNote = proof.note;
1220
+ }
1044
1221
  if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1045
1222
  // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
1046
- const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false;
1047
- let ghNote = "";
1223
+ const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false; let ghNote = "";
1048
1224
  let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1049
1225
  let bodyNote = "";
1050
1226
  const forgeName = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
@@ -1086,7 +1262,7 @@ ${mdDigest(draftRefresh)}`))
1086
1262
  ghNote = gr.ok ? `${forge} release ${tag} created. ${notesNote}`.trim() : `${forge} release skipped: ${tail(gr.out)}`;
1087
1263
  }
1088
1264
  }
1089
- const behind = sessionRunsOlderBuild(LOADED_VERSION, pluginVersion(import.meta.dirname).version);
1265
+ const behind = sessionRunsOlderBuild(loadedVersion(), pluginVersion(import.meta.dirname).version);
1090
1266
  const openRelease = checklistPending(cfg, state!, "release");
1091
1267
  // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
1092
1268
  // name them at the last objective gate — on the way out too, or the refusal hides half the story
@@ -1120,7 +1296,12 @@ ${mdDigest(draftRefresh)}`))
1120
1296
  state!.approvals.release = now();
1121
1297
  const tailNote = [
1122
1298
  // a session that shipped from behind: the code it runs is not the code the checkout just released
1123
- behind ? `warning: this session runs dev-flow ${behind}, not the build in the checkout — /reload before trusting what it printed.` : "",
1299
+ state!.staleBuild
1300
+ ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
1301
+ : behind
1302
+ ? `warning: this session runs dev-flow ${behind}, not the build in the checkout — /reload before trusting what it printed.`
1303
+ : "",
1304
+ mergeNote,
1124
1305
  openNote,
1125
1306
  ghNote,
1126
1307
  bodyNote,
@@ -1138,7 +1319,8 @@ ${mdDigest(draftRefresh)}`))
1138
1319
  // after this the flow state is gone: nothing may sit uncommitted or unpushed
1139
1320
  const dirty = await sh("git status --porcelain", root);
1140
1321
  if (dirty.ok && dirty.out.trim()) return { text: `main checkout has uncommitted changes — commit them first (finish deletes .dev-flow/${state!.slug}/):\n${tail(dirty.out)}`, isError: true };
1141
- if ((await sh("git remote get-url origin", root)).ok) {
1322
+ const hasOriginF = (await sh("git remote get-url origin", root)).ok;
1323
+ if (hasOriginF) {
1142
1324
  const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1143
1325
  if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
1144
1326
  }
@@ -1151,7 +1333,22 @@ ${mdDigest(draftRefresh)}`))
1151
1333
  const unmerged = await sh(`git -C ${sq(wt)} log origin/${cfg.defaultBranch}..HEAD --oneline 2>/dev/null || git -C ${sq(wt)} log ${cfg.defaultBranch}..HEAD --oneline`, root);
1152
1334
  const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1153
1335
  if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}`, isError: true };
1154
- if (assess.unmerged.length) unmergedNote = ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?).`;
1336
+ if (assess.unmerged.length) {
1337
+ const policy = cfg.release.merge;
1338
+ // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1339
+ // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1340
+ const measurable = hasOriginF && !!state!.branch && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${state!.branch}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1341
+ unmergedNote =
1342
+ policy && policy !== "merge" && policy !== "any"
1343
+ ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1344
+ : policy === "merge" && measurable
1345
+ ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} although the playbook says merge = merge — that PR did not land as a merge commit`
1346
+ : ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1347
+ // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1348
+ // answer it, only the operator does
1349
+ if (policy === "merge" && measurable && !flag("confirmed"))
1350
+ return { text: needsOperator(`the playbook says merge = merge, but ${assess.unmerged.length} commit(s) of ${state!.slug} are not on ${cfg.defaultBranch} — the PR landed as a squash or a rebase. Ask the operator how to proceed, then re-run with --confirmed`, "Merge policy violation?"), isError: true };
1351
+ }
1155
1352
  }
1156
1353
  // a forge release that failed at release-done is still the operator's call — but they must see it before the state vanishes (#63)
1157
1354
  const forgeSkipNote = state!.forgeReleaseSkipped ? ` WARNING: the forge release was not created (${state!.forgeReleaseSkipped}) — recreate it manually or re-run release-done before finishing.` : "";
@@ -1505,6 +1702,15 @@ export default function devFlow(pi: ExtensionAPI) {
1505
1702
  const why = await askOperator(ctx, command, `a forced push rewrites a pushed branch — CI and other sessions lose these commits (with the operator's word, prefix the push with ${ALLOW_REWRITE})`);
1506
1703
  if (why) return { block: true, reason: why };
1507
1704
  }
1705
+ // the playbook's merge style is enforced where the decision is actually made: gh/glab merging the PR.
1706
+ // An explicit contradiction is a hard block, a merge with no style flag (the forge default decides)
1707
+ // is a confirmation. No policy in the playbook → no new verdicts at all.
1708
+ const mv = mergeStyleInvocation(command, cfg.release.merge);
1709
+ if (mv.block) return { block: true, reason: mv.block };
1710
+ if (mv.confirm) {
1711
+ const why = await askOperator(ctx, command, mv.confirm);
1712
+ if (why) return { block: true, reason: why };
1713
+ }
1508
1714
  const inv = gitInvocation(command);
1509
1715
  if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
1510
1716
  const bound = boundFeature(ctx.cwd, key);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.53.2",
3
+ "version": "0.55.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": [
@@ -112,6 +112,15 @@ writing.
112
112
  `flow start <slug> [--ui]` — `--ui` whenever anything user-visible is touched;
113
113
  slug lowercase words-dashed; check `flow status` for an active feature first.
114
114
 
115
+ `flow start` **preflights** before it creates anything: it warns when this session runs an older dev-flow
116
+ build than the checkout (`/reload` before trusting gate output), prints the playbook gaps `flow doctor`
117
+ would report, and **refuses while the playbook has no merge policy**. That refusal is a question: ask the
118
+ operator how a merged PR should land on the default branch — `squash`, `merge` (a merge commit), `rebase`,
119
+ or `any` (no policy) — with the suggestion the refusal read off their own history, then re-run
120
+ `flow start <slug> --merge=<style> --confirmed`. The gate writes the answer into `## release` (single-line
121
+ insert, validated, `.bak` kept) and never asks again. Never pick the style yourself and never write
122
+ `project.md` by hand to get rid of the question.
123
+
115
124
  ## Stage: plan
116
125
 
117
126
  1. Research the code the plan needs (reads are always allowed).
@@ -259,7 +268,10 @@ here) — this stage publishes; the preparation happened in pre-release. Run in
259
268
  the worktree unless noted:
260
269
 
261
270
  1. Commit everything, push the feature branch, open the PR, wait for the merge
262
- (`gh pr merge` or ask the user) — without `--delete-branch`: it fails when
271
+ (`gh pr merge` or ask the user) — with the **playbook's merge style spelled out**
272
+ (`gh pr merge --squash` under `merge = squash`): the guard blocks a style that contradicts the
273
+ playbook and asks the operator about a merge with no style flag, so let the playbook decide rather
274
+ than the forge default. Merge without `--delete-branch`: it fails when
263
275
  the default branch is checked out in the main worktree, and `flow finish`
264
276
  deletes the branch on merge proof anyway.
265
277
  2. `git fetch`, confirm the merge landed, create the **annotated** tag
@@ -287,9 +299,14 @@ the worktree unless noted:
287
299
  `flow finish` closes the feature out. Skipping the forge release
288
300
  (`--no-release-create`, once, or `release.releases = false`, always) and
289
301
  the artifact check (`--no-artifact-check`, once) are operator calls only —
290
- act when told, never on your own. If `flow version` says this session runs
291
- an older build than the checkout, **stop and ask the operator to `/reload`
292
- before publishing** — gates execute the code loaded at session start.
302
+ act when told, never on your own. If this session runs an older build than
303
+ the checkout, **the release gate asks instead of blocking**: it prints both
304
+ builds, lists what shipped between them (those proofs will not run), and
305
+ puts the choice to the operator — **update (`/reload` and re-run) or
306
+ proceed with the old release?** Publishing under an older gate is a
307
+ legitimate choice (hotfix, offline reload); the answer is recorded in the
308
+ release output and `release-done` repeats the acknowledgement as the
309
+ backstop for headless runs.
293
310
  Release-stage checklist items have no gate of their own: `release-done`
294
311
  lists the open ones and the Finish? answer closes them.
295
312
 
@@ -316,9 +333,10 @@ unmerged. `flow finish [slug]`:
316
333
  - removes the worktree and branch, then deletes `.dev-flow/<slug>/` and
317
334
  unbinds the session. A feature branch still on `origin` is deleted **only on
318
335
  proof it was merged** — ancestor of `origin/<default>`, or a merged PR via gh
319
- (squash merges); otherwise kept with a note. Uncommitted worktree edits block
320
- finish; unmerged-looking commits called out at Finish? without an operator
321
- answer → stop and show them.
336
+ or glab (what a squash leaves behind); otherwise kept with a note. Uncommitted worktree edits block
337
+ finish; commits that never reached the default branch are read against the playbook's `merge` policy —
338
+ expected under `squash`/`rebase`, a **violation** under `merge` (which `yolo` cannot answer for), and
339
+ called out at Finish? without an operator answer → stop and show them.
322
340
 
323
341
  Production deployment stays manual and out of scope: never ask the operator
324
342
  whether a prod deploy happened.
package/src/core.ts CHANGED
@@ -40,6 +40,7 @@ export interface FlowState {
40
40
  setupAt?: string; // commands.setup exited 0 in this worktree — a reused worktree reruns it only when unset (#49)
41
41
  releaseVersion?: string; // the manifest version the release gate approved — release-done publishes this, not whatever a checkout says later (#52)
42
42
  forgeReleaseSkipped?: string; // a gh/glab release create that failed: release-done says so, finish names it so the missing forge release cannot slip past (#63)
43
+ staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
43
44
  }
44
45
 
45
46
  /** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features. */
@@ -60,6 +61,17 @@ export interface Commands {
60
61
  dev?: string;
61
62
  }
62
63
 
64
+ /** How a merged feature branch lands on the default branch (playbook key `merge`).
65
+ * `any` is an explicit opt-out: "no policy, stop asking" — absent means unset and nagged about. */
66
+ export type MergeStyle = "squash" | "merge" | "rebase";
67
+ export const MERGE_STYLES = ["squash", "merge", "rebase", "any"] as const;
68
+
69
+ /** A playbook `merge` value, or null when it is not a policy at all (a typo must not silently mean "no policy"). */
70
+ export function parseMergeStyle(raw: unknown): MergeStyle | "any" | null {
71
+ const v = typeof raw === "string" ? raw.trim().toLowerCase() : "";
72
+ return (MERGE_STYLES as readonly string[]).includes(v) ? (v as MergeStyle | "any") : null;
73
+ }
74
+
63
75
  export interface Versioning {
64
76
  /** Repo-relative manifest holding the version: VERSION | package.json | Cargo.toml | pyproject.toml. */
65
77
  file?: string;
@@ -82,7 +94,7 @@ export interface Config {
82
94
  versioning: Versioning;
83
95
  /** Seconds the post-deploy health probe may keep retrying before the gate gives up (0 = single shot). */
84
96
  healthWait: number;
85
- release: { review: string; changelog?: string; tagPattern?: string; releases?: boolean; artifact?: string };
97
+ release: { review: string; changelog?: string; tagPattern?: string; releases?: boolean; artifact?: string; merge?: MergeStyle | "any" };
86
98
  mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
87
99
  /** `require` (default): a shell call must carry its own visible timeout — the injected class
88
100
  * default is armed silently and never shows in the transcript. `inject`: arm it silently. */
@@ -449,6 +461,22 @@ export function sessionRunsOlderBuild(loaded: string | null, disk: string | null
449
461
  return loaded && disk && loaded !== disk ? loaded : "";
450
462
  }
451
463
 
464
+ /** The changelog's version headings strictly between `from` (exclusive) and `to` (inclusive), newest
465
+ * first — what a session running `from` is missing against a checkout on `to`, i.e. the gate proofs
466
+ * that will not run. Only `## [0.54.0]` / `## 0.54.0` headings with a parseable numeric-dot version
467
+ * count; everything else (Unreleased, prose, `v` prefixes) is skipped, and so are unparseable bounds. */
468
+ export function changelogVersionsBetween(changelog: string, from: string, to: string): string[] {
469
+ const versioned = (v: string) => /^\d+\.\d+\.\d+/.test(v);
470
+ if (!versioned(from) || !versioned(to)) return [];
471
+ const found: string[] = [];
472
+ for (const m of changelog.matchAll(/^##\s+\[?([^\]\s]+)\]?/gm)) {
473
+ const v = m[1];
474
+ if (!versioned(v) || found.includes(v)) continue;
475
+ if (cmpVersions(v, from) > 0 && cmpVersions(v, to) <= 0) found.push(v);
476
+ }
477
+ return found.sort((a, b) => cmpVersions(b, a));
478
+ }
479
+
452
480
  /** Owner/slug from any GitHub repo reference — "owner/repo", "github.com/owner/repo", git+https or scp-style git@github.com:owner/repo.git; "" when it is not GitHub. */
453
481
  export function githubSlug(ref: string): string {
454
482
  const m = ref.match(/github\.com[/:]([\w.-]+\/[\w.-]+?)(?:\.git)?(?:\/|$)/) ?? /^[\w.-]+\/[\w.-]+$/.exec(ref);
@@ -552,6 +580,109 @@ export function cleanupAssess(porcelain: string, unmerged: string[]): { errors:
552
580
  return { errors, unmerged: unmerged.filter(Boolean) };
553
581
  }
554
582
 
583
+ /* -------------------------------------------------------------- merge policy */
584
+
585
+ /** Past tense of a style, for the wording of a refusal. */
586
+ const MERGE_PAST: Record<MergeStyle, string> = { squash: "squash-merged", merge: "merge-committed", rebase: "rebase-merged" };
587
+
588
+ /**
589
+ * What the repo's own history says about its merge style, for `flow init` and `flow start` to suggest
590
+ * instead of asking blind. Input is one line per first-parent commit as `%p|%s`: two parents is a merge
591
+ * commit, a single commit whose subject ends in `(#123)` is what a squash leaves behind. Direct pushes and
592
+ * release chores are neither — the answer must come from PR merges only. `recent` is the style of the newest
593
+ * classified merge, which is what the repo actually does now (dev-flow: merge commits; ollamaMQ switched to
594
+ * squash at PR #21 and nothing wrote it down).
595
+ */
596
+ export function classifyMergeHistory(lines: string[]): { merges: number; squashes: number; recent: MergeStyle | null; note: string } {
597
+ let merges = 0;
598
+ let squashes = 0;
599
+ let recent: MergeStyle | null = null;
600
+ for (const line of lines) {
601
+ const sep = line.indexOf("|");
602
+ if (sep === -1) continue;
603
+ const parents = line.slice(0, sep).trim().split(/\s+/).filter(Boolean).length;
604
+ const subject = line.slice(sep + 1).trim();
605
+ const isMerge = parents > 1;
606
+ const isSquash = !isMerge && /\(#[0-9]+\)$/.test(subject);
607
+ if (!isMerge && !isSquash) continue;
608
+ if (isMerge) merges++;
609
+ else squashes++;
610
+ if (!recent) recent = isMerge ? "merge" : "squash";
611
+ }
612
+ const note = recent
613
+ ? `merge history: ${merges} merge commit(s), ${squashes} squash(es) — the most recent PR landed as ${recent}`
614
+ : "merge history: no PR merges on the first parent to read a style from";
615
+ return { merges, squashes, recent, note };
616
+ }
617
+
618
+ export interface MergeShapeFacts {
619
+ /** Is the merged branch an ancestor of the default branch? null = not measurable (no origin, unfetched branch). */
620
+ ancestor: boolean | null;
621
+ /** What the forge says landed the PR, when `gh`/`glab` could answer — the only way to tell a squash from a rebase. */
622
+ forgeStyle?: MergeStyle | null;
623
+ /** Wording only. */
624
+ branch?: string;
625
+ defaultBranch?: string;
626
+ }
627
+
628
+ /**
629
+ * Did what actually landed agree with the playbook's `merge` policy? A measured contradiction is an error;
630
+ * what cannot be measured is a note — the split the changelog proofs learned (#97): a topology dev-flow
631
+ * cannot see must never refuse a legal release. Note that ancestry alone proves *not squashed/rebased*:
632
+ * a fast-forward looks exactly like a merge commit here.
633
+ */
634
+ export function mergeShapeProof(policy: MergeStyle | "any" | undefined, facts: MergeShapeFacts): { errors: string[]; note: string } {
635
+ const errors: string[] = [];
636
+ if (!policy || policy === "any") return { errors, note: "" };
637
+ const br = facts.branch ? `origin/${facts.branch}` : "the branch";
638
+ const def = facts.defaultBranch ?? "the default branch";
639
+ if (facts.ancestor === null) return { errors, note: `merge = ${policy} could not be checked from here (no origin or ${br} is not fetched) — confirm the merge style by hand` };
640
+ const landed = facts.forgeStyle ?? null;
641
+ if (policy === "merge") {
642
+ if (!facts.ancestor) errors.push(`the playbook says merge = merge, but ${br} is not an ancestor of ${def} — the PR was ${landed ? MERGE_PAST[landed] : "squash- or rebase-merged"}, which rewrites the branch's commits out of the release's ancestry`);
643
+ else if (landed && landed !== "merge") errors.push(`the forge reports a ${landed} merge, but the playbook says merge = merge`);
644
+ else return { errors, note: `merge shape matches the playbook: ${br} is an ancestor of ${def} (merge = merge)` };
645
+ } else {
646
+ if (facts.ancestor) errors.push(`the playbook says merge = ${policy}, but ${br} is an ancestor of ${def} — the branch was merged as a merge commit or fast-forward, not ${MERGE_PAST[policy]}`);
647
+ else if (landed && landed !== policy) errors.push(`the forge reports a ${landed} merge, but the playbook says merge = ${policy}`);
648
+ else return { errors, note: `merge shape matches the playbook: ${br} is not on ${def} as its own commits (${policy === "squash" ? "one squashed commit" : "replayed commits"})` };
649
+ }
650
+ return { errors, note: "" };
651
+ }
652
+
653
+ export interface MergeStyleVerdict {
654
+ block: string | null;
655
+ confirm: string | null;
656
+ }
657
+
658
+ /**
659
+ * Does this command pick a merge style the playbook forbids? The forge CLI is the one place the shape of the
660
+ * default branch is decided, so an explicit contradiction is a hard block; a merge with no style flag lets the
661
+ * forge default decide, which deserves a confirmation, not a refusal. A local `git merge --squash` is only ever
662
+ * a confirmation: merging main into a feature branch is normal work and `--no-ff` there is not a merge policy at all.
663
+ * Quoted text is prose (`grep "gh pr merge --squash" docs/` searches), except inside a head that execs its argument.
664
+ */
665
+ export function mergeStyleInvocation(command: string, policy: MergeStyle | "any" | undefined): MergeStyleVerdict {
666
+ const none: MergeStyleVerdict = { block: null, confirm: null };
667
+ if (!policy || policy === "any") return none;
668
+ for (const seg of bashSegments(command)) {
669
+ if (READ_ONLY_HEADS.has(segHead(seg))) continue; // `grep "gh pr merge --squash" docs/` searches, it does not merge
670
+ const head = segHead(seg);
671
+ const hay = REEXEC_HEADS.has(head) ? `${seg} ${maskQuoted(seg)}` : maskQuoted(seg);
672
+ const forge: "gh" | "glab" | null = /\bgh\s+pr\s+merge\b/.test(hay) ? "gh" : /\bglab\s+mr\s+merge\b/.test(hay) ? "glab" : null;
673
+ if (forge) {
674
+ const style: MergeStyle | null = /--no-squash\b/.test(hay) ? "merge" : /--squash\b/.test(hay) ? "squash" : /--rebase\b/.test(hay) ? "rebase" : /--merge\b/.test(hay) ? "merge" : null;
675
+ const wanted = forge === "glab" ? (policy === "squash" ? "--squash" : "--no-squash") : `--${policy}`;
676
+ if (!style) return { block: null, confirm: `this merge carries no style flag, so the forge default decides the shape of the default branch — the playbook says merge = ${policy}; pass ${wanted} explicitly` };
677
+ if (style !== policy) return { block: `the playbook says merge = ${policy} (.dev-flow/project.md) — this command forces a ${style} merge; drop the flag or pass ${wanted}`, confirm: null };
678
+ return none;
679
+ }
680
+ if (/\bgit\b[^\n]*\bmerge\b[^\n]*--squash\b/.test(hay) && policy !== "squash")
681
+ return { block: null, confirm: `git merge --squash folds a branch into a single commit, but the playbook says merge = ${policy} — if this is the PR merge itself, merge it on the forge instead` };
682
+ }
683
+ return none;
684
+ }
685
+
555
686
  export interface GuardCtx {
556
687
  command: string;
557
688
  branch: string; // branch of the directory the git commands run in (feature worktree or main checkout)
@@ -1308,6 +1439,12 @@ export function compactionReflectionLine(slug: string, stage: Stage, reason: str
1308
1439
  }
1309
1440
 
1310
1441
  /** What the agent/user should do next, per stage. */
1442
+ /** The playbook's merge style spelled for a hint: "" when the project has no policy. */
1443
+ function mergeHintFor(cfg: Config): string {
1444
+ const m = cfg.release.merge;
1445
+ return m && m !== "any" ? ` (the playbook says merge = ${m} — gh pr merge --${m === "merge" ? "merge" : m})` : "";
1446
+ }
1447
+
1311
1448
  export function nextHint(state: FlowState, cfg: Config): string {
1312
1449
  switch (state.stage) {
1313
1450
  case "plan":
@@ -1323,8 +1460,8 @@ export function nextHint(state: FlowState, cfg: Config): string {
1323
1460
  return state.approvals.release
1324
1461
  ? "release recorded — commit and push the release chores in the main checkout (prefix the commit with DEV_FLOW_ALLOW_MAIN=1 — the installed pre-commit hook otherwise blocks main commits), ask the operator Finish? and run flow finish (removes worktree, branch and .dev-flow/" + state.slug + "/)"
1325
1462
  : state.noVersion
1326
- ? "publish: commit and push the branch, open and merge the PR — unversioned release: no manifest bump, no tag, your changelog entry rides under Unreleased; then run flow release-done (no further question)"
1327
- : "publish: commit and push the branch, open and merge the PR, create the annotated tag from the manifest version and push it, then run flow release-done (no further question)";
1463
+ ? `publish: commit and push the branch, open and merge the PR${mergeHintFor(cfg)} — unversioned release: no manifest bump, no tag, your changelog entry rides under Unreleased; then run flow release-done (no further question)`
1464
+ : `publish: commit and push the branch, open and merge the PR${mergeHintFor(cfg)}, create the annotated tag from the manifest version and push it, then run flow release-done (no further question)`;
1328
1465
  default:
1329
1466
  return "feature finished";
1330
1467
  }
package/src/detect.ts CHANGED
@@ -10,7 +10,8 @@ import path from "node:path";
10
10
  import { parseVersion } from "./core.ts";
11
11
 
12
12
  export interface Detection {
13
- partial: { defaultBranch: string; commands: Record<string, string>; versioning?: { file: string }; forge?: string };
13
+ /** `merge` is not detected here (detection is fs-only): the caller fills it from the first-parent history. */
14
+ partial: { defaultBranch: string; commands: Record<string, string>; versioning?: { file: string }; forge?: string; merge?: string };
14
15
  report: string[]; // human lines: what was detected
15
16
  missing: string[]; // command keys left empty (excluding setup)
16
17
  }
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, parseVersion, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
10
+ import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, toSeconds, type GuardRules, type MergeStyle, 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];
@@ -40,6 +40,7 @@ const KEYMAP: Record<string, Record<string, string>> = {
40
40
  "release.github": "release.releases",
41
41
  "release.releases": "release.releases",
42
42
  "release.artifact": "release.artifact",
43
+ "release.merge": "release.merge",
43
44
  },
44
45
  plan: {},
45
46
  implement: {
@@ -60,6 +61,7 @@ const KEYMAP: Record<string, Record<string, string>> = {
60
61
  github: "release.releases", // legacy alias for `releases` — parse warns about the rename
61
62
  releases: "release.releases",
62
63
  artifact: "release.artifact",
64
+ merge: "release.merge", // how a merged branch lands: squash | merge | rebase | any
63
65
  },
64
66
  };
65
67
  // pre-release owns release preparation; the release keys are accepted under both sections so
@@ -161,6 +163,11 @@ export function parseProjectMd(text: string): ParsedMd {
161
163
  p.warn.push(`${where}: bashTimeout = "${m[2]}" — expected require or inject, keeping require`);
162
164
  return;
163
165
  }
166
+ // merge is the other enum: a typo here must not quietly mean "no policy" and drop the teeth
167
+ if (mapped === "release.merge" && !parseMergeStyle(m[2])) {
168
+ p.warn.push(`${where}: merge = "${m[2]}" — expected squash, merge, rebase or any — ignored`);
169
+ return;
170
+ }
164
171
  p.flow[stage as MdStage][mapped] = m[2];
165
172
  }
166
173
  }
@@ -245,6 +252,42 @@ function mergeInto(c: Config, r: Record<string, unknown>): void {
245
252
  if (wait !== undefined) c.healthWait = wait;
246
253
  }
247
254
 
255
+ /**
256
+ * Insert — or replace in place — one `key = value` line in a stage's flow block. This is the surgical
257
+ * playbook write `flow start --merge=` uses: a full `buildDraft` regeneration is not an option there,
258
+ * because a draft cannot reproduce hand-written prose and checklist items and would drop them. Replacing an
259
+ * existing line keeps an update idempotent (no stacked duplicates), and the caller validates the result with
260
+ * `parseProjectMd` before writing anything.
261
+ */
262
+ export function setPlaybookKey(text: string, stage: MdStage, key: string, value: string): { text: string; where: string } | { error: string } {
263
+ const lines = text.split("\n");
264
+ const headOf = (l: string) => l.match(/^##\s+(\S+)\s*$/)?.[1]?.toLowerCase();
265
+ const head = lines.findIndex((l) => headOf(l) === stage);
266
+ if (head === -1) {
267
+ // no section yet: the heading and its flow block go at the end of the file — appending leaves every
268
+ // hand-written line above it exactly where it was
269
+ const tail = `\n## ${stage}\n\n` + "```flow\n" + key + " = " + value + "\n```\n";
270
+ return { text: (text.endsWith("\n") ? text : text + "\n") + tail, where: `## ${stage} — the section was created for it` };
271
+ }
272
+ let end = lines.length;
273
+ for (let i = head + 1; i < lines.length; i++) if (/^##\s/.test(lines[i])) { end = i; break; }
274
+ const kv = new RegExp(`^\\s*${key}\\s*=`);
275
+ for (let i = head + 1; i < end; i++) {
276
+ if (!/^```\s*flow\s*$/.test(lines[i])) continue;
277
+ let close = end;
278
+ for (let j = i + 1; j < end; j++) if (lines[j].trim() === "```") { close = j; break; }
279
+ const existing = lines.findIndex((l, j) => j > i && j < close && kv.test(l));
280
+ if (existing !== -1) {
281
+ lines[existing] = `${key} = ${value}`;
282
+ return { text: lines.join("\n"), where: `## ${stage} flow block (replaced the value it held)` };
283
+ }
284
+ lines.splice(i + 1, 0, `${key} = ${value}`);
285
+ return { text: lines.join("\n"), where: `## ${stage} flow block` };
286
+ }
287
+ lines.splice(head + 1, 0, "", "```flow", `${key} = ${value}`, "```");
288
+ return { text: lines.join("\n"), where: `## ${stage} — opened a flow block for it` };
289
+ }
290
+
248
291
  /** Load the project config: project.md alone — the legacy project.json is no longer read. */
249
292
  export function loadProject(dfDir: string): { cfg: Config; md: ParsedMd | null } {
250
293
  const mdFile = path.join(dfDir, "project.md");
@@ -289,6 +332,10 @@ export function doctorFindings(root: string, cfg: Config, md: ParsedMd | null):
289
332
  const gi = path.join(root, ".dev-flow", ".gitignore");
290
333
  if (existsSync(gi) && !readFileSync(gi, "utf8").includes("!project.md")) f.push(".dev-flow/.gitignore still hides project.md from git — re-run flow init to heal it");
291
334
  if (cfg.forge && !["github", "gitlab", "self"].includes(cfg.forge)) f.push(`forge "${cfg.forge}" is invalid — use github, gitlab or self`);
335
+ // the merge policy is the one playbook knob a repo can silently lack: without it nobody can say how a
336
+ // merged branch was supposed to land, and `flow finish` can only ask about what it sees
337
+ if (!cfg.release.merge) f.push("no merge policy — `flow start` asks once and writes it: merge = squash | merge | rebase under ## release (or any = no policy, stop asking)");
338
+ else if (cfg.release.merge !== "any" && cfg.forge === "self") f.push(`merge = ${cfg.release.merge} is not provable on forge = self (no gh/glab to ask how the PR landed) — release-done prints an advisory instead of a proof`);
292
339
  if (cfg.versioning.file) {
293
340
  const mf = path.join(root, cfg.versioning.file);
294
341
  if (!existsSync(mf)) f.push(`versioning.file "${cfg.versioning.file}" does not exist`);
@@ -327,7 +374,7 @@ export function doctorFindings(root: string, cfg: Config, md: ParsedMd | null):
327
374
  /** Compact per-stage digest of project.md content for dialog display (raw md walls are unreadable). */
328
375
  const DIGEST_STAGES: Record<string, string> = { global: "General", plan: "Planning", implement: "Implement", "pre-release": "Pre-release", release: "Release" };
329
376
  const DIGEST_CMDS: Record<string, string> = { setup: "setup", test: "test", build: "build", run: "run app", seedData: "seed data", dev: "dev deploy" };
330
- const DIGEST_WORDS: Record<string, string> = { defaultBranch: "default branch", branchPattern: "branch pattern", worktreeDir: "worktree dir", mainHook: "main-branch hook", mockupGlobs: "mockup files", forge: "forge", bashTimeout: "shell-call timeout mode" };
377
+ const DIGEST_WORDS: Record<string, string> = { defaultBranch: "default branch", branchPattern: "branch pattern", worktreeDir: "worktree dir", mainHook: "main-branch hook", mockupGlobs: "mockup files", forge: "forge", bashTimeout: "shell-call timeout mode", merge: "merge policy" };
331
378
 
332
379
  /** Human summary of a playbook for the init confirm: one line per stage, real values and full item/guidance text, nothing truncated. */
333
380
  export function mdDigest(text: string): string {
@@ -389,6 +436,11 @@ export function buildDraft(det: { report: string[]; partial: { defaultBranch: st
389
436
  }
390
437
  L.push("- [ ] app runs locally with real data; visual pass: no overflows or stray scrollbars", "", "<!-- tier-3: standing guidance for this stage -->", "");
391
438
  L.push("## pre-release", "", "<!-- e.g. review policy, docs expectations, who picks the version -->", "", "```flow", `versionFile = ${verFile}`, "versionTag = v{version}", "```", "");
392
- L.push("## release", "", "<!-- e.g. PR/merge/tag policy, who publishes artifacts -->", "");
439
+ // the merge policy is never invented by detection: a refresh carries the operator's answer over, a fresh
440
+ // draft asks. It is the one knob that decides the shape of the default branch, so it gets its own block.
441
+ L.push("## release", "");
442
+ if (c.release.merge) L.push("```flow", `merge = ${c.release.merge}`, "```", "");
443
+ else L.push("<!-- merge = squash | merge | rebase — how a merged PR lands on the default branch (`any` = no policy). flow start also asks and writes it. -->", "");
444
+ L.push("<!-- e.g. tag policy, who publishes artifacts -->", "");
393
445
  return L.join("\n") + "\n";
394
446
  }