pi-dev-flow 0.53.2 → 0.54.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,19 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.54.0] - 2026-10-22
8
+
9
+ ### Added
10
+
11
+ - **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.
12
+ - **`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.
13
+
14
+ ### Changed
15
+
16
+ - **`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.
17
+ - **`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.
18
+ - 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.
19
+
7
20
  ## [0.53.2] - 2026-10-22
8
21
 
9
22
  ### 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,7 +9,7 @@ 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) |
@@ -17,13 +17,13 @@ so it needs no `--confirmed`.
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
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` |
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) |
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/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
@@ -39,6 +39,7 @@ import {
39
39
  checklistPending,
40
40
  checkoutTarget,
41
41
  claimBlocks,
42
+ classifyMergeHistory,
42
43
  cmpVersions,
43
44
  cleanupAssess,
44
45
  compactionReflectionLine,
@@ -54,6 +55,9 @@ import {
54
55
  guardPath,
55
56
  healthProbe,
56
57
  healthRetry,
58
+ mergeShapeProof,
59
+ mergeStyleInvocation,
60
+ parseMergeStyle,
57
61
  investigationBrief,
58
62
  parseLsRemoteTags,
59
63
  parsePushRefs,
@@ -103,7 +107,7 @@ import {
103
107
  type PushRef,
104
108
  type SessionClaim,
105
109
  } from "../src/core.ts";
106
- import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd } from "../src/projectmd.ts";
110
+ import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
107
111
  import { bashTimeout, requireTimeout } from "../src/timeouts.ts";
108
112
  import { detectProject } from "../src/detect.ts";
109
113
 
@@ -135,6 +139,81 @@ async function sh(command: string, cwd: string): Promise<{ ok: boolean; out: str
135
139
 
136
140
  const dfDir = (root: string) => path.join(root, ".dev-flow");
137
141
 
142
+ /** A `--merge=squash` style flag, or null when absent. Returned as the raw string: the caller validates it
143
+ * with parseMergeStyle so a typo is reported instead of ignored. */
144
+ function flagValue(rest: string[], name: string): string | null {
145
+ for (const a of rest) {
146
+ const m = a.match(new RegExp(`^--${name}=(.+)$`));
147
+ if (m) return m[1];
148
+ }
149
+ return null;
150
+ }
151
+
152
+ /** One cheap first-parent log tells the operator what their repo actually does when a PR merges: merge
153
+ * commits or one squashed commit per PR. `flow init` and `flow start` ask with this evidence instead of
154
+ * asking blind; null when there is no default-branch log to read. */
155
+ async function mergeHistoryEvidence(root: string, defaultBranch: string): Promise<{ note: string; recent: "squash" | "merge" | "rebase" | null } | null> {
156
+ 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);
157
+ if (!log.ok || !log.out.trim()) return null;
158
+ const c = classifyMergeHistory(log.out.split("\n"));
159
+ return { note: c.note, recent: c.recent };
160
+ }
161
+
162
+ /** How the forge says the PR landed, when it can be asked — the only way to tell a squash from a rebase,
163
+ * because both erase the branch's ancestry. null = unaskable (self-hosted, no CLI, no merged PR found). */
164
+ async function forgeMergeStyle(root: string, forge: string, branch: string): Promise<"squash" | "merge" | "rebase" | null> {
165
+ if (!branch) return null;
166
+ // sh() folds stderr into stdout, so a CLI error can arrive where the JSON was expected: parse defensively
167
+ const json = (out: string): unknown | null => {
168
+ try {
169
+ return JSON.parse(out);
170
+ } catch {
171
+ return null;
172
+ }
173
+ };
174
+ if (forge === "github") {
175
+ const pr = await sh(`gh pr list --state merged --head ${sq(branch)} --json number,squashCommit,rebaseCommit,mergeCommit --jq '.[0]'`, root);
176
+ if (!pr.ok || !pr.out.trim() || pr.out.trim() === "null") return null;
177
+ const parsed = json(pr.out.trim()) as { squashCommit?: string | null; rebaseCommit?: string | null; mergeCommit?: string | null } | null;
178
+ return parsed?.squashCommit ? "squash" : parsed?.rebaseCommit ? "rebase" : parsed?.mergeCommit ? "merge" : null;
179
+ }
180
+ if (forge === "gitlab") {
181
+ const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${branch}&state=merged&per_page=1`)}`, root);
182
+ if (!mr.ok || !mr.out.trim() || mr.out.trim() === "[]") return null;
183
+ const list = json(mr.out.trim()) as { squash_commit_sha?: string | null; merge_commit_sha?: string | null }[] | null;
184
+ const parsed = Array.isArray(list) ? list[0] : null;
185
+ return parsed?.squash_commit_sha ? "squash" : parsed?.merge_commit_sha ? "merge" : null;
186
+ }
187
+ return null;
188
+ }
189
+
190
+ /**
191
+ * Write the merge policy into the playbook with a single-line insert — never a draft regeneration, which
192
+ * cannot reproduce hand-written prose and checklist items and would drop them. Validated before it is
193
+ * written and kept as `.bak`, exactly like `flow init --write`. The commit is the playbook chore the guard
194
+ * already blesses, and only when the playbook is the only dirty path: a gate never sweeps someone else's
195
+ * work into a chore commit.
196
+ */
197
+ async function writePlaybookMergePolicy(root: string, style: string): Promise<{ note: string } | { err: string }> {
198
+ const mdFile = path.join(dfDir(root), "project.md");
199
+ if (!existsSync(mdFile)) return { err: "no .dev-flow/project.md to write the policy into — run flow init first" };
200
+ const ins = setPlaybookKey(readFileSync(mdFile, "utf8"), "release", "merge", style);
201
+ if ("error" in ins) return { err: ins.error };
202
+ const parsed = parseProjectMd(ins.text);
203
+ if (parsed.hard.length) return { err: `refusing to write project.md — the result would not parse:\n- ${parsed.hard.join("\n- ")}` };
204
+ copyFileSync(mdFile, `${mdFile}.bak`);
205
+ writeFileSync(mdFile, ins.text);
206
+ const dirty = await sh("git status --porcelain", root);
207
+ const onlyPlaybook = dirty.ok && dirty.out.trim().split("\n").every((l) => l.trim().endsWith(" .dev-flow/project.md"));
208
+ const tracked = (await sh("git ls-files --error-unmatch .dev-flow/project.md", root)).ok;
209
+ let note = `merge = ${style} written to .dev-flow/project.md (${ins.where}; previous copy kept as project.md.bak)`;
210
+ if (tracked && onlyPlaybook) {
211
+ 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);
212
+ note += commit.ok ? " — committed as a playbook chore" : ` — commit failed (${tail(commit.out)}); commit it yourself`;
213
+ } else note += `. ${GIT_TRACK_NOTE}`;
214
+ return { note };
215
+ }
216
+
138
217
  /**
139
218
  * Run the health probe with the playbook's wait budget (#42). A service whose readiness lags its
140
219
  * container start can never pass a single shot, and hand-writing a poll loop into every playbook was
@@ -162,7 +241,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
162
241
  }
163
242
 
164
243
  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)";
244
+ "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)";
166
245
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
167
246
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
168
247
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -450,9 +529,11 @@ function isSelfRepo(root: string): boolean {
450
529
  }
451
530
 
452
531
  /** 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[] {
532
+ function setupQuestions(det: { partial: { defaultBranch: string; versioning?: { file: string }; forge?: string; merge?: string }; missing: string[] }): string[] {
454
533
  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
534
  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?");
535
+ // the merge style is inferable from history and worth asking with that evidence: a repo almost always has one
536
+ 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
537
  q.push("releases: should release-done create the forge release automatically via gh/glab (releases = yes), or is publishing manual (no)?");
457
538
  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
539
  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.`);
@@ -505,6 +586,7 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
505
586
  const det = detectProject(root, branch);
506
587
  const origin = await sh("git remote get-url origin", root);
507
588
  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
589
+ det.partial.merge = (await mergeHistoryEvidence(root, branch))?.note; // "what do you actually do when a PR merges", read off the log
508
590
  const loaded = loadProject(dfDir(root));
509
591
  const draftFresh = buildDraft(det);
510
592
  const draftRefresh = buildDraft(det, loaded.cfg);
@@ -571,6 +653,11 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
571
653
  // doctor mode: cheap consistency probes only — never runs project commands
572
654
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
573
655
  findings.push(...(await gitConsistency(root, loaded.cfg)));
656
+ // 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
657
+ if (!loaded.cfg.release.merge) {
658
+ const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
659
+ 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)`);
660
+ }
574
661
  for (const l of readReflections(root)) findings.push(`open reflection: ${l.slice(6)}`);
575
662
  if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
576
663
  else {
@@ -616,7 +703,7 @@ ${mdDigest(draftRefresh)}`))
616
703
  }
617
704
 
618
705
  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 };
706
+ 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
707
  if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
621
708
  // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
622
709
  if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
@@ -625,13 +712,52 @@ ${mdDigest(draftRefresh)}`))
625
712
  // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
626
713
  const curBr = await currentBranch(root);
627
714
  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
715
+ // --- preflight: is this session running the current build, and is the playbook complete? ---
716
+ const notes: string[] = [];
629
717
  const self = pluginVersion(import.meta.dirname);
718
+ const behind = sessionRunsOlderBuild(LOADED_VERSION, self.version);
719
+ if (behind) notes.push(`warning: this session runs dev-flow ${behind}, the checkout has ${self.version} — /reload before trusting what a gate prints`);
720
+ if (flag("check-upstream")) {
721
+ const pub = await sh("npm view pi-dev-flow version", root);
722
+ const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
723
+ 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?)");
724
+ }
725
+ // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
726
+ const gaps = doctorFindings(root, cfg, loadProject(dfDir(root)).md).filter((x) => !x.startsWith("no merge policy"));
727
+ 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")}`);
728
+ // the merge policy is the one blocking gap: it decides the shape of the default branch and nobody can
729
+ // reconstruct it afterwards. Ask once in chat (a checkpoint word like any other), write the answer, continue.
730
+ const styleArg = flagValue(rest, "merge");
731
+ const style = styleArg === null ? null : parseMergeStyle(styleArg);
732
+ if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
733
+ // with no playbook at all there is nothing to ask about: writing the playbook is `flow init`'s job, and
734
+ // a repo that never ran init must not be refused a feature by a merge-policy question
735
+ const hasPlaybook = existsSync(path.join(dfDir(root), "project.md"));
736
+ if (!hasPlaybook) notes.push("no .dev-flow/project.md yet — flow init writes the playbook (it now asks for the merge policy too)");
737
+ if (hasPlaybook && (!cfg.release.merge || (style && style !== cfg.release.merge))) {
738
+ if (!style) {
739
+ const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
740
+ return {
741
+ text: needsOperator(
742
+ `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)`,
743
+ "Merge policy?",
744
+ ),
745
+ isError: true,
746
+ };
747
+ }
748
+ 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 };
749
+ const written = await writePlaybookMergePolicy(root, style);
750
+ if ("err" in written) return { text: written.err, isError: true };
751
+ // the flow that just wrote the policy must see it: nextHint and the merge guard read this config
752
+ cfg.release.merge = style;
753
+ notes.push(written.note);
754
+ }
755
+ // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling
630
756
  const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), self.version ?? undefined);
631
757
  mkdirSync(path.join(featDir(root, slugArg), "plan"), { recursive: true });
632
758
  writeState(root, state);
633
759
  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)}` };
760
+ 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
761
  }
636
762
 
637
763
  case "status": {
@@ -745,6 +871,12 @@ ${mdDigest(draftRefresh)}`))
745
871
  const self = pluginVersion(import.meta.dirname);
746
872
  const behind = sessionRunsOlderBuild(LOADED_VERSION, self.version);
747
873
  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}`;
874
+ // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
875
+ if (flag("check-upstream")) {
876
+ const pub = await sh("npm view pi-dev-flow version", root);
877
+ const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
878
+ return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
879
+ }
748
880
  return { text: behind ? `${head} — but this session runs ${behind}; /reload to run ${self.version}` : head };
749
881
  }
750
882
 
@@ -1041,10 +1173,25 @@ ${mdDigest(draftRefresh)}`))
1041
1173
  else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
1042
1174
  }
1043
1175
  }
1176
+ // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
1177
+ // refuses the release record; what dev-flow cannot see stays an advisory — the split the changelog
1178
+ // proofs learned (#97): an invisible topology never blocks a legal release.
1179
+ let mergeNote = "";
1180
+ if (cfg.release.merge && cfg.release.merge !== "any" && state!.branch) {
1181
+ const br = state!.branch;
1182
+ await sh(`git fetch -q origin ${sq(br)} 2>/dev/null; git fetch -q origin ${sq(cfg.defaultBranch)} 2>/dev/null`, root);
1183
+ const refsOk = hasOrigin && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${br}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1184
+ // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1185
+ // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1186
+ const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1187
+ const forgeProof = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1188
+ const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeProof, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1189
+ if (proof.errors.length) errs.push(...proof.errors);
1190
+ else mergeNote = proof.note;
1191
+ }
1044
1192
  if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1045
1193
  // 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 = "";
1194
+ const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false; let ghNote = "";
1048
1195
  let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1049
1196
  let bodyNote = "";
1050
1197
  const forgeName = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
@@ -1121,6 +1268,7 @@ ${mdDigest(draftRefresh)}`))
1121
1268
  const tailNote = [
1122
1269
  // a session that shipped from behind: the code it runs is not the code the checkout just released
1123
1270
  behind ? `warning: this session runs dev-flow ${behind}, not the build in the checkout — /reload before trusting what it printed.` : "",
1271
+ mergeNote,
1124
1272
  openNote,
1125
1273
  ghNote,
1126
1274
  bodyNote,
@@ -1138,7 +1286,8 @@ ${mdDigest(draftRefresh)}`))
1138
1286
  // after this the flow state is gone: nothing may sit uncommitted or unpushed
1139
1287
  const dirty = await sh("git status --porcelain", root);
1140
1288
  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) {
1289
+ const hasOriginF = (await sh("git remote get-url origin", root)).ok;
1290
+ if (hasOriginF) {
1142
1291
  const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1143
1292
  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
1293
  }
@@ -1151,7 +1300,22 @@ ${mdDigest(draftRefresh)}`))
1151
1300
  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
1301
  const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1153
1302
  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?).`;
1303
+ if (assess.unmerged.length) {
1304
+ const policy = cfg.release.merge;
1305
+ // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1306
+ // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1307
+ 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;
1308
+ unmergedNote =
1309
+ policy && policy !== "merge" && policy !== "any"
1310
+ ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1311
+ : policy === "merge" && measurable
1312
+ ? ` ${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`
1313
+ : ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1314
+ // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1315
+ // answer it, only the operator does
1316
+ if (policy === "merge" && measurable && !flag("confirmed"))
1317
+ 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 };
1318
+ }
1155
1319
  }
1156
1320
  // 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
1321
  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 +1669,15 @@ export default function devFlow(pi: ExtensionAPI) {
1505
1669
  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
1670
  if (why) return { block: true, reason: why };
1507
1671
  }
1672
+ // the playbook's merge style is enforced where the decision is actually made: gh/glab merging the PR.
1673
+ // An explicit contradiction is a hard block, a merge with no style flag (the forge default decides)
1674
+ // is a confirmation. No policy in the playbook → no new verdicts at all.
1675
+ const mv = mergeStyleInvocation(command, cfg.release.merge);
1676
+ if (mv.block) return { block: true, reason: mv.block };
1677
+ if (mv.confirm) {
1678
+ const why = await askOperator(ctx, command, mv.confirm);
1679
+ if (why) return { block: true, reason: why };
1680
+ }
1508
1681
  const inv = gitInvocation(command);
1509
1682
  if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
1510
1683
  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.54.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
@@ -316,9 +328,10 @@ unmerged. `flow finish [slug]`:
316
328
  - removes the worktree and branch, then deletes `.dev-flow/<slug>/` and
317
329
  unbinds the session. A feature branch still on `origin` is deleted **only on
318
330
  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.
331
+ or glab (what a squash leaves behind); otherwise kept with a note. Uncommitted worktree edits block
332
+ finish; commits that never reached the default branch are read against the playbook's `merge` policy —
333
+ expected under `squash`/`rebase`, a **violation** under `merge` (which `yolo` cannot answer for), and
334
+ called out at Finish? without an operator answer → stop and show them.
322
335
 
323
336
  Production deployment stays manual and out of scope: never ask the operator
324
337
  whether a prod deploy happened.
package/src/core.ts CHANGED
@@ -60,6 +60,17 @@ export interface Commands {
60
60
  dev?: string;
61
61
  }
62
62
 
63
+ /** How a merged feature branch lands on the default branch (playbook key `merge`).
64
+ * `any` is an explicit opt-out: "no policy, stop asking" — absent means unset and nagged about. */
65
+ export type MergeStyle = "squash" | "merge" | "rebase";
66
+ export const MERGE_STYLES = ["squash", "merge", "rebase", "any"] as const;
67
+
68
+ /** A playbook `merge` value, or null when it is not a policy at all (a typo must not silently mean "no policy"). */
69
+ export function parseMergeStyle(raw: unknown): MergeStyle | "any" | null {
70
+ const v = typeof raw === "string" ? raw.trim().toLowerCase() : "";
71
+ return (MERGE_STYLES as readonly string[]).includes(v) ? (v as MergeStyle | "any") : null;
72
+ }
73
+
63
74
  export interface Versioning {
64
75
  /** Repo-relative manifest holding the version: VERSION | package.json | Cargo.toml | pyproject.toml. */
65
76
  file?: string;
@@ -82,7 +93,7 @@ export interface Config {
82
93
  versioning: Versioning;
83
94
  /** Seconds the post-deploy health probe may keep retrying before the gate gives up (0 = single shot). */
84
95
  healthWait: number;
85
- release: { review: string; changelog?: string; tagPattern?: string; releases?: boolean; artifact?: string };
96
+ release: { review: string; changelog?: string; tagPattern?: string; releases?: boolean; artifact?: string; merge?: MergeStyle | "any" };
86
97
  mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
87
98
  /** `require` (default): a shell call must carry its own visible timeout — the injected class
88
99
  * default is armed silently and never shows in the transcript. `inject`: arm it silently. */
@@ -552,6 +563,109 @@ export function cleanupAssess(porcelain: string, unmerged: string[]): { errors:
552
563
  return { errors, unmerged: unmerged.filter(Boolean) };
553
564
  }
554
565
 
566
+ /* -------------------------------------------------------------- merge policy */
567
+
568
+ /** Past tense of a style, for the wording of a refusal. */
569
+ const MERGE_PAST: Record<MergeStyle, string> = { squash: "squash-merged", merge: "merge-committed", rebase: "rebase-merged" };
570
+
571
+ /**
572
+ * What the repo's own history says about its merge style, for `flow init` and `flow start` to suggest
573
+ * instead of asking blind. Input is one line per first-parent commit as `%p|%s`: two parents is a merge
574
+ * commit, a single commit whose subject ends in `(#123)` is what a squash leaves behind. Direct pushes and
575
+ * release chores are neither — the answer must come from PR merges only. `recent` is the style of the newest
576
+ * classified merge, which is what the repo actually does now (dev-flow: merge commits; ollamaMQ switched to
577
+ * squash at PR #21 and nothing wrote it down).
578
+ */
579
+ export function classifyMergeHistory(lines: string[]): { merges: number; squashes: number; recent: MergeStyle | null; note: string } {
580
+ let merges = 0;
581
+ let squashes = 0;
582
+ let recent: MergeStyle | null = null;
583
+ for (const line of lines) {
584
+ const sep = line.indexOf("|");
585
+ if (sep === -1) continue;
586
+ const parents = line.slice(0, sep).trim().split(/\s+/).filter(Boolean).length;
587
+ const subject = line.slice(sep + 1).trim();
588
+ const isMerge = parents > 1;
589
+ const isSquash = !isMerge && /\(#[0-9]+\)$/.test(subject);
590
+ if (!isMerge && !isSquash) continue;
591
+ if (isMerge) merges++;
592
+ else squashes++;
593
+ if (!recent) recent = isMerge ? "merge" : "squash";
594
+ }
595
+ const note = recent
596
+ ? `merge history: ${merges} merge commit(s), ${squashes} squash(es) — the most recent PR landed as ${recent}`
597
+ : "merge history: no PR merges on the first parent to read a style from";
598
+ return { merges, squashes, recent, note };
599
+ }
600
+
601
+ export interface MergeShapeFacts {
602
+ /** Is the merged branch an ancestor of the default branch? null = not measurable (no origin, unfetched branch). */
603
+ ancestor: boolean | null;
604
+ /** What the forge says landed the PR, when `gh`/`glab` could answer — the only way to tell a squash from a rebase. */
605
+ forgeStyle?: MergeStyle | null;
606
+ /** Wording only. */
607
+ branch?: string;
608
+ defaultBranch?: string;
609
+ }
610
+
611
+ /**
612
+ * Did what actually landed agree with the playbook's `merge` policy? A measured contradiction is an error;
613
+ * what cannot be measured is a note — the split the changelog proofs learned (#97): a topology dev-flow
614
+ * cannot see must never refuse a legal release. Note that ancestry alone proves *not squashed/rebased*:
615
+ * a fast-forward looks exactly like a merge commit here.
616
+ */
617
+ export function mergeShapeProof(policy: MergeStyle | "any" | undefined, facts: MergeShapeFacts): { errors: string[]; note: string } {
618
+ const errors: string[] = [];
619
+ if (!policy || policy === "any") return { errors, note: "" };
620
+ const br = facts.branch ? `origin/${facts.branch}` : "the branch";
621
+ const def = facts.defaultBranch ?? "the default branch";
622
+ 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` };
623
+ const landed = facts.forgeStyle ?? null;
624
+ if (policy === "merge") {
625
+ 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`);
626
+ else if (landed && landed !== "merge") errors.push(`the forge reports a ${landed} merge, but the playbook says merge = merge`);
627
+ else return { errors, note: `merge shape matches the playbook: ${br} is an ancestor of ${def} (merge = merge)` };
628
+ } else {
629
+ 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]}`);
630
+ else if (landed && landed !== policy) errors.push(`the forge reports a ${landed} merge, but the playbook says merge = ${policy}`);
631
+ 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"})` };
632
+ }
633
+ return { errors, note: "" };
634
+ }
635
+
636
+ export interface MergeStyleVerdict {
637
+ block: string | null;
638
+ confirm: string | null;
639
+ }
640
+
641
+ /**
642
+ * Does this command pick a merge style the playbook forbids? The forge CLI is the one place the shape of the
643
+ * default branch is decided, so an explicit contradiction is a hard block; a merge with no style flag lets the
644
+ * forge default decide, which deserves a confirmation, not a refusal. A local `git merge --squash` is only ever
645
+ * a confirmation: merging main into a feature branch is normal work and `--no-ff` there is not a merge policy at all.
646
+ * Quoted text is prose (`grep "gh pr merge --squash" docs/` searches), except inside a head that execs its argument.
647
+ */
648
+ export function mergeStyleInvocation(command: string, policy: MergeStyle | "any" | undefined): MergeStyleVerdict {
649
+ const none: MergeStyleVerdict = { block: null, confirm: null };
650
+ if (!policy || policy === "any") return none;
651
+ for (const seg of bashSegments(command)) {
652
+ if (READ_ONLY_HEADS.has(segHead(seg))) continue; // `grep "gh pr merge --squash" docs/` searches, it does not merge
653
+ const head = segHead(seg);
654
+ const hay = REEXEC_HEADS.has(head) ? `${seg} ${maskQuoted(seg)}` : maskQuoted(seg);
655
+ const forge: "gh" | "glab" | null = /\bgh\s+pr\s+merge\b/.test(hay) ? "gh" : /\bglab\s+mr\s+merge\b/.test(hay) ? "glab" : null;
656
+ if (forge) {
657
+ 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;
658
+ const wanted = forge === "glab" ? (policy === "squash" ? "--squash" : "--no-squash") : `--${policy}`;
659
+ 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` };
660
+ 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 };
661
+ return none;
662
+ }
663
+ if (/\bgit\b[^\n]*\bmerge\b[^\n]*--squash\b/.test(hay) && policy !== "squash")
664
+ 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` };
665
+ }
666
+ return none;
667
+ }
668
+
555
669
  export interface GuardCtx {
556
670
  command: string;
557
671
  branch: string; // branch of the directory the git commands run in (feature worktree or main checkout)
@@ -1308,6 +1422,12 @@ export function compactionReflectionLine(slug: string, stage: Stage, reason: str
1308
1422
  }
1309
1423
 
1310
1424
  /** What the agent/user should do next, per stage. */
1425
+ /** The playbook's merge style spelled for a hint: "" when the project has no policy. */
1426
+ function mergeHintFor(cfg: Config): string {
1427
+ const m = cfg.release.merge;
1428
+ return m && m !== "any" ? ` (the playbook says merge = ${m} — gh pr merge --${m === "merge" ? "merge" : m})` : "";
1429
+ }
1430
+
1311
1431
  export function nextHint(state: FlowState, cfg: Config): string {
1312
1432
  switch (state.stage) {
1313
1433
  case "plan":
@@ -1323,8 +1443,8 @@ export function nextHint(state: FlowState, cfg: Config): string {
1323
1443
  return state.approvals.release
1324
1444
  ? "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
1445
  : 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)";
1446
+ ? `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)`
1447
+ : `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
1448
  default:
1329
1449
  return "feature finished";
1330
1450
  }
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
  }