pi-dev-flow 0.92.1 → 0.93.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,27 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.93.0] - 2026-11-18
8
+
9
+ **`flow release` needs a review on record and opens the PR with the body your template asks for; checks stay passed across a commit of the same tree; feature worktrees take only their own feature's work; and `flow finish` names what is really wrong.**
10
+
11
+ ### Fixed
12
+ - **The flow tool names a wrongly shaped `args` (gh#238).** An `args` array that arrived marshalled as one JSON string was dispatched with the whole blob as the subcommand, and the reply was the full usage with the diagnosis buried in it. The tool now refuses with "args must be an array of strings; this arrived as one string holding an array" and shows the elements to pass. An unknown subcommand gets a one-line reply that leads with the word and lists the known ones.
13
+ - **The reflection digest marks only real guard blocks as `GUARD` (gh#239).** A successful command whose output happened to contain `NEEDS-OPERATOR` (a grep of the source, a quoted refusal) was tagged as a guard event, and a review worker went looking for a block that never happened. Guard blocks reach the transcript as error results, so `GUARD` is now only an error result that begins with the guard's marker.
14
+ - **A passing check survives committing the tree it passed on (gh#231).** A check's record was tied to HEAD plus the uncommitted diff. Running `flow check` over a fix and then committing that same fix made the record stale, and `flow release` re-ran a minute-long suite over an identical tree. The record is now tied to the tree's content (every file's blob, computed without writing to the repo), so only a real change makes it stale. When the gate does re-run a check it says why: the tree changed, the last run failed, or no run is on record.
15
+ - **`flow release` opens the PR with the body your repo's template asks for (gh#240).** The gate built the PR body from the changelog entry, so a repo's `.github/pull_request_template.md` gate list (what changed, who verified it, over which commit) never reached the PR. It had to be patched in after the merge. The gate now uses `.dev-flow/<slug>/pr-body.md` when the agent wrote one. In a repo with a PR template it refuses, before Release? is asked, until that file exists. The publish result says which body the PR got.
16
+ - **A flow's scratch dir no longer piles up `mktemp` leftovers (gh#243).** Every process a flow runs gets `.dev-flow/<slug>/tmp` as `TMPDIR`, and tooling that never removes its `mktemp` directories left over a thousand of them after one flow. Each check run now sweeps entries that look like `mktemp` output and haven't been touched for an hour. A name the project chose (a dev server's cache) is never swept, and neither is anything recent. Worker briefs also say to remove what they create there.
17
+ - **The ground rules say not to batch a gate with the git step it reads (gh#236).** In one session the agent put gates in the same tool batch as the command they depend on (commit then verify, merge then finish, checkout main then start, verify then release). The gate ran first and refused, four times across flows. The injected rules now say to call a gate only after that step has returned.
18
+ - **The stage line names the open checklist items (gh#241).** It showed tier-2 as a bare count (`tier-2 \`4 open\` ?`), and since implement and pre-release have different lists the count changed with no explanation. Finding the items meant re-reading `project.md`. The stage line now names the current stage's items, clipped, up to four plus a count.
19
+ - **`flow doctor` checks a script against the package.json it runs in (gh#227).** `cd storefront && npm run build` was checked against the root package.json and flagged on every start, status and doctor run. A leading relative `cd`, `npm --prefix`, `pnpm -C` and `yarn --cwd` now pick the package.json. A directory it can't resolve (an absolute or `$VAR` path) is skipped, not flagged.
20
+ - **`flow release` requires a review on record (gh#233).** The pre-release hint said to run the review step, but nothing checked it ran, and a 566-line change shipped unreviewed. The release gate now refuses until a review is recorded: a `flow_stage` review worker records itself, and an inline `/flow-review` is recorded with `flow review done "<verdict>"`. The verdict stays advisory. Shipping without a review is the operator's word (`flow review --skip`, asked as **Skip review?**). Docs flows and release-only cuts owe none, and `review = ""` under `## release` turns the requirement off.
21
+ - **A failing check shows its errors, not just its last lines (gh#242).** `flow check` printed the last 15 lines of a failing command, and for a lint step those were pre-existing warnings and "exited with code 1". The two files it refused were 200 lines up, and finding them took running the linter by hand. A failing check or build now lifts the error-level lines from the part of the output that gets cut, each with the line before it (where formatters name the file), above the usual tail.
22
+ - **A branch switch earlier in a command decides where a later merge lands (gh#235).** The guard read each directory's branch before the command ran, so `git checkout team-test && git merge feat/x` in the main checkout was refused as "merging into main". The agent then merged in a /tmp worktree the guard couldn't see. A `checkout`/`switch` to a branch earlier in the chain now moves the branch the later segments are judged on. A path restore (`git checkout -- f`) doesn't.
23
+ - **An empty playbook value turns the setting off (gh#226, gh#229).** `changelog =` was read as a single space and `changelog = ""` as a literal `""`, so a project couldn't opt out of a changelog, though the gate's own hint said to. An empty `health =` likewise showed up as `health: PASS ( )`. An empty value, `""` or `''` now means unset for the command and release keys (`changelog`, `review`, `health`, `test`, …). The missing-changelog refusal names the opt-out, and `flow verify` no longer claims it re-probed a live app when no dev deploy or health probe is configured.
24
+ - **`flow finish` no longer blames a squash merge for a PR that just merged (gh#237).** Under `merge = merge`, a branch missing from main was always reported as squash- or rebase-merged, even when the forge reported no merged PR yet or a real merge commit that this clone hadn't fetched. The refusal now says which: not merged yet, main behind the forge (fetch and re-run), or the squash or rebase the forge reports.
25
+ - **`flow finish` checks the local default branch, not wherever the main checkout happens to be (gh#234, gh#228).** With the main checkout on another branch, finish said "push the release (git push origin main)", which was wrong. And the playbook commit from `flow init --track` sat on local main, so finish sent the agent to merge origin into local main and push main directly. Finish now compares local main with origin wherever the checkout is, and names the local-only commits and the checkout's branch. Playbook-only commits are a note, not a block, and fast-forwarding local main works off-branch too.
26
+ - **A feature worktree takes only its own feature's work (gh#232).** After a release was recorded, an agent created a branch in the same worktree, committed a redesign and merged it to production with no plan, check, review or Verified?. The guard now refuses `git branch <name>` in a feature worktree (as it already did `checkout -b`), any commit, merge, cherry-pick or revert while the worktree is on another branch, and any commit once the release is recorded. Each refusal says to start a new flow.
27
+
7
28
  ## [0.92.1] - 2026-11-14
8
29
 
9
30
  **Stage workers are told your guard rules, a docs flow's worker runs no project checks, and `flow reflect done` closes a batch.**
package/docs/gates.md CHANGED
@@ -122,6 +122,11 @@ Proves the branch is ready to ship:
122
122
  before a commit holding only release prep (version file, changelog) stay green without a re-run;
123
123
  set `recheck = always` in `## release` to re-run them anyway. `release.preflight` passes if set.
124
124
  - There are no leftover conflict markers (`<<<<<<<`) and no uncommitted files in the worktree.
125
+ - **A review is on record.** The playbook's review step (`release.review`, `/flow-review` by
126
+ default) has to have run: a `flow_stage` review worker records itself, and an inline review is
127
+ recorded with `flow review done "<verdict>"`. The verdict stays advisory; only that a review ran
128
+ is checked. Shipping without one is your call (`flow review --skip`, asked as **Skip review?**).
129
+ Docs flows and release-only cuts owe none, and `review = ""` under `## release` turns it off.
125
130
 
126
131
  **Release? often answers itself** (`ask = on-change`, the default). That happens when your call is
127
132
  on record and only release prep (bump, changelog) changed since Verified?. A `--confirmed` given before the gate asked doesn't count where a question must be put (a held yolo,
@@ -142,7 +147,10 @@ Escape hatches, used only on your word: `--no-fold-check` skips the line-level c
142
147
 
143
148
  On GitHub, the same `flow release` call then publishes. Your Release? answer is what authorizes it:
144
149
 
145
- 1. Pushes the branch and opens the PR, with the changelog entry as the body.
150
+ 1. Pushes the branch and opens the PR. The body is `.dev-flow/<slug>/pr-body.md` when the agent
151
+ wrote one, else the changelog entry. If the repo has a pull-request template
152
+ (`.github/pull_request_template.md`), the gate refuses until `pr-body.md` exists, before
153
+ Release? is asked, so the template's sections are filled before the merge.
146
154
  2. Waits for the PR's CI, up to 30 minutes. A repo with no CI is given a minute for checks to show up.
147
155
  3. Merges in the playbook's `merge` style.
148
156
  4. Creates an annotated tag on the PR's merge commit and pushes it (versioned flows).
@@ -188,8 +196,11 @@ call it.
188
196
  the remote branch only once it's proven merged. If local main is just behind origin, it
189
197
  fast-forwards it.
190
198
 
191
- It refuses until the release is recorded, the main checkout is clean and pushed, and the worktree has
192
- no uncommitted changes. Under `merge = merge`, commits missing from main are a policy violation that
199
+ It refuses until the release is recorded, the main checkout is clean, the local default branch has
200
+ nothing origin lacks, and the worktree has no uncommitted changes. It reads the local default branch
201
+ even when the main checkout is on another branch, and names the commits that are local-only.
202
+ Playbook commits from `flow init --track` are only noted: they reach origin through a docs flow,
203
+ never a direct push. Under `merge = merge`, commits missing from main are a policy violation that
193
204
  yolo can't answer.
194
205
 
195
206
  **Finish? answers itself on a clean flow** (`finish = on-change`, the default): the release is
@@ -28,7 +28,11 @@ playbook, dev-flow stays silent.
28
28
  - Paths are checked after resolving symlinks.
29
29
  - Scratch files outside the repo (the OS temp dir) are always fine. A bound feature's `TMPDIR`
30
30
  points to `.dev-flow/<slug>/tmp/`, which is cleaned up at finish.
31
- - Creating a new branch inside a feature worktree is refused. An unrelated fix gets its own flow.
31
+ - Creating a new branch inside a feature worktree is refused (`checkout -b`, `switch -c` and
32
+ `git branch <name>`). An unrelated fix gets its own flow.
33
+ - A worktree only takes its own feature's commits: a commit, merge, cherry-pick or revert while the
34
+ worktree is on any other branch is refused. Once the release is recorded the worktree takes no new
35
+ commits at all; follow-up work is a new flow, and release chores go in the main checkout.
32
36
 
33
37
  **No work outside a flow.**
34
38
  - In a repo with `.dev-flow/`, an unbound session can't edit source files. Everything starts with
package/docs/playbook.md CHANGED
@@ -169,7 +169,7 @@ These go under `## pre-release` or `## release`. Either section works.
169
169
  |---|---|---|
170
170
  | `versionFile` | — | the version manifest (`package.json`, `VERSION`, …). Without it, releases are unversioned. |
171
171
  | `versionTag` | `v{version}` | tag format |
172
- | `changelog` | `CHANGELOG.md` | set it empty to opt out |
172
+ | `changelog` | `CHANGELOG.md` | set it empty (`changelog =` or `changelog = ""`) to opt out |
173
173
  | `merge` | *(asked)* | how a PR lands: `squash`, `merge`, `rebase` or `any`. See below. |
174
174
  | `version` | `ask` | who makes the release call: `ask` (you, at Verified?), or `versioned` / `unversioned` for every flow |
175
175
  | `ask` | `on-change` | `on-change`: Release? answers itself when only release prep changed. `always`: ask every time. |
@@ -178,7 +178,7 @@ These go under `## pre-release` or `## release`. Either section works.
178
178
  | `recheck` | `prep-skip` | `prep-skip`: checks stay green across a commit that holds only the version bump and changelog. `always`: re-run them. |
179
179
  | `yolo` | `all` | `until-release`: a yolo given earlier never answers Release?. The gate asks, and only your answer to that question releases. |
180
180
  | `reflect` | `on-friction` | `always`: run the closing reflection on every finish |
181
- | `review` | `/flow-review` | the review step at pre-release |
181
+ | `review` | `/flow-review` | the review step at pre-release. `flow release` requires one on record (see [gates](gates.md#release-release)); set it empty to turn that off. |
182
182
  | `preflight` | — | runs in the worktree at `flow release` before anything ships, for example `docker build .` |
183
183
  | `artifact` | — | proves the release was published, for example `npm view <pkg>@{version} version` |
184
184
  | `releases` | `true` | `false` skips creating a forge release |
@@ -24,7 +24,7 @@ import path from "node:path";
24
24
  import { Type } from "typebox";
25
25
  import { compact, defineTool, isToolCallEventType, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
26
26
  import { type ExtensionAPI, type ToolCallEvent, type ToolCallEventResult, type TurnEndEvent, type TurnEndEventResult } from "@earendil-works/pi-coding-agent";
27
- import { ALLOW_REWRITE, applicableItems, openItemsNote, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, WORKER_STEER_AT, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, hollowStop, hollowStopNote, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
27
+ import { ALLOW_REWRITE, applicableItems, openItemsNote, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, WORKER_STEER_AT, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, hollowStop, hollowStopNote, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, worktreeWorkGuard, flowArgsShapeError, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
28
28
  import { loadProject } from "../src/projectmd.ts";
29
29
  import { bashTimeout, requireTimeout, timeoutClass } from "../src/timeouts.ts";
30
30
  import { AGENT_MARK, operatorCommandAsks, operatorCommandCorrection, viewHeader, askLine, type GateView } from "../src/present.ts";
@@ -232,6 +232,8 @@ export default function devFlow(pi: ExtensionAPI) {
232
232
  args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug"]' }),
233
233
  }),
234
234
  execute: async (id, params, signal, onUpdate, ctx) => {
235
+ const shape = flowArgsShapeError((params as { args?: unknown }).args);
236
+ if (shape) return { content: [{ type: "text", text: shape }], details: {}, isError: true };
235
237
  const root = await flowRoot(ctx.cwd);
236
238
  // the agent's call never opens a dialog (#181): a dialog inside a tool call blocks the turn, so nobody
237
239
  // can talk to the agent while it waits, and the agent cannot see who answered. Gates answer with the
@@ -498,8 +500,17 @@ export default function devFlow(pi: ExtensionAPI) {
498
500
  } else if (newCommits.trim() || dirty) {
499
501
  parts.push("note: the reviewer changed the tree — treat its verdict with suspicion and inspect the change");
500
502
  }
503
+ if (wop === "review" && report.found) {
504
+ // gh#233: the record flow release reads — a review ran for this flow. The verdict stays advisory.
505
+ const cur = readState(root, st.slug);
506
+ if (cur && (cur.stage === "implement" || cur.stage === "pre-release")) {
507
+ const head = (headAfter || "").trim();
508
+ cur.review = { by: "worker", at: now(), ...(head ? { head } : {}), ...(report.verdict ? { verdict: report.verdict } : {}) };
509
+ writeState(root, cur);
510
+ }
511
+ }
501
512
  parts.push(`transcript: ${transcript || "(unknown)"}`);
502
- parts.push(wop === "implement" ? "Next: read the report, decide what is left, and drive the gates yourself." : "Advisory review: fix what is real (inline is fine for small things), then carry on — no gate waits on this verdict.");
513
+ parts.push(wop === "implement" ? "Next: read the report, decide what is left, and drive the gates yourself." : "Review recorded for flow release; the verdict itself is advisory: fix what is real (inline is fine for small things), then carry on.");
503
514
  return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
504
515
  }
505
516
 
@@ -515,7 +526,7 @@ export default function devFlow(pi: ExtensionAPI) {
515
526
  name: "flow_stage",
516
527
  label: "Stage worker",
517
528
  description:
518
- 'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (advisory: no gate depends on it); op "reflect" (any stage; flow finish runs it itself before cleanup) — a fresh read-only reviewer of this session\'s transcript and every worker transcript that returns classified reflection findings (docs / code / plugin) with a fold-or-drop recommendation each, for the operator to decide. The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Delegate an implement slice when it is in the plan, provable by flow check, needs no operator input mid-slice and is big enough (≈4+ files or heavy reading) to crowd this context; small work, small fixes, mid-debug work, operator-judged work and final integration stay inline (criteria: references/implement.md). In pi-web the worker appears in the session\'s Agents menu as a subagent (running while it works, then its final status); the opened transcript holds its report.',
529
+ 'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (the verdict is advisory; that a review ran is recorded — flow release requires a review on record); op "reflect" (any stage; flow finish runs it itself before cleanup) — a fresh read-only reviewer of this session\'s transcript and every worker transcript that returns classified reflection findings (docs / code / plugin) with a fold-or-drop recommendation each, for the operator to decide. The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Delegate an implement slice when it is in the plan, provable by flow check, needs no operator input mid-slice and is big enough (≈4+ files or heavy reading) to crowd this context; small work, small fixes, mid-debug work, operator-judged work and final integration stay inline (criteria: references/implement.md). In pi-web the worker appears in the session\'s Agents menu as a subagent (running while it works, then its final status); the opened transcript holds its report.',
519
530
  promptSnippet: 'flow_stage(op: "implement"|"review"|"reflect", note, label?) — optional fresh-session worker for a big implement slice, an independent review, or a reflection (flow finish runs the closing one itself); gates stay with you; in pi-web workers show up as subagents in the Agents menu',
520
531
  parameters: Type.Object({
521
532
  op: Type.String({ description: '"implement" (a worker edits + commits a slice), "review" (read-only reviewer, findings + verdict) or "reflect" (read-only reviewer of the session transcripts, reflection findings + fold/drop recommendations)' }),
@@ -756,10 +767,14 @@ export default function devFlow(pi: ExtensionAPI) {
756
767
  return branchCache.get(at)!;
757
768
  };
758
769
  const worktrees = featureRefs(guardRoot).map((f) => f.worktreeAbs).filter((w): w is string => !!w);
770
+ // gh#235: a checkout/switch earlier in the chain moves the branch the later segments run on — the probe
771
+ // reads the branch before anything runs, so `git checkout team-test && git merge feat/x` was judged as a
772
+ // merge into main
773
+ const switched = new Map<string, string>();
759
774
  for (const g of inv.gitSegs) {
760
775
  const gitDir = g.dir ? path.resolve(ctx.cwd, g.dir) : ctx.cwd;
761
776
  const seg = gitInvocation(g.seg); // parsed once per segment — this runs on every bash call of every session
762
- const branch = await branchOf(g.dir);
777
+ const branch = switched.get(gitDir) ?? (await branchOf(g.dir));
763
778
  let pushRefs: PushRef[] | undefined;
764
779
  const gp = seg.pushes;
765
780
  if (gp.length) {
@@ -781,10 +796,18 @@ export default function devFlow(pi: ExtensionAPI) {
781
796
  }
782
797
  const reason = bashFlowGuard({ command: g.seg, branch, stage: bound?.stage ?? null, defaultBranch: cfg.defaultBranch, pushRefs, playbookChore, dir: gitDir, attribution: bound ? undefined : `not attributed to a bound feature (session ${key}; dev-flow ${loadedVersion() ?? "?"} at ${SELF_BUILD.dir}) — run flow use <slug> here if a binding is missing` });
783
798
  if (reason) return { block: true, reason };
799
+ // gh#232: a feature worktree takes its feature's commits and nothing else
800
+ const home = featureRefs(guardRoot).find((f) => f.worktreeAbs && (gitDir === f.worktreeAbs || gitDir.startsWith(f.worktreeAbs + path.sep)));
801
+ if (home) {
802
+ const wtReason = worktreeWorkGuard({ subs: seg.subs, command: g.seg, branch, home: { slug: home.state.slug, branch: home.state.branch, released: !!home.state.approvals.release, wt: path.relative(guardRoot, home.worktreeAbs!) || home.worktreeAbs! } });
803
+ if (wtReason) return { block: true, reason: wtReason };
804
+ }
784
805
  // A feature worktree stays on its feature branch: a side branch cut inside it repurposes the
785
806
  // worktree (and leaves it off its branch for the next gate); out-of-flow fixes get their own flow.
786
807
  const co = checkoutInvocation(g.seg);
787
808
  if (!co) continue;
809
+ // a path restore (`git checkout -- f`, `git checkout f`) is not a switch: only a branch that exists or is created moves
810
+ if (co.creates || (!/\s--(\s|$)/.test(g.seg) && (await sh(`git -C ${sq(gitDir)} rev-parse --verify -q ${sq(`refs/heads/${co.target}`)}`, ctx.cwd)).ok)) switched.set(gitDir, co.target);
788
811
  const homeWt = worktrees.find((w) => gitDir === w || gitDir.startsWith(w + path.sep));
789
812
  if (co.creates && homeWt) return { block: true, reason: `a feature worktree stays on its own branch — not creating ${co.target} in ${homeWt}; an unrelated fix is its own flow (flow start <slug> --patch)` };
790
813
  // Branch discipline: feature branches live in their worktree — never checked out or created (-b) in the main checkout
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.92.1",
3
+ "version": "0.93.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": [
@@ -39,8 +39,7 @@ criteria hold. Call it with an args array — `["start", "dark-mode"]`,
39
39
  - **Talk outcomes, not internals.** Chat is for the operator: what changed or
40
40
  is wrong, why it matters, in plain words and a few lines. Name a file or
41
41
  function only when they must act on it — no code-path walkthroughs or
42
- internal identifiers. Depth lives in plan.md, commits and the diff; give it
43
- in full when asked.
42
+ internal identifiers; give depth when asked.
44
43
  - **yolo** at a checkpoint → that gate with `--yolo --confirmed`; run the
45
44
  remaining gates back to back without asking, honoring guidance attached to
46
45
  the word ("yolo, patch bump", "yolo, no tag" → `--no-version`). Checks,
@@ -56,8 +55,9 @@ criteria hold. Call it with an args array — `["start", "dark-mode"]`,
56
55
  - **A guard blocking you means you skipped a stage or wrote outside your
57
56
  feature** — run the gate instead of working around it. A refusal lists what
58
57
  is missing: fix that, rerun.
59
- - **Every bash call has a timeout** (class default when unstated); pass
60
- `timeout` (seconds) for longer runs.
58
+ - **Every bash call has a timeout** (a class default when unstated).
59
+ - **Run a gate only after the git/gh step it reads has returned**, never in
60
+ the same batch.
61
61
  - Abandon a feature with `flow abort <slug>`. The repo's own AGENTS.md and
62
62
  project skills still apply.
63
63
 
@@ -10,7 +10,10 @@ tags are `versioning.pattern` rendered from it. No `versioning.file` → stop
10
10
  and settle the scheme with the operator; never invent one.
11
11
 
12
12
  1. **Review**: `/flow-review` the change; fix every **Must fix** and **Should
13
- fix**; `flow check` again if code changed.
13
+ fix**; `flow check` again if code changed. Then record it:
14
+ `flow review done "<verdict in a line>"` (a `flow_stage` review worker records
15
+ itself). `flow release` refuses until a review is on record; shipping without
16
+ one is the operator's word (`flow review --skip`, asked as **Skip review?**).
14
17
  - A fix that changes behaviour → `flow verify` again: it redeploys, then
15
18
  ask **Verified?** over the fixed build and run `flow verify --confirmed`
16
19
  on the answer (stays in pre-release; a standing yolo does not answer it).
@@ -35,14 +38,18 @@ and settle the scheme with the operator; never invent one.
35
38
  dropped or rewritten pending line, leftovers under `Unreleased`, and a
36
39
  changelog this branch never touched. `--no-fold-check` only on the
37
40
  operator's word.
38
- 4. No `flow check` is owed after the prep commit: the gate keeps green checks across a commit that
41
+ 4. **PR body**: if the repo has a pull-request template, write
42
+ `.dev-flow/<slug>/pr-body.md` from it (every section; the changelog entry; the
43
+ commit Verified? was given over). `flow release` opens the PR with it, and
44
+ refuses without it.
45
+ 5. No `flow check` is owed after the prep commit: the gate keeps green checks across a commit that
39
46
  holds only the bump and changelog, and runs any stale check itself.
40
- 5. **Run `flow release`.** By default (`ask = on-change`) it answers
47
+ 6. **Run `flow release`.** By default (`ask = on-change`) it answers
41
48
  Release? itself when the release call is on record and only the prep
42
49
  landed since Verified? — say in a few lines what the PR delivers (the
43
50
  changelog entry usually is that) and the version, and carry on with the
44
51
  release stage.
45
- 6. **It returned `NEEDS-OPERATOR Release?`** (it says why: code after
52
+ 7. **It returned `NEEDS-OPERATOR Release?`** (it says why: code after
46
53
  Verified?, no call on record, a stale build, `yolo = until-release`, a
47
54
  major bump, or the playbook's `ask = always`) → **ask Release? and
48
55
  stop**, with the same summary and the version. Report opening:
package/src/core.ts CHANGED
@@ -62,9 +62,19 @@ export interface FlowState {
62
62
  friction?: number; // process refusals, a gate refusing twice in a row, guard blocks and post-Verified? code changes this feature hit (isFriction; a red check alone is not one) — finish skips the closing reflection at 0 (playbook reflect = on-friction)
63
63
  reflectQuiet?: boolean; // finish skipped the closing reflection because the flow had no friction — with nothing else open, Finish? answers itself (release.finish = on-change)
64
64
  reviewDeploy?: { wt: string; slot: string; at: string }; // the tree (checkFingerprint) and dev slot `flow verify` deployed for the operator's review — a --confirmed over the same tree does not build and deploy it a second time
65
+ review?: FlowReview; // the pre-release review step ran (worker or inline) or the operator skipped it — flow release refuses without one (gh#233)
65
66
  aborted?: string; // flow abort on a feature whose worktree exists: the state is a deliberate abandoned-feature record (gh#138) — the doctor's git-consistency sweep must never flag its hand-removed worktree as drift
66
67
  }
67
68
 
69
+ /** A recorded pre-release review: `worker` (a flow_stage review worker reported), `inline` (the agent ran the
70
+ * playbook's review step and recorded it with `flow review done`), or `skipped` (the operator's word). */
71
+ export interface FlowReview {
72
+ by: "worker" | "inline" | "skipped";
73
+ at: string;
74
+ head?: string; // the worktree HEAD the review read — release names commits after it
75
+ verdict?: string;
76
+ }
77
+
68
78
  /** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features;
69
79
  * versionedOnly items ("(versioned)") presuppose a bump/tag and stand down on a --no-version flow (#166);
70
80
  * docs items ("(docs)") keep an implement item on a --docs flow, where implement items otherwise stand down (gh#207). */
@@ -568,6 +578,14 @@ export function versionArg(value: string | null, noVersion: boolean): { choice:
568
578
  * under Unreleased. The git-dependent proofs (touched, folded) skip with an advisory when no base
569
579
  * resolves; the content proofs always run (#97). Review/docs quality stays tier-2.
570
580
  */
581
+ /** gh#233: the playbook's review step is a release prerequisite, not a hint — a 566-line change shipped with
582
+ * no review because nothing recorded whether one ran. A docs flow and a release-only cut (nothing on the
583
+ * branch to read) owe none; `release.review = ""` opts the project out. Null when nothing is owed. */
584
+ export function reviewOwed(state: FlowState, cfg: Config): string | null {
585
+ if (!cfg.release.review || state.docs || state.releaseOnly || state.review) return null;
586
+ return `no review is recorded for this flow — run the playbook's review step (${cfg.release.review}, or flow_stage op "review"), fix what it finds, then record it: flow review done "<verdict in a line>" (a review worker records itself). To ship without a review, ask the operator; on their word: flow review --skip --confirmed`;
587
+ }
588
+
571
589
  export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep): string[] {
572
590
  const errs: string[] = [];
573
591
  if (state.stage !== "pre-release") errs.push(`stage is "${state.stage}", the release gate only applies to "pre-release"`);
@@ -582,7 +600,7 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
582
600
  // A --docs flow does not (#163): it changes the playbook/docs, which many projects keep out of a
583
601
  // user-facing changelog — an entry it writes is still welcome, just not proven.
584
602
  if (cfg.release.changelog && !state.docs) {
585
- if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — an unversioned release must record its entry there (under Unreleased)`);
603
+ if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — an unversioned release must record its entry there (under Unreleased), or set changelog = "" under ## release if this project keeps none`);
586
604
  else {
587
605
  if (prep.changelogChanged === false) errs.push(`${prep.changelog.file} is unchanged on this branch — an unversioned release must add its entry (under Unreleased)`);
588
606
  // an unversioned release must leave a trail someone can find later: the section is where it lives,
@@ -607,7 +625,7 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
607
625
  errs.push(`version ${prep.manifestVersion} is already tagged — bump the manifest to the next version`);
608
626
  }
609
627
  if (cfg.release.changelog) {
610
- if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — prepare the changelog`);
628
+ if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — prepare the changelog (a project that keeps none: set changelog = "" under ## release)`);
611
629
  else {
612
630
  const entry = prep.manifestVersion ? changelogEntry(prep.changelog.content, prep.manifestVersion) : "";
613
631
  if (prep.manifestVersion && !entry)
@@ -922,6 +940,8 @@ export interface MergeShapeFacts {
922
940
  ancestor: boolean | null;
923
941
  /** What the forge says landed the PR, when `gh`/`glab` could answer — the only way to tell a squash from a rebase. */
924
942
  forgeStyle?: MergeStyle | null;
943
+ /** Was a forge CLI (gh/glab) there to ask? false on a self-hosted forge: a null forgeStyle then means "unknown", not "no merged PR". */
944
+ forgeAsked?: boolean;
925
945
  /** Wording only. */
926
946
  branch?: string;
927
947
  defaultBranch?: string;
@@ -941,7 +961,13 @@ export function mergeShapeProof(policy: MergeStyle | "any" | undefined, facts: M
941
961
  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` };
942
962
  const landed = facts.forgeStyle ?? null;
943
963
  if (policy === "merge") {
944
- 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`);
964
+ // gh#237: "not an ancestor" is also what an unmerged PR and a stale origin/<default> look like — blame a
965
+ // squash only when the forge says one landed
966
+ if (!facts.ancestor && landed === "merge")
967
+ errors.push(`the forge reports ${br} merged as a merge commit, but it is not an ancestor of ${def} here — this clone's ${def} is behind the forge: git fetch origin, then re-run`);
968
+ else if (!facts.ancestor && !landed)
969
+ errors.push(`${br} is not an ancestor of ${def}, and the forge reports no merged PR for it — not merged yet, or merged moments ago and not fetched: let the merge finish, git fetch origin, then re-run${facts.forgeAsked === false ? " (no forge CLI answered here — a squash or rebase merge looks the same, and the playbook says merge = merge)" : ""}`);
970
+ else if (!facts.ancestor) errors.push(`the playbook says merge = merge, but ${br} is not an ancestor of ${def} — the PR was ${MERGE_PAST[landed!]}, which rewrites the branch's commits out of the release's ancestry`);
945
971
  else if (landed && landed !== "merge") errors.push(`the forge reports a ${landed} merge, but the playbook says merge = merge`);
946
972
  else return { errors, note: `merge shape matches the playbook: ${br} is an ancestor of ${def} (merge = merge)` };
947
973
  } else {
@@ -1195,6 +1221,22 @@ export function playbookOnlyChange(porcelain: string): boolean {
1195
1221
  return paths.length === 1 && PLAYBOOK_PATH.test(paths[0]);
1196
1222
  }
1197
1223
 
1224
+ /** gh#234, gh#228: what `flow finish` says about commits on the local default branch that origin does not have.
1225
+ * `flow init --track` commits the playbook to local main and nothing ever pushes it, so "push the release"
1226
+ * sent the agent to merge origin into local main and push the default branch directly. Playbook-only commits
1227
+ * are setup, not an unpushed release: a note, never a block. Anything else is named, with the branch the
1228
+ * main checkout is actually on — "git push origin main" from a checkout on another branch pushes nothing
1229
+ * you meant. Null when nothing is local-only. */
1230
+ export function localDefaultAhead(o: { defaultBranch: string; checkoutBranch: string; commits: { line: string; files: string[] }[] }): { block: string | null; note: string } | null {
1231
+ const { defaultBranch: d, checkoutBranch: cur, commits } = o;
1232
+ if (!commits.length) return null;
1233
+ const list = `${commits.slice(0, 5).map((c) => c.line).join(" | ")}${commits.length > 5 ? ` …(${commits.length - 5} more)` : ""}`;
1234
+ const where = cur && cur !== d ? ` (the main checkout is on ${cur}, not ${d} — this is the local ${d} branch)` : "";
1235
+ if (commits.every((c) => c.files.length > 0 && c.files.every((f) => PLAYBOOK_PATH.test(f))))
1236
+ return { block: null, note: ` local ${d} carries ${commits.length} playbook commit(s) origin/${d} does not have (${list})${where} — playbook tracking from flow init --track; they reach origin through a docs flow, never a direct push to ${d}. To line local ${d} up with origin meanwhile: git -C <main checkout> rebase origin/${d} ${d}.` };
1237
+ return { block: `local ${d} has ${commits.length} commit(s) origin/${d} does not have${where}: ${list} — finish removes the flow state, so nothing may stay local-only. If these are release chores, push them (git push origin ${d}); if they are work that belongs in a flow, move them onto a branch and ship them through one; then re-run flow finish`, note: "" };
1238
+ }
1239
+
1198
1240
  /** The operator's authorisation for rewriting a branch that is already pushed — same contract as
1199
1241
  * DEV_FLOW_ALLOW_MAIN: the guard prints it, the operator grants it, the agent types it. (#83) */
1200
1242
  export const ALLOW_REWRITE = "DEV_FLOW_ALLOW_REWRITE=1";
@@ -1307,6 +1349,36 @@ export function checkoutInvocation(command: string): { target: string; creates:
1307
1349
  return target ? { target: unquote(target), creates: false } : null;
1308
1350
  }
1309
1351
 
1352
+ /** The branch a `git branch <name>` creates, or null (listing, deleting, renaming, copying and the query flags only read
1353
+ * or move what exists — a rename is still not new work). */
1354
+ export function branchCreateInvocation(command: string): string | null {
1355
+ const m = command.match(/\bgit\s+(?:-C\s+\S+\s+)?branch\b([^;|&\n]*)/);
1356
+ if (!m) return null;
1357
+ const tok = m[1].trim().split(/\s+/).filter(Boolean);
1358
+ if (tok.some((t) => /^(-d|-D|--delete|-m|-M|--move|-c|-C|--copy|-l|--list|-a|--all|-r|--remotes|-v|-vv|--verbose|--contains|--no-contains|--merged|--no-merged|--points-at|--show-current|--edit-description|-u|--set-upstream-to(=.*)?|--unset-upstream|--format(=.*)?|--sort(=.*)?)$/.test(t))) return null;
1359
+ const name = tok.find((t) => !t.startsWith("-"));
1360
+ return name ? unquote(name) : null;
1361
+ }
1362
+
1363
+ /** gh#232: a feature worktree holds its feature and nothing else. After `flow release` recorded the release, an
1364
+ * agent cut a side branch in the same worktree, committed a redesign on it and merged it to production with no
1365
+ * plan, check, review or Verified? — every gate is keyed to the feature branch, so none of them saw it. Judged
1366
+ * per git segment that runs inside a feature worktree: new branches, commits or merges on any branch but the
1367
+ * feature's own, and commits once its release is recorded, are refused. Null when the segment may run. */
1368
+ export function worktreeWorkGuard(o: { subs: string[]; command: string; branch: string; home: { slug: string; branch: string; released: boolean; wt: string } }): string | null {
1369
+ const { subs, home } = o;
1370
+ const newFlow = `follow-up work is its own flow: flow start <new-slug> (--patch for a small fix) — it gets a worktree, plan, checks, review and Verified? of its own`;
1371
+ const created = subs.includes("branch") ? branchCreateInvocation(o.command) : null;
1372
+ if (created) return `a feature worktree stays on its own branch — not creating ${created} in ${home.wt}; ${newFlow}`;
1373
+ const writes = subs.includes("commit") || subs.includes("merge") || subs.includes("cherry-pick") || subs.includes("revert");
1374
+ if (!writes) return null;
1375
+ if (o.branch && home.branch && o.branch !== home.branch)
1376
+ return `${home.wt} is ${home.slug}'s worktree (branch ${home.branch}), but it is on ${o.branch} — work committed here skips every gate of ${home.slug}; switch back (git switch ${home.branch}) — ${newFlow}`;
1377
+ if (home.released)
1378
+ return `${home.slug}'s release is recorded — its worktree takes no new commits (they would never ship through a gate); ${newFlow}. Release chores belong in the main checkout; flow finish closes ${home.slug}`;
1379
+ return null;
1380
+ }
1381
+
1310
1382
  // ------------------------------------------------------- project safety rules
1311
1383
 
1312
1384
  /** One flow-guard rule: `pattern` is a JS regex source (deny/confirm) or a repo-relative path (protect/forbid). */
@@ -1568,6 +1640,17 @@ export function featureTmpDir(dfDir: string, slug: string): string {
1568
1640
  return path.join(dfDir, slug, "tmp");
1569
1641
  }
1570
1642
 
1643
+ /** gh#243: the per-flow scratch dir is a TMPDIR every tool writes into, and tooling that never removes its
1644
+ * `mktemp` dirs left ~1,000 of them after one flow. Which entries a gate may sweep: names shaped like mktemp
1645
+ * output (`tmp.XXXXXX`, `<prefix>.XXXXXX`, `<prefix>-XXXXXX` — a 6+ char random tail with a digit or mixed
1646
+ * case) untouched for `maxAgeMs`. A name the project chose (a dev server's cache dir) never matches, and
1647
+ * anything recent may still be in use. */
1648
+ export function staleScratch(entries: { name: string; mtimeMs: number }[], now: number, maxAgeMs = 3_600_000): string[] {
1649
+ const tail = /^(?:tmp|[\w-]+?)[.-]([A-Za-z0-9]{6,})$/;
1650
+ const randomish = (t: string) => /\d/.test(t) || (/[a-z]/.test(t) && /[A-Z]/.test(t));
1651
+ return entries.filter((e) => { const m = tail.exec(e.name); return !!m && randomish(m[1]) && now - e.mtimeMs > maxAgeMs; }).map((e) => e.name);
1652
+ }
1653
+
1571
1654
  /** The env every process of a bound feature gets: TMPDIR in the feature's scratch dir, and that dir as a
1572
1655
  * git ceiling. The scratch dir sits inside the repo, so without the ceiling git walks up out of a
1573
1656
  * test's mkdtemp fixture and answers with the enclosing checkout — a suite asserting "no repo here"
@@ -2308,13 +2391,16 @@ export function nextHint(state: FlowState, cfg: Config): string {
2308
2391
  case "pre-release": {
2309
2392
  // gh#198: the release call made with Verified? decides which prep this is
2310
2393
  const vc = state.versionChoice;
2394
+ // gh#233: flow release refuses until the review is on record — the hint says how it gets there
2395
+ const rv = reviewOwed(state, cfg) ? `${cfg.release.review} (then record it: flow review done "<verdict>")` : cfg.release.review && state.review ? "review on record" : "";
2396
+ const review = rv ? `${rv}, ` : "";
2311
2397
  const auto = cfg.release.ask !== "always" ? " (release.ask = on-change: it asks Release? only when something beyond the prep changed)" : "";
2312
2398
  if (vc === "unreleased")
2313
- return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${cfg.release.changelog && !state.docs ? `, add this flow's line under Unreleased in ${cfg.release.changelog} (the call is merge unreleased: no bump)` : ""}; show the PR summary, then run flow release${auto || " and ask Release?"}`;
2399
+ return `${review}fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${cfg.release.changelog && !state.docs ? `, add this flow's line under Unreleased in ${cfg.release.changelog} (the call is merge unreleased: no bump)` : ""}; show the PR summary, then run flow release${auto || " and ask Release?"}`;
2314
2400
  const prep = [cfg.release.changelog ? `prepare ${cfg.release.changelog} (fold Unreleased lines verbatim)` : "", cfg.versioning.file ? `bump version in ${cfg.versioning.file}${isBumpKind(vc) ? ` to ${bumpVersion(state.versionFrom, vc) ?? `the next ${vc}`} (a ${vc} release, the operator's call — the gate counts it from the newest tag, so a flow that released first moves the number)` : vc && vc !== "next" ? ` to ${vc} (the operator's call)` : ""}` : ""].filter(Boolean).join(" and ");
2315
- if (vc && prep) return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs, ${prep}; show the PR summary, version and changelog, then run flow release${auto || " and ask Release?"}`;
2316
- if (state.docs && prep) return `${cfg.release.review}, fix must/should; a docs flow usually ships unversioned — ask the operator (flow release --no-version on their word); versioned instead: ${prep}; then ask Release? and run flow release`;
2317
- return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${prep ? `, ${prep}` : ""}; show the PR summary, version and changelog, ask Release? and run flow release`;
2401
+ if (vc && prep) return `${review}fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs, ${prep}; show the PR summary, version and changelog, then run flow release${auto || " and ask Release?"}`;
2402
+ if (state.docs && prep) return `${review}fix must/should; a docs flow usually ships unversioned — ask the operator (flow release --no-version on their word); versioned instead: ${prep}; then ask Release? and run flow release`;
2403
+ return `${review}fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${prep ? `, ${prep}` : ""}; show the PR summary, version and changelog, ask Release? and run flow release`;
2318
2404
  }
2319
2405
  case "release":
2320
2406
  if (state.approvals.release) return `release recorded — commit and push any release chores in the main checkout (DEV_FLOW_ALLOW_MAIN=1 for the pre-commit hook), then flow finish (closing reflection first; its fold/drop answer is Finish?)`;
@@ -2323,6 +2409,41 @@ export function nextHint(state: FlowState, cfg: Config): string {
2323
2409
  }
2324
2410
  }
2325
2411
 
2412
+ /** gh#242: a failing check's output, trimmed for the gate result. The last lines alone pointed away from the
2413
+ * failure — a lint step's tail was its pre-existing warnings and "script exited with code 1", and the two files
2414
+ * it refused were 200 lines up. When the output is longer than the tail, the error-level lines that the tail
2415
+ * cuts off are lifted above it, each with the line before it (formatters name the file there), capped. */
2416
+ export function failTail(out: string, n = 15, maxErr = 12): string {
2417
+ const lines = out.split("\n").filter((l) => l.trim());
2418
+ if (lines.length <= n) return out;
2419
+ const cut = lines.length - n;
2420
+ const isErr = (l: string) => !/\bwarn(?:ing)?s?\b/i.test(l) && /(^|[\s[(:])(?:error|errors|ERR!|FAIL(?:ED|URE)?|fail(?:ed|ure)?|panic(?:ked)?|exception|Traceback)\b|[×✖✗]|^\s*E\s{2,}|AssertionError/i.test(l);
2421
+ const pick = new Set<number>();
2422
+ for (let i = 0; i < cut && pick.size < maxErr * 2; i++)
2423
+ if (isErr(lines[i])) {
2424
+ if (i > 0 && !isErr(lines[i - 1])) pick.add(i - 1);
2425
+ pick.add(i);
2426
+ }
2427
+ const clip = (l: string) => (l.length > 240 ? `${l.slice(0, 240)}…` : l);
2428
+ const head = [...pick].sort((a, b) => a - b).slice(0, maxErr * 2).map((i) => clip(lines[i]));
2429
+ return `${head.length ? `error lines from the ${cut} cut off:\n${head.join("\n")}\n…\n` : `…(${cut} lines)…\n`}${lines.slice(-n).join("\n")}`;
2430
+ }
2431
+
2432
+ /** gh#238: the flow tool's `args` must be an array of strings. A call whose array arrived marshalled as one JSON
2433
+ * string was dispatched with the whole blob as the subcommand, and the refusal ("unknown subcommand …" plus the
2434
+ * full usage) never said the shape was wrong. Null when the shape is fine. */
2435
+ export function flowArgsShapeError(args: unknown): string | null {
2436
+ if (!Array.isArray(args)) return `args must be an array of strings, e.g. ["status"] or ["start", "my-slug"] — this arrived as ${args === null ? "null" : typeof args}`;
2437
+ if (args.some((a) => typeof a !== "string")) return `args must be an array of strings — element(s) ${args.map((a, i) => (typeof a === "string" ? -1 : i)).filter((i) => i >= 0).join(", ")} are not strings`;
2438
+ if (args.length === 1 && /^\s*\[/.test(args[0] as string)) {
2439
+ let inner: unknown = null;
2440
+ try { inner = JSON.parse(args[0] as string); } catch { /* not JSON: still looks like a marshalled array */ }
2441
+ const shown = Array.isArray(inner) ? JSON.stringify(inner) : (args[0] as string).slice(0, 120);
2442
+ return `args must be an array of strings; this arrived as one string holding an array (${shown}) — pass the elements themselves: args: ${shown}`;
2443
+ }
2444
+ return null;
2445
+ }
2446
+
2326
2447
  /** Stable token prefixing every no-UI operator refusal, so a headless orchestrator can route refusals without grepping prose. */
2327
2448
  export const NEEDS_OPERATOR = "NEEDS-OPERATOR";
2328
2449
 
@@ -2491,6 +2612,7 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2491
2612
  ? "- Project checks: none — this is a docs flow. The gates skip the project's commands and no setup ran in this worktree (no installed dependencies): do not install, build or run the test suite; check the docs against the code by reading."
2492
2613
  : `- Project checks (run them before you report${o.preamble?.length ? ", in a shell that ran the setup below first" : ""}):\n${checks}`,
2493
2614
  "- You hold no flow tool: gates, checkpoints and the operator stay with the driving session.",
2615
+ "- Scratch goes in $TMPDIR (the feature's tmp dir); remove what you create there — `d=$(mktemp -d) && …; rm -rf \"$d\"`.",
2494
2616
  "",
2495
2617
  ...workerGuardLines(o.guard),
2496
2618
  ...(o.preamble?.length && !o.docs
@@ -2651,11 +2773,13 @@ export function digestTranscript(jsonl: string, opts: { maxChars?: number } = {}
2651
2773
  const res = textOf(m.content);
2652
2774
  if (m.isError) {
2653
2775
  errors++;
2654
- out.push(`${L} ERROR ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 400)}`);
2776
+ // gh#239: a guard block reaches the transcript as an error result whose text is the guard's reason;
2777
+ // the operator-ask ones lead with the marker. A successful result is never a guard event, whatever
2778
+ // words its output quotes — matching NEEDS-OPERATOR anywhere in a success tagged a grep as a block.
2779
+ const guardAsk = name !== "flow" && name !== "flow_stage" && res.trimStart().startsWith(NEEDS_OPERATOR);
2780
+ out.push(`${L} ${guardAsk ? "GUARD" : "ERROR"} ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 400)}`);
2655
2781
  } else if (name === "flow" || name === "flow_stage") {
2656
2782
  out.push(`${L} ↳ ${clip(res, name === "flow_stage" ? 600 : 400)}`);
2657
- } else if (/NEEDS-OPERATOR/.test(res.slice(0, 600))) {
2658
- out.push(`${L} GUARD ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 300)}`);
2659
2783
  }
2660
2784
  }
2661
2785
  }
package/src/present.ts CHANGED
@@ -111,10 +111,13 @@ export function stageLine(state: FlowState, cfg: Config, f: StageFacts = {}): st
111
111
  if (stage === "implement" || stage === "pre-release") {
112
112
  if (f.ahead !== undefined) fields.push(`commits \`${f.ahead} ahead, ${f.uncommitted ?? 0} uncommitted\``);
113
113
  if (!state.docs) fields.push(`checks ${checksSummary(state)}`);
114
- const items = applicableItems(cfg, state, stage).length;
114
+ const list = applicableItems(cfg, state, stage);
115
115
  const pend = checklistPending(cfg, state, stage);
116
- if (pend) fields.push(`tier-2 \`${pend} open\` ?`);
117
- else if (items) fields.push("tier-2 `confirmed` ✓");
116
+ // gh#241: name them — a bare count made the agent re-read project.md, and implement's and pre-release's
117
+ // lists are different checklists, so the count "moved" with no explanation
118
+ const clip = (t: string) => (t.length > 40 ? `${t.slice(0, 39)}…` : t);
119
+ if (pend) fields.push(`tier-2 \`${pend} open\` ? (## ${stage}: ${list.slice(0, 4).map((i) => `"${clip(i.text)}"`).join(" · ")}${list.length > 4 ? ` +${list.length - 4}` : ""})`);
120
+ else if (list.length) fields.push("tier-2 `confirmed` ✓");
118
121
  }
119
122
  if (stage === "pre-release" || stage === "release") {
120
123
  const version = state.noVersion ? "version `no-version` ✓" : state.releaseVersion ? `version \`${state.releaseVersion}\` ✓` : state.versionChoice && state.versionChoice !== "next" && state.versionChoice !== "unreleased" ? `version \`${state.versionChoice}\` ✓` : f.manifest ? `version \`${f.manifest}\` ~` : "version `pending` ?";
package/src/projectmd.ts CHANGED
@@ -160,7 +160,10 @@ export function parseProjectMd(text: string): ParsedMd {
160
160
  return;
161
161
  }
162
162
  if (inFence === "flow") {
163
- const m = line.match(/^\s*([A-Za-z][\w.]*)\s*=\s*(.+?)\s*$/);
163
+ // gh#226: an empty value is the opt-out (`changelog =`, `changelog = ""`) — `(.+?)` read `key = ` as " " and
164
+ // `""` as a literal, so a project could not say "no changelog" at all
165
+ const m0 = line.match(/^\s*([A-Za-z][\w.]*)\s*=\s*(.*?)\s*$/);
166
+ const m = m0 ? ([m0[0], m0[1], m0[2].replace(/^(["'])\1$/, "")] as const) : null;
164
167
  if (!m || !stage) {
165
168
  if (line.trim() && !line.trim().startsWith("#")) p.hard.push(`${where}: expected \`key = value\` inside flow block`);
166
169
  } else if (!MD_STAGES.includes(stage as MdStage)) {
@@ -280,6 +283,17 @@ export function mdToConfig(p: ParsedMd): Config {
280
283
  const rel = (nested as { release?: { releases?: unknown } }).release;
281
284
  if (rel && typeof rel.releases === "string") rel.releases = !/^(no|false)$/i.test(rel.releases);
282
285
  mergeInto(c, nested);
286
+ // gh#226: an empty value in the playbook is an explicit opt-out (`changelog =`), not "keep the default" —
287
+ // applyAnswer drops "" (that is the answers' meaning of unset), so the empties are set here, string keys only
288
+ for (const stage of MD_STAGES)
289
+ for (const [key, val] of Object.entries(p.flow[stage])) {
290
+ if (val !== "" || !key.includes(".")) continue; // a top-level key (defaultBranch, worktreeDir…) has no "none"
291
+ const segs = key.split(".");
292
+ const leaf = segs.pop()!;
293
+ let at: Record<string, unknown> | undefined = c as unknown as Record<string, unknown>;
294
+ for (const sg of segs) at = at && typeof at[sg] === "object" && at[sg] !== null ? (at[sg] as Record<string, unknown>) : undefined;
295
+ if (at && (at[leaf] === undefined || typeof at[leaf] === "string")) at[leaf] = "";
296
+ }
283
297
  // a flow-guard block is the whole rule set; with none in project.md the DEFAULTS (empty) stand
284
298
  if (GUARD_VERBS.some((v) => p.guard[v].length)) c.guard = structuredClone(p.guard);
285
299
  // one check per name: an explicit flow-check block wins over the `test =` / `health =` shorthand
@@ -533,14 +547,34 @@ export function doctorFindings(root: string, cfg: Config, md: ParsedMd | null):
533
547
  if (!existsSync(mf)) f.push(`versioning.file "${cfg.versioning.file}" does not exist`);
534
548
  else if (!parseVersion(cfg.versioning.file, readFileSync(mf, "utf8"))) f.push(`versioning.file "${cfg.versioning.file}": no parsable version found`);
535
549
  }
536
- // drift: `npm|pnpm|yarn|bun run <script>` where the script no longer exists
537
- let pkgScripts: Record<string, string> | null = null;
538
- const pkgRaw = existsSync(path.join(root, "package.json")) ? safeJson(readFileSync(path.join(root, "package.json"), "utf8")) : null;
539
- if (pkgRaw && typeof pkgRaw === "object" && typeof (pkgRaw as { scripts?: unknown }).scripts === "object") pkgScripts = (pkgRaw as { scripts: Record<string, string> }).scripts;
550
+ // drift: `npm|pnpm|yarn|bun run <script>` where the script no longer exists — judged against the package.json
551
+ // the command actually runs in (gh#227): a leading `cd <dir> &&`, or npm --prefix / pnpm -C / yarn --cwd
552
+ const scriptsAt = new Map<string, Record<string, string> | null>();
553
+ const scriptsOf = (dir: string): Record<string, string> | null => {
554
+ if (!scriptsAt.has(dir)) {
555
+ const pj = path.join(root, dir, "package.json");
556
+ const raw = existsSync(pj) ? safeJson(readFileSync(pj, "utf8")) : null;
557
+ scriptsAt.set(dir, raw && typeof raw === "object" && typeof (raw as { scripts?: unknown }).scripts === "object" ? (raw as { scripts: Record<string, string> }).scripts : null);
558
+ }
559
+ return scriptsAt.get(dir)!;
560
+ };
540
561
  const cmdList = [...Object.entries(cfg.commands).map(([k, v]) => [`commands.${k}`, v!] as [string, string]), ...cfg.checkList.map((c) => [`check ${c.name}`, c.cmd] as [string, string])];
541
562
  for (const [label, cmd] of cmdList) {
542
- const run = cmd.match(/\b(?:npm|pnpm|yarn|bun)\s+run\s+([\w:.-]+)/);
543
- if (run && pkgScripts && !(run[1] in pkgScripts)) f.push(`${label} runs "run ${run[1]}" but package.json has no such script`);
563
+ let dir = ".";
564
+ for (const seg of cmd.split(/&&|;|\|\||\n/)) {
565
+ const cd = seg.match(/^\s*cd\s+(['"]?)([^'"\s]+)\1\s*$/);
566
+ if (cd) {
567
+ // only a relative cd is followable; an absolute or $VAR one leaves the package.json unknown
568
+ dir = /^[\w.][\w./-]*$/.test(cd[2]) ? path.join(dir, cd[2]) : "";
569
+ continue;
570
+ }
571
+ const run = seg.match(/\b(npm|pnpm|yarn|bun)\b(.*?)\s+run\s+([\w:.-]+)/);
572
+ if (!run || !dir) continue;
573
+ const pre = run[2].match(/(?:--prefix|-C|--cwd|--dir)[=\s]+(['"]?)([^'"\s]+)\1/);
574
+ const at = pre ? (/^[\w.][\w./-]*$/.test(pre[2]) ? path.join(dir, pre[2]) : "") : dir;
575
+ const scripts = at ? scriptsOf(at) : null;
576
+ if (scripts && !(run[3] in scripts)) f.push(`${label} runs "run ${run[3]}" but ${at === "." ? "" : `${at}/`}package.json has no such script`);
577
+ }
544
578
  for (const tok of cmd.split(/\s+/)) {
545
579
  // only root-relative paths are probeable — checks run in the worktree, where `../../docker/.env` is correct
546
580
  if (/^[\w][\w-]*\/[\w./-]+$/.test(tok) && /\.\w+$/.test(tok) && !existsSync(path.join(root, tok))) {
@@ -1,10 +1,10 @@
1
1
  /** dev-flow runtime — Shared runtime: shell, paths, flow state, sessions and claims, skill core, compaction pacing. Moved out of extensions/dev-flow.ts as is (exports added). */
2
2
  import { exec } from "node:child_process";
3
- import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { compact, SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
7
- import { checklistPending, claimBlocks, classifyMergeHistory, cmpVersions, detectForge, extractSkillCore, featureBranchPrefix, healthRetry, parseMergeStyle, parseLsRemoteTags, pluginVersion, reflectItems, sessionRunsOlderBuild, listFiles, shouldSelfCompact, sq, featureTmpDir, featureTmpEnv, mainCheckoutRoot, type ReflectItem, type Config, type FeatureRef, type FlowState, type SessionClaim } from "../core.ts";
7
+ import { checklistPending, claimBlocks, classifyMergeHistory, cmpVersions, detectForge, extractSkillCore, featureBranchPrefix, healthRetry, parseMergeStyle, parseLsRemoteTags, pluginVersion, reflectItems, sessionRunsOlderBuild, listFiles, shouldSelfCompact, sq, featureTmpDir, featureTmpEnv, staleScratch, mainCheckoutRoot, type ReflectItem, type Config, type FeatureRef, type FlowState, type SessionClaim } from "../core.ts";
8
8
  import { loadProject, parseProjectMd, setPlaybookKey } from "../projectmd.ts";
9
9
  import { bashTimeout } from "../timeouts.ts";
10
10
  import { type RunResult, type Session } from "./checks.ts";
@@ -236,7 +236,7 @@ export async function releaseTags(root: string): Promise<string[] | null> {
236
236
  }
237
237
 
238
238
  export const GATE_HELP =
239
- "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n>[,<n>…] [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] [--version=<v>|--no-version] | release [--yolo|--version=<v>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — verify --confirmed carries the operator's release call: --version=<v> (ship that version) or --no-version (merge unreleased), asked with Verified?; release takes the same flags when the call changed — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped) — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
239
+ "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n>[,<n>…] [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | review [done <verdict>|--skip] | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] [--version=<v>|--no-version] | release [--yolo|--version=<v>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — verify --confirmed carries the operator's release call: --version=<v> (ship that version) or --no-version (merge unreleased), asked with Verified?; release takes the same flags when the call changed — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped) — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — review records the pre-release review flow release requires: done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
240
240
  export const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
241
241
  export const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
242
242
  export const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -507,6 +507,21 @@ export function featureEnv(root: string, state: FlowState): Record<string, strin
507
507
  return featureTmpEnv(dir);
508
508
  }
509
509
 
510
+ /** gh#243: drop stale mktemp leftovers from the feature's scratch dir (staleScratch decides which). Run where a
511
+ * gate runs the project's commands; best effort — a sweep that cannot read or remove something skips it. */
512
+ export function sweepScratch(root: string, state: FlowState, now = Date.now()): number {
513
+ const dir = featureTmpDir(dfDir(root), state.slug);
514
+ let entries: { name: string; mtimeMs: number }[] = [];
515
+ try {
516
+ entries = readdirSync(dir).map((name) => { try { return { name, mtimeMs: statSync(path.join(dir, name)).mtimeMs }; } catch { return { name, mtimeMs: now }; } });
517
+ } catch { return 0; }
518
+ let n = 0;
519
+ for (const name of staleScratch(entries, now)) {
520
+ try { rmSync(path.join(dir, name), { recursive: true, force: true }); n++; } catch { /* in use or not ours: leave it */ }
521
+ }
522
+ return n;
523
+ }
524
+
510
525
  /** Per-cwd cache of the main checkout a linked worktree belongs to (null = not a linked worktree) —
511
526
  * every hook resolves its root through flowRoot, so git is asked once per directory. */
512
527
  export const mainCheckoutCache = new Map<string, string | null>();
@@ -3,10 +3,10 @@ import { existsSync, readFileSync, statfsSync } from "node:fs";
3
3
  import { createServer } from "node:net";
4
4
  import { freemem } from "node:os";
5
5
  import path from "node:path";
6
- import { AGENT_MARK, checkFingerprint, DEFAULTS, freshenChecks, healthProbe, prepOnlyChange, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
6
+ import { AGENT_MARK, checkFingerprint, DEFAULTS, failTail, freshenChecks, healthProbe, prepOnlyChange, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
7
7
  import { loadProject } from "../projectmd.ts";
8
8
  import { agentText, presentGate, type GateView, type StageFacts } from "../present.ts";
9
- import { atomicWrite, boundFeature, buildSkew, dfDir, featDir, featureEnv, flagValue, gateCwd, initiated, mergeBase, now, originUrl, readState, runHealthProbe, sh, tail, worktreeAbs, writeState } from "./base.ts";
9
+ import { atomicWrite, boundFeature, buildSkew, dfDir, featDir, featureEnv, sweepScratch, flagValue, gateCwd, initiated, mergeBase, now, originUrl, readState, runHealthProbe, sh, tail, worktreeAbs, writeState } from "./base.ts";
10
10
  import { type GateCtx } from "./gates.ts";
11
11
 
12
12
  /** The port this flow's dev deploy uses: the operator's pick for it, else the playbook default. */
@@ -200,6 +200,7 @@ export async function runChecks(root: string, state: FlowState, cfg: Config, che
200
200
  const lines: string[] = [];
201
201
  let failed = false;
202
202
  const ran: string[] = [];
203
+ sweepScratch(root, state);
203
204
  for (const c of checks) {
204
205
  // health is the same probe `flow health` runs: seeded first, retried within healthWait
205
206
  const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state), undefined, featureEnv(root, state));
@@ -211,7 +212,7 @@ export async function runChecks(root: string, state: FlowState, cfg: Config, che
211
212
  state.checks[c.name] = { ok: res.ok, at: now() };
212
213
  ran.push(c.name);
213
214
  const tried = triedNote((res as { attempts?: number }).attempts ?? 1);
214
- lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd}${tried})${res.ok ? "" : `\n${tail(res.out)}`}`);
215
+ lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd}${tried})${res.ok ? "" : `\n${failTail(res.out)}`}`);
215
216
  if (!res.ok) failed = true;
216
217
  }
217
218
  await stampChecks(root, state, ran);
@@ -258,12 +259,32 @@ export const triedNote = (attempts: number) => (attempts > 1 ? `, ${attempts} at
258
259
  * tracked content (a hash of the uncommitted diff) and HEAD. Null when git cannot answer — a
259
260
  * measurement failure must never mark a green record stale (see freshenChecks). */
260
261
  export async function worktreeFingerprint(cwd: string): Promise<string | null> {
261
- const st = await sh("git status --porcelain", cwd);
262
- if (!st.ok) return null;
263
- const diff = await sh("git diff HEAD --no-color | git hash-object --stdin", cwd);
264
- const head = await sh("git rev-parse HEAD", cwd);
265
- if (!diff.ok || !head.ok) return null;
266
- return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
262
+ // gh#231: the fingerprint is the tree's CONTENT — path → blob for every tracked and untracked file as it is on
263
+ // disk. It used to hash HEAD + status + diff, so a check run over an uncommitted fix went stale the moment
264
+ // that same fix was committed, and the next gate re-ran a minute-long suite over an identical tree.
265
+ // Nothing is written: index blob ids for clean paths, `git hash-object` (no -w) for changed and untracked ones.
266
+ const ls = await sh("git ls-files -s -z", cwd);
267
+ const changed = await sh("git ls-files -m -o --exclude-standard -z", cwd);
268
+ const deleted = await sh("git ls-files -d -z", cwd);
269
+ if (!ls.ok || !changed.ok || !deleted.ok) return null;
270
+ const map = new Map<string, string>();
271
+ for (const rec of ls.out.split("\0")) {
272
+ const tab = rec.indexOf("\t");
273
+ if (tab > 0) map.set(rec.slice(tab + 1), rec.slice(0, tab).split(" ")[1] ?? "");
274
+ }
275
+ const gone = new Set(deleted.out.split("\0").filter(Boolean));
276
+ for (const p of gone) map.delete(p);
277
+ const live = [...new Set(changed.out.split("\0").filter((p) => p && !gone.has(p)))].filter((p) => !p.includes("\n"));
278
+ for (let i = 0; i < live.length; i += 200) {
279
+ const batch = live.slice(i, i + 200);
280
+ const h = await sh(`printf '%s\\n' ${batch.map(sq).join(" ")} | git hash-object --stdin-paths`, cwd);
281
+ if (!h.ok) return null;
282
+ const ids = h.out.trim().split("\n");
283
+ if (ids.length !== batch.length) return null;
284
+ batch.forEach((p, j) => map.set(p, ids[j]));
285
+ }
286
+ const listing = [...map.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([p, id]) => `${id} ${p}`).join("\n");
287
+ return checkFingerprint(listing, "content");
267
288
  }
268
289
 
269
290
  /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
@@ -73,6 +73,9 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
73
73
  case "health":
74
74
  return gateHealth(o);
75
75
 
76
+ case "review":
77
+ return gateReview(o);
78
+
76
79
  case "release":
77
80
  return gateRelease(o);
78
81
 
@@ -89,7 +92,8 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
89
92
  return gateAbort(o);
90
93
 
91
94
  default:
92
- return { text: `unknown subcommand "${sub}" — ${GATE_HELP}`, isError: true };
95
+ // gh#238: the unknown word first and alone — the full usage buried it
96
+ return { text: `unknown subcommand "${sub.length > 120 ? `${sub.slice(0, 120)}…` : sub}" — known: ${GATE_HELP.split(" — ")[0].split(" | ").map((g) => g.split(" ")[0]).join(", ")}; flow help prints the usage`, isError: true };
93
97
  }
94
98
  }
95
99
  /** Records the checkpoint word a gate asked for and has not been given: the footer shows 💬 (“operator,
@@ -706,6 +710,38 @@ export async function gateHealth(o: GateCtx): Promise<RunResult> {
706
710
  return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${probe}${triedNote(res.attempts)})\n${tail(res.out)}` };
707
711
  }
708
712
 
713
+ /** gh#233: records the pre-release review flow release requires. `done "<verdict>"` — the agent ran the playbook's
714
+ * review step inline; `--skip` — the operator's word to ship without one (asked first: Skip review?). A
715
+ * flow_stage review worker records itself. Bare: what is on record. Bound flow only — `done`'s verdict is free text. */
716
+ export async function gateReview(o: GateCtx): Promise<RunResult> {
717
+ const { root, ui, sess, cfg, rest, flag } = o;
718
+ const { state, err } = needState(root, sess);
719
+ if (err) return err;
720
+ const st = state!;
721
+ const words = rest.filter((a) => !a.startsWith("--"));
722
+ const onRecord = st.review
723
+ ? `review on record: ${st.review.by === "skipped" ? "skipped on the operator's word" : `${st.review.by}${st.review.head ? ` over ${st.review.head.slice(0, 7)}` : ""}${st.review.verdict ? ` — ${st.review.verdict}` : ""}`} (${ago(st.review.at)})`
724
+ : "no review on record";
725
+ if (!words.length && !flag("skip")) return { text: `${onRecord}${cfg.release.review ? ` — flow release requires one (${cfg.release.review})` : " — the playbook sets no review step"}` };
726
+ if (st.stage !== "implement" && st.stage !== "pre-release") return { text: `review is recorded at implement or pre-release — ${st.slug} is at ${st.stage}`, isError: true };
727
+ const head = st.worktree ? (await sh("git rev-parse HEAD", gateCwd(root, st))).out.trim() : "";
728
+ if (flag("skip")) {
729
+ if (!flag("confirmed")) {
730
+ const ok = ui.hasUI && (await ui.confirm("Skip review?", `Release ${st.slug} without the review step (${cfg.release.review || "none set"})?`));
731
+ if (!ok) return { text: needsOperator(`shipping without a review is the operator's word — the playbook's review step is ${cfg.release.review || "unset"}`, "Skip review?", "ask the operator in chat, then re-run flow review --skip --confirmed once they answer"), isError: true };
732
+ }
733
+ st.review = { by: "skipped", at: now(), ...(head ? { head } : {}) };
734
+ writeState(root, st);
735
+ return { text: `review skipped on the operator's word — flow release will not ask for one` };
736
+ }
737
+ if (words[0] !== "done") return { text: `usage: flow review [done "<verdict>"] | --skip [--confirmed]`, isError: true };
738
+ const verdict = words.slice(1).join(" ").trim();
739
+ if (!verdict) return { text: `flow review done needs the verdict in a line — e.g. flow review done "PASS — 2 should-fix items fixed in abc1234"`, isError: true };
740
+ st.review = { by: "inline", at: now(), ...(head ? { head } : {}), verdict: verdict.slice(0, 300) };
741
+ writeState(root, st);
742
+ return { text: `review recorded${head ? ` over ${head.slice(0, 7)}` : ""} — ${st.review.verdict}` };
743
+ }
744
+
709
745
  export async function gateUse(o: GateCtx): Promise<RunResult> {
710
746
  const { root, sess, slugArg } = o;
711
747
  if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
@@ -6,7 +6,7 @@ import { existsSync, readFileSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { pickReleaseNotes, prepOnlyChange, sq } from "../core.ts";
8
8
  import type { Config, FlowState } from "../core.ts";
9
- import { gateCwd, mergeBase, releaseTags, sh, tail, writeState } from "./base.ts";
9
+ import { featDir, gateCwd, mergeBase, releaseTags, sh, tail, writeState } from "./base.ts";
10
10
 
11
11
  /** How long the gate waits on a PR's CI; a seam so tests run in milliseconds (same shape as artifactWait). */
12
12
  export const publishWait = {
@@ -96,6 +96,25 @@ export async function gatePublishes(cfg: Config, forgeName: string, root: string
96
96
  return (await sh("gh --version", root, 15_000)).ok;
97
97
  }
98
98
 
99
+ /** gh#240: the repo's own pull-request template, when it has one (GitHub's single-file locations). */
100
+ export function prTemplate(cwd: string): string | null {
101
+ for (const rel of [".github/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE.md", "pull_request_template.md", "PULL_REQUEST_TEMPLATE.md", "docs/pull_request_template.md", "docs/PULL_REQUEST_TEMPLATE.md"])
102
+ if (existsSync(path.join(cwd, rel))) return rel;
103
+ return null;
104
+ }
105
+
106
+ /** The PR body the agent authored for the gate to open the PR with (gh#240). */
107
+ export const prBodyFile = (root: string, slug: string) => path.join(featDir(root, slug), "pr-body.md");
108
+
109
+ /** gh#240: a repo with a PR template keeps its gate list there — what changed, who verified it, over which
110
+ * commit. Synthesizing the body from the changelog dropped all of it, and the merged PR had to be patched
111
+ * afterwards. With a template and no authored body the gate refuses before the PR exists; null when fine. */
112
+ export function prBodyOwed(root: string, state: FlowState): string | null {
113
+ const tpl = prTemplate(gateCwd(root, state));
114
+ if (!tpl || existsSync(prBodyFile(root, state.slug))) return null;
115
+ return `this repo has a pull-request template (${tpl}) and no PR body is written — flow release opens the PR itself, and a body synthesized from the changelog drops the template's sections. Write .dev-flow/${state.slug}/pr-body.md from ${tpl} (every section filled; the changelog entry, and the commit the operator's Verified? was given over), then re-run`;
116
+ }
117
+
99
118
  async function prsFor(branch: string, cwd: string): Promise<Pr[] | null> {
100
119
  const r = await sh(`gh pr list --head ${sq(branch)} --state all --limit 20 --json number,state,url,headRefOid,mergeCommit`, cwd, 60_000);
101
120
  return r.ok ? jsonArray<Pr>(r.out) ?? (r.out.trim() ? null : []) : null;
@@ -113,8 +132,11 @@ async function prTitle(cwd: string, cfg: Config, slug: string): Promise<string>
113
132
  return rows[0]?.[1] ?? slug;
114
133
  }
115
134
 
116
- /** Body for the PR: the changelog entry of the version being released, else the branch's commit subjects. */
117
- async function prBody(cwd: string, cfg: Config, state: FlowState): Promise<string> {
135
+ /** Body for the PR: the authored .dev-flow/<slug>/pr-body.md (gh#240), else the changelog entry of the version
136
+ * being released, else the branch's commit subjects. */
137
+ async function prBody(root: string, cwd: string, cfg: Config, state: FlowState): Promise<string> {
138
+ const authored = prBodyFile(root, state.slug);
139
+ if (existsSync(authored)) return readFileSync(authored, "utf8").trim();
118
140
  const file = cfg.release.changelog ? path.join(cwd, cfg.release.changelog) : "";
119
141
  const entry = pickReleaseNotes({ changelog: file && existsSync(file) ? readFileSync(file, "utf8") : null, version: state.releaseVersion ?? null, annotation: "" }).notes;
120
142
  if (entry) return entry;
@@ -157,13 +179,16 @@ export async function publishRelease(root: string, state: FlowState, cfg: Config
157
179
  let pr = found.open;
158
180
  if (pr) steps.push(`PR #${pr.number} already open`);
159
181
  else {
160
- const body = await prBody(wt, cfg, state);
182
+ const owed = prBodyOwed(root, state);
183
+ if (owed) return stop(owed, `write .dev-flow/${state.slug}/pr-body.md`);
184
+ const authored = existsSync(prBodyFile(root, state.slug));
185
+ const body = await prBody(root, wt, cfg, state);
161
186
  const create = await sh(`gh pr create --head ${sq(br)} --base ${sq(cfg.defaultBranch)} --title ${sq(await prTitle(wt, cfg, state.slug))} --body ${sq(body || state.slug)}`, wt);
162
187
  if (!create.ok) return stop(`opening the PR failed:\n${tail(create.out, 8)}`, "open the PR yourself");
163
188
  found = await find();
164
189
  pr = found?.open;
165
190
  if (!pr) return stop("the PR was created but gh pr list does not show it yet", "wait a moment");
166
- steps.push(`PR #${pr.number} opened`);
191
+ steps.push(`PR #${pr.number} opened (body: ${authored ? "your pr-body.md" : "the changelog entry"})`);
167
192
  }
168
193
  state.publish = { ...state.publish, pr: pr.number };
169
194
  writeState(root, state);
@@ -1,13 +1,13 @@
1
1
  /** dev-flow runtime — The gates that ship: verify, release, release-done, finish. Moved out of extensions/dev-flow.ts as is (exports added). */
2
2
  import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { applicableItems, changelogVersionsBetween, normalizeReleaseBody, pendingEntryLines, pickReleaseNotes, checklistHash, checklistPending, cmpVersions, freshenChecks, healthProbe, mergeShapeProof, preReleaseGate, reflectionNudges, conflictMarkerLines, isReleaseOnly, looksLikeShellError, needsOperator, newestTaggedVersion, nextHint, releaseGate, parseVersion, roadmapDoneForSlug, sq, tagNotesCommand, verifyGate, versionTagGate, servedBuildMatches, prepFiles, versionArg, playbookVersionChoice, describeVersionChoice, majorBump, bumpVersion, isBumpKind, resolvedDevEnv } from "../core.ts";
4
+ import { applicableItems, changelogVersionsBetween, normalizeReleaseBody, pendingEntryLines, pickReleaseNotes, checklistHash, checklistPending, cmpVersions, freshenChecks, healthProbe, mergeShapeProof, preReleaseGate, reflectionNudges, conflictMarkerLines, isReleaseOnly, looksLikeShellError, needsOperator, newestTaggedVersion, nextHint, releaseGate, parseVersion, roadmapDoneForSlug, sq, tagNotesCommand, verifyGate, versionTagGate, servedBuildMatches, prepFiles, versionArg, playbookVersionChoice, describeVersionChoice, majorBump, bumpVersion, isBumpKind, resolvedDevEnv, reviewOwed, localDefaultAhead, failTail } from "../core.ts";
5
5
  import type { Config, FlowState } from "../core.ts";
6
6
  import { AGENT_MARK } from "../present.ts";
7
7
  import { buildSkew, copyWarning, currentBranch, featDir, flagValue, forgeMergeStyle, forgeOf, gateCwd, mergeBase, needState, now, originUrl, readReflectionsText, readRoadmap, readState, releaseTags, roadmapFile, sh, tail, worktreeAbs, writeState } from "./base.ts";
8
8
  import { type RunResult, ago, releaseDevSlot, keepThroughPrep, branchState, catchUp, describeBranchState, devEnv, devPortOf, devSlotCheck, healthRerunsAfterDeploy, pendingChecks, probeHealth, readDevPorts, runChecks, slotKey, triedNote, unreleasedOnMain, worktreeFingerprint, writeDevPorts } from "./checks.ts";
9
9
  import { type GateCtx, markPendingAsk } from "./gates.ts";
10
- import { gatePublishes, publishRelease } from "./publish.ts";
10
+ import { gatePublishes, prBodyOwed, publishRelease } from "./publish.ts";
11
11
 
12
12
  /** gh#198: the version question asked with Verified? — null when it is not the operator's to answer here
13
13
  * (no manifest to version, the playbook decides, or an earlier Verified? already recorded the call). */
@@ -88,7 +88,7 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
88
88
  const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
89
89
  state!.checks.build = { ok: res.ok, at: now() };
90
90
  writeState(root, state!);
91
- if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
91
+ if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${failTail(res.out)}`, isError: true };
92
92
  did.push(`build ran (${cfg.commands.build})`);
93
93
  }
94
94
  // deploy to dev before asking — the operator reviews the running dev app, not a promise
@@ -156,7 +156,8 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
156
156
  // operator, and the answer comes back in chat as flow verify --confirmed
157
157
  if (!ui.hasUI) {
158
158
  const port = devPortOf(state!, cfg);
159
- const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : "live app re-probed for review";
159
+ // gh#229: say what actually ran — with no dev deploy and no health probe nothing was deployed or probed
160
+ const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : healthProbe(cfg) ? "live app re-probed for review" : "ready for review — no dev deploy or health probe is configured, so nothing was deployed or probed: the operator checks the change as it runs for them";
160
161
  const vq = versionQuestion(root, state!, cfg);
161
162
  return { text: `${needsOperator(`${what}${reverify ? ` — a re-verify over the review fixes since ${state!.verifiedHead?.slice(0, 7) ?? "the last Verified?"}` : ""} — the app stays up until you answer${vq ? ` — ${vq.ask}` : ""}`, "Verified?", `look at the change in the running app yourself first (the playbook's self-check), then ask the operator Verified? in chat and run flow verify --confirmed${vq ? ` ${vq.flags}` : ""} once they answer. Keep it running until they answer.`)}\n${ran}` };
162
163
  }
@@ -244,6 +245,12 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
244
245
  const n = dirtyWt.out.split("\n").filter((l) => l.trim()).length;
245
246
  return { text: `release gate FAILED:\n- ${n} uncommitted path(s) in ${state!.worktree} — a merge ships the branch, not your working tree: commit or discard them, then re-run\n${tail(dirtyWt.out)}`, isError: true };
246
247
  }
248
+ // gh#233: the review step ran (or the operator waived it) before anything slow or anything ships
249
+ const noReview = reviewOwed(state!, cfg);
250
+ if (noReview) return { text: `release gate FAILED:\n- ${noReview}`, isError: true };
251
+ // gh#240: the PR body the template asks for exists before Release? is asked — the gate opens and merges the PR
252
+ const noBody = prBodyOwed(root, state!);
253
+ if (noBody && (await gatePublishes(cfg, forgeOf(cfg, await originUrl(root)), root))) return { text: `release gate FAILED:\n- ${noBody}`, isError: true };
247
254
  const branchProof = await branchState(wtCwd, cfg.defaultBranch);
248
255
  const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
249
256
  ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
@@ -292,7 +299,11 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
292
299
  // — except across a commit that is nothing but release prep: those greens are carried onto the current tree
293
300
  const fpRelease = await worktreeFingerprint(wtCwd);
294
301
  const keptThroughPrep = await keepThroughPrep(root, state!, cfg, fpRelease);
295
- if (freshenChecks(state!, fpRelease).length || keptThroughPrep.length) writeState(root, state!);
302
+ // gh#231: remember why each owed check is owed — the result names it instead of reading like skipped work
303
+ const failedBefore = new Set(Object.entries(state!.checks).filter(([, r]) => !r.ok).map(([n]) => n));
304
+ const staleNow = new Set(freshenChecks(state!, fpRelease));
305
+ if (staleNow.size || keptThroughPrep.length) writeState(root, state!);
306
+ const owedWhy = (n: string) => (staleNow.has(n) ? "the tree changed since it passed" : failedBefore.has(n) ? "its last run failed" : "no run on record");
296
307
  // gh#198: the branch must carry the call the operator made — a bump they did not choose, or a bump on a flow
297
308
  // they said merges unreleased, is prep that contradicts the word Release? would stand on. It runs before the
298
309
  // generic proofs: when a parallel flow released first, "already tagged" alone would send the agent round a loop.
@@ -333,8 +344,9 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
333
344
  let checksNote = carried.length ? ` Checks kept (${carried.join(", ")}): only release prep was committed since they passed.` : "";
334
345
  if (owed.length) {
335
346
  const ran = await runChecks(root, state!, cfg, owed);
336
- if (ran.failed) return { text: `release gate FAILED — a check run at the gate failed:\n${ran.lines.join("\n")}`, isError: true };
337
- checksNote += ` Checks ran at the gate (${owed.map((c) => c.name).join(", ")}).`;
347
+ const why = owed.map((c) => `${c.name}: ${owedWhy(c.name)}`).join("; ");
348
+ if (ran.failed) return { text: `release gate FAILED — a check run at the gate failed (run because ${why}):\n${ran.lines.join("\n")}`, isError: true };
349
+ checksNote += ` Checks ran at the gate (${why}).`;
338
350
  }
339
351
  const preGate = preReleaseGate(gateState(state!.checks), cfg, prep);
340
352
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
@@ -597,7 +609,7 @@ export async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
597
609
  // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
598
610
  // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
599
611
  const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
600
- const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeName, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
612
+ const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeName, br) : null, forgeAsked: forgeName === "github" || forgeName === "gitlab", branch: br, defaultBranch: cfg.defaultBranch });
601
613
  if (proof.errors.length) errs.push(...proof.errors);
602
614
  else mergeNote = proof.note;
603
615
  }
@@ -731,24 +743,37 @@ export async function gateFinishCore(o: GateCtx): Promise<RunResult> {
731
743
  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 };
732
744
  const origin = await originUrl(root);
733
745
  const hasOriginF = origin !== null;
734
- if (hasOriginF) {
735
- const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
736
- if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
746
+ // gh#234/gh#228: judge the local default branch, not whatever HEAD the main checkout happens to be on, and
747
+ // name what is local-only — playbook tracking is a note, anything else must reach origin first
748
+ const checkoutBranch = await currentBranch(root);
749
+ const localDef = `refs/heads/${cfg.defaultBranch}`;
750
+ let aheadNote = "";
751
+ if (hasOriginF && (await sh(`git rev-parse --verify -q ${sq(localDef)}`, root)).ok) {
752
+ const log = await sh(`git log --no-decorate --name-only --format=%x1e%h%x20%s ${sq(`origin/${cfg.defaultBranch}`)}..${sq(localDef)}`, root);
753
+ if (log.ok) {
754
+ const commits = log.out.split("\x1e").map((r) => r.split("\n").map((l) => l.trim()).filter(Boolean)).filter((r) => r.length).map(([line, ...files]) => ({ line, files }));
755
+ const ahead = localDefaultAhead({ defaultBranch: cfg.defaultBranch, checkoutBranch, commits });
756
+ if (ahead?.block) return { text: ahead.block, isError: true };
757
+ aheadNote = ahead?.note ?? "";
758
+ }
737
759
  }
738
760
  // close-out also syncs the main checkout: a released flow must never leave local
739
761
  // <default> trailing origin — the push check above proved nothing local-only remains, so a
740
762
  // differing sha means local trails and the fast-forward is safe. never a merge: a diverged
741
763
  // or not-checked-out main prints the operator's exact command instead of touching anything
742
- let syncNote = "";
743
- if (hasOriginF) {
744
- const headSha = await sh("git rev-parse HEAD", root);
764
+ let syncNote = aheadNote;
765
+ if (hasOriginF && !aheadNote) {
766
+ const localSha = await sh(`git rev-parse --verify -q ${sq(localDef)}`, root);
745
767
  const originSha = await sh(`git rev-parse ${sq(`origin/${cfg.defaultBranch}`)}`, root);
746
- if (headSha.ok && originSha.ok && headSha.out.trim() !== originSha.out.trim()) {
747
- const onDefault = (await currentBranch(root)) === cfg.defaultBranch;
748
- const ff = onDefault ? await sh(`git merge --ff-only ${sq(`origin/${cfg.defaultBranch}`)}`, root) : { ok: false, out: "" };
768
+ if (localSha.ok && originSha.ok && localSha.out.trim() !== originSha.out.trim()) {
769
+ const onDefault = checkoutBranch === cfg.defaultBranch;
770
+ // off the default branch, the local ref moves without touching the checkout: fetch into it fast-forward-only
771
+ const ff = onDefault
772
+ ? await sh(`git merge --ff-only ${sq(`origin/${cfg.defaultBranch}`)}`, root)
773
+ : await sh(`git fetch -q . ${sq(`refs/remotes/origin/${cfg.defaultBranch}:${localDef}`)}`, root);
749
774
  syncNote = ff.ok
750
- ? ` local ${cfg.defaultBranch} fast-forwarded to origin/${cfg.defaultBranch}.`
751
- : ` local ${cfg.defaultBranch} trails origin/${cfg.defaultBranch} and did not fast-forward cleanly — sync by hand: git -C ${sq(root)} pull --ff-only`;
775
+ ? ` local ${cfg.defaultBranch} fast-forwarded to origin/${cfg.defaultBranch}${onDefault ? "" : ` (the main checkout stays on ${checkoutBranch})`}.`
776
+ : ` local ${cfg.defaultBranch} trails origin/${cfg.defaultBranch} and did not fast-forward cleanly — sync by hand: git -C ${sq(root)} ${onDefault ? "pull --ff-only" : `fetch . origin/${cfg.defaultBranch}:${cfg.defaultBranch}`}`;
752
777
  }
753
778
  }
754
779
  // After-merge checks (flow-check blocks under ## release): run from the main checkout, which now holds the