pi-dev-flow 0.91.0 โ†’ 0.92.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.
@@ -2,46 +2,59 @@
2
2
 
3
3
  ## Stage: release
4
4
 
5
- Main-repo git (merge, tag, push on the default branch) is allowed only here.
6
5
  Nothing in this stage asks the operator anything โ€” Release? covered it (answered
7
- by the operator, or by the gate itself under `ask = on-change`). Report
8
- each step with the gate's stage line, **๐Ÿš€ release ยท `<slug>`**; no `Done:` /
9
- `Next steps:` block.
10
-
11
- 1. **PR and merge.** Commit everything, push the feature branch, open the PR.
12
- - **Merge only once CI is green**: `gh pr checks <n> --watch` (or your
13
- forge's equivalent) first โ€” CI runs jobs the host may not.
14
- - **Waiting on CI is your job, inside the turn.** Nothing wakes you once
15
- the turn ends, so never end it with "I'll keep watching" or a
16
- *wait / hold* choice: keep re-running the watch until CI settles.
17
- - **Runs stuck in `queued`** (no job started after ~15 min, while other
18
- runs on the repo do start) are a stuck schedule, not a slow runner:
19
- re-trigger them โ€” `gh run cancel <id>` then `gh run rerun <id>`, or
20
- push a merge of the default branch when it moved โ€” and keep watching.
21
- - Only a red CI you can't fix, or CI still stuck after a re-trigger, ends
22
- the turn: report it plainly ("stopped: โ€ฆ โ€” say *go* to resume") and
23
- stop.
24
- - Merge in the **playbook's style**, PR number before the flag:
25
- `gh pr merge <n> --squash` under `merge = squash`, `--merge` under
26
- `merge = merge`. (`gh pr merge --merge main` reads `main` as the PR.)
27
- - No `--delete-branch` โ€” finish deletes the branch on merge proof.
6
+ by the operator, or by the gate itself under `ask = on-change`). Report with the
7
+ gate's stage line, **๐Ÿš€ release ยท `<slug>`**; no `Done:` / `Next steps:` block.
8
+
9
+ ### The gate publishes (GitHub)
10
+
11
+ `flow release` does the whole stage in the same call that passed Release?: it
12
+ pushes the branch, opens the PR (changelog entry as body), waits for the PR's
13
+ CI, merges in the playbook's style, cuts and pushes the annotated tag on the
14
+ merge commit, then records the release (tag on origin, artifact, forge release
15
+ created from the changelog entry and read back). You run no git or `gh` step.
16
+
17
+ It stops with one of two results, and **re-running `flow release` resumes** โ€”
18
+ it skips whatever the forge already shows as done:
19
+
20
+ - **`publish waiting โ€” โ€ฆ`**: CI was still running after 30 minutes. Re-run
21
+ `flow release` now, in this turn. Nothing wakes you once the turn ends, so
22
+ never end it with "I'll keep watching".
23
+ - **`publish stopped โ€” โ€ฆ`**: something needs fixing, and the result names it.
24
+ - A red check: fix it on the branch and commit (the re-run pushes it), or
25
+ re-run a flaky job, then `flow release`.
26
+ - Runs stuck in `queued` (~15 min, while other runs on the repo start):
27
+ `gh run cancel <id>` then `gh run rerun <id>`, then `flow release`.
28
+ - The forge refused the merge (required review, merge queue): tell the
29
+ operator what it needs and stop. Once the PR is merged, `flow release`
30
+ carries on from there.
31
+ - A red CI you can't fix ends the turn: report it plainly ("stopped: โ€ฆ โ€” say
32
+ *go* to resume").
33
+
34
+ Then [finish.md](finish.md): `flow finish`.
35
+
36
+ ### By hand (`publish = manual`, GitLab, self-hosted, no `gh`)
37
+
38
+ The gate result says `next: publish: push the branch, open the PRโ€ฆ`. Main-repo
39
+ git (merge, tag, push on the default branch) is allowed only in this stage.
40
+
41
+ 1. **PR and merge.** Push the feature branch, open the PR. Merge only once CI
42
+ is green (`gh pr checks <n> --watch`), and wait for it inside the turn. Merge in the **playbook's
43
+ style**, PR number before the flag (`gh pr merge <n> --squash`). No
44
+ `--delete-branch` โ€” finish deletes the branch on merge proof.
28
45
  2. **Tag** (versioned flows). `git fetch`, confirm the merge landed, create an
29
46
  **annotated** tag (`git tag -a v<ver> -m โ€ฆ`) and push it explicitly:
30
- `git push origin v<ver>`. Never `--follow-tags`.
31
- - CI builds from the tag? `release.preflight` proves that build at
32
- `flow release`; `release.artifact` makes the record step verify the
33
- published artifact. On GitHub it waits for the publish CI the tag
34
- started (up to 15 min) โ€” no hand-run `gh run watch` before it.
35
- - `--no-version` flow: no bump, no tag โ€” publish the merge only.
36
- 3. **Hand over to finish.** Once merged and tagged, the playbook continues in
37
- [finish.md](finish.md): `flow finish` records the release itself first
38
- (the same proofs `flow release-done` runs โ€” tag on the default branch and
39
- on origin, artifact, forge release created from the changelog entry and
40
- read back) and then closes the feature out.
41
- - Skipping the forge release (`--no-release-create`, or `release.releases
42
- = false`) or the artifact check (`--no-artifact-check`) is the
43
- operator's call only.
44
- - Session on an older build than the checkout: the release gate prints
45
- both builds and what shipped between them and asks **update (`/reload`
46
- and re-run) or proceed?** โ€” a recorded choice, not a block.
47
- - Release-stage checklist items close with the Finish? answer.
47
+ `git push origin v<ver>`. Never `--follow-tags`. A `--no-version` flow has
48
+ no tag.
49
+ 3. **`flow finish`** records the release itself first, then closes out.
50
+
51
+ ### Either way
52
+
53
+ - Skipping the forge release (`--no-release-create`, or `release.releases =
54
+ false`) or the artifact check (`--no-artifact-check`) is the operator's call
55
+ only.
56
+ - `release.artifact` set and CI publishes from the tag: the record step waits
57
+ for that CI (up to 15 min) โ€” no hand-run `gh run watch`.
58
+ - After-merge work: `flow-check` blocks under `## release` are run by
59
+ `flow finish` from the main checkout; `- [ ]` items there close with the
60
+ Finish? answer.
@@ -35,14 +35,16 @@ knobs ยท merge-policy state.
35
35
  adds the mockup gate, so don't ask. Turning it **off** is the operator's:
36
36
  `flow start <slug> --no-ui --confirmed` at plan, after they say so, and
37
37
  aborting a ui feature at plan asks the same.
38
- - **Ask every grant in one message**, then make one call with all of them:
39
- the mode (`normal` default, or `--patch` / `--docs`) and the merge policy if
40
- the playbook has none โ€”
41
- `flow start <slug> [--ui] [--patch|--docs] [--merge=<style>] --confirmed`.
42
- Never grant any of them yourself. When the operator's own request already
43
- grants one ("start a docs flow"), that is their word: pass `--confirmed` on
44
- the first call. After a refusal, only a message sent later counts, so a
45
- `--confirmed` re-run right away is refused too. Ask once.
38
+ - **A mode is a proposal, not a grant**: pass `--patch` or `--docs` on the
39
+ start call when the work fits (no `--confirmed`, no question). The
40
+ operator grants it with their **Approve?** answer โ€” say the mode and why
41
+ when you ask it. They say no โ†’ `flow abort`, start again as a normal
42
+ feature.
43
+ - **The merge policy is the one grant start asks for**, and only when the
44
+ playbook has none: `flow start <slug> [--ui] [--patch|--docs]
45
+ --merge=<style> --confirmed` on their answer. After a refusal, only a
46
+ message sent later counts, so a `--confirmed` re-run right away is refused
47
+ too. Ask once.
46
48
  - No merge policy โ†’ the gate refuses with `NEEDS-OPERATOR Merge policy?` and a
47
49
  suggestion read off the repo's history. Ask: squash, merge, rebase or any.
48
50
  The answer is written into `## release` once.
@@ -56,6 +58,7 @@ knobs ยท merge-policy state.
56
58
  - `normal` โ€” a written plan (`plan/plan.md`) is required before Approve?.
57
59
  - `--patch` โ€” a small change to release now (one-file fix, version chore):
58
60
  no plan file, one chat line is the plan, every other gate identical.
61
+ Approve? reads "approve this as a patch: <one line>".
59
62
  - `--docs` โ€” docs only: no plan file and no tier-1 checks; worktree and the
60
63
  full release stay.
61
64
  - A change that grows past one line or touches behavior is a normal feature.
package/src/core.ts CHANGED
@@ -20,6 +20,11 @@ export interface Check {
20
20
  * longer exists โ€” green is not enough when the tree moved under it. Absent = recorded by an
21
21
  * older build, or git could not be asked: never proven stale, never dropped. */
22
22
  wt?: string;
23
+ /** HEAD when the check passed, recorded only when the tree was clean then: lets the release gate tell
24
+ * "nothing but release prep was committed since" from a real change (see prepOnlyChange). */
25
+ head?: string;
26
+ /** Carried over a release-prep-only commit instead of being re-run (keepThroughPrep) โ€” the release gate says so. */
27
+ prep?: boolean;
23
28
  }
24
29
 
25
30
  export interface StageCheck {
@@ -43,6 +48,7 @@ export interface FlowState {
43
48
  noVersion?: boolean; // operator chose: this flow ships merge + changelog only โ€” no bump, no tag, no forge release; the entry rides under Unreleased until the next versioned release folds it
44
49
  yolo?: boolean; // operator said "yolo" at any gate question: that one answered, every later one pre-confirmed; checks and guardrails stay
45
50
  setupAt?: string; // commands.setup exited 0 in this worktree โ€” a reused worktree reruns it only when unset (#49)
51
+ publish?: { pr?: number; merged?: string; tag?: string }; // set when the release gate publishes itself (GitHub): what it has done so far โ€” every step re-probes the forge, this only feeds the hint and the result
46
52
  releaseVersion?: string; // the manifest version the release gate approved โ€” release-done publishes this, not whatever a checkout says later (#52)
47
53
  forgeReleaseSkipped?: string; // a gh/glab release create that failed: release-done says so, finish names it so the missing forge release cannot slip past (#63)
48
54
  staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
@@ -53,7 +59,9 @@ export interface FlowState {
53
59
  verifiedHead?: string; // HEAD the operator's Verified? was given over โ€” release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
54
60
  reflectedAt?: string; // a reflect worker reported for this flow โ€” finish runs one first while this is unset (only --no-reflect --confirmed skips it)
55
61
  devPort?: number; // the port the operator chose for this flow's dev deploy when the default was held by another flow โ€” finish stops it (devDown)
56
- friction?: number; // gate refusals, guard blocks and post-Verified? code changes this feature hit โ€” finish skips the closing reflection at 0 (playbook reflect = on-friction)
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
+ 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
+ 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
57
65
  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
58
66
  }
59
67
 
@@ -111,6 +119,9 @@ export interface Config {
111
119
  forge: string;
112
120
  commands: Commands;
113
121
  checkList: StageCheck[]; // tier-1 executable checks (project.md flow blocks)
122
+ /** `flow-check` blocks under ## release: after-merge checks `flow finish` runs from the main checkout once the
123
+ * release is recorded, before anything is removed (a post-merge build, a deploy check). */
124
+ releaseChecks: StageCheck[];
114
125
  checklist: Record<string, ChecklistItem[]>; // tier-2 operator items per stage
115
126
  prose: Record<string, string>; // tier-3 guidance per stage
116
127
  versioning: Versioning;
@@ -123,7 +134,7 @@ export interface Config {
123
134
  /** Bytes one dev instance needs (playbook `instanceMem` / `instanceDisk`, e.g. 2G) โ€” the side-by-side feasibility check. */
124
135
  instanceMem?: number;
125
136
  instanceDisk?: number;
126
- release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any"; /** `until-release`: a standing yolo never answers Release? (gh#176) */ yolo?: "all" | "until-release"; /** `always`: finish runs the closing reflection even on a flow with no friction */ reflect?: "always" | "on-friction"; /** who decides versioned vs unreleased: asked with Verified? (`ask`, default) or fixed by the playbook (gh#198) */ version?: "ask" | "versioned" | "unversioned"; /** `on-change` (default): Release? answers itself when nothing but release prep changed since Verified? and the version choice is on record; `always` asks it every time (gh#198) */ ask?: "always" | "on-change" };
137
+ release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any"; /** `until-release`: a standing yolo never answers Release? (gh#176) */ yolo?: "all" | "until-release"; /** `always`: finish runs the closing reflection even on a flow with no friction */ reflect?: "always" | "on-friction"; /** who decides versioned vs unreleased: asked with Verified? (`ask`, default) or fixed by the playbook (gh#198) */ version?: "ask" | "versioned" | "unversioned"; /** `on-change` (default): Release? answers itself when nothing but release prep changed since Verified? and the version choice is on record; `always` asks it every time (gh#198) */ ask?: "always" | "on-change"; /** `prep-skip` (default): green checks survive a commit that touches only release-prep files; `always` re-runs them */ recheck?: "always" | "prep-skip"; /** `on-change` (default): Finish? answers itself on a clean flow (quiet reflection, no open release items, nothing skipped); `always` asks it every time */ finish?: "always" | "on-change"; /** `gate` (default): on GitHub `flow release` pushes, opens the PR, waits for CI, merges and tags itself; `manual`: the agent runs those steps */ publish?: "gate" | "manual" };
127
138
  mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
128
139
  /** `inject` (default): the class default timeout is armed silently on every shell call.
129
140
  * `require`: a shell call without its own visible timeout is refused (costs a turn per miss). */
@@ -143,6 +154,7 @@ export const DEFAULTS: Config = {
143
154
  forge: "",
144
155
  commands: {},
145
156
  checkList: [],
157
+ releaseChecks: [],
146
158
  checklist: {},
147
159
  prose: {},
148
160
  versioning: { pattern: "v{version}" },
@@ -341,7 +353,7 @@ export function approveGate(state: FlowState, cfg: Config, planFiles: string[],
341
353
  // ![alt](mockups/screen-390.png) with an optional "title" tolerated; matching is case-insensitive
342
354
  const embeds = [...planDoc.matchAll(/!\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)].map((m) => m[1].toLowerCase());
343
355
  const unembedded = planFiles.filter((f) => IMG_EXT.test(f) && !embeds.some((e) => e === f.toLowerCase() || e.endsWith("/" + f.toLowerCase())));
344
- if (unembedded.length) errs.push(`plan.md must embed every render โ€” missing embed: ${unembedded.join(", ")} (write ![<screen> โ€” width](mockups/<file>) under the screen's section)`);
356
+ if (unembedded.length) errs.push(`plan.md must embed every render โ€” missing embed: ${unembedded.join(", ")} (write ![<screen> โ€” width](mockups/<file>) under the screen's section, or delete the file if that screen/variant was dropped)`);
345
357
  // the naming plan.md prescribes (screen.html โ†’ screen-<width>.png): a mockups/*.html with no
346
358
  // embedded shot of its own was never rendered
347
359
  const unrendered = planFiles
@@ -350,7 +362,7 @@ export function approveGate(state: FlowState, cfg: Config, planFiles: string[],
350
362
  const stem = f.toLowerCase().replace(/\.html$/, "").split("/").pop()!;
351
363
  return !embeds.some((e) => (e.split("/").pop() ?? "").startsWith(stem) && IMG_EXT.test(e));
352
364
  });
353
- if (unrendered.length) errs.push(`mockups without an embedded render โ€” ${unrendered.join(", ")} (render each screen and name the shot after it: <screen>-<width>.png)`);
365
+ if (unrendered.length) errs.push(`mockups without an embedded render โ€” ${unrendered.join(", ")} (render each screen and name the shot after it: <screen>-<width>.png, or delete the html if that screen was dropped)`);
354
366
  }
355
367
  if (foreignLinks.length)
356
368
  errs.push(`mockups link another feature's worktree โ€” ${foreignLinks.join(", ")}: that branch drifts and is removed at its finish; at plan link the main checkout's stylesheet (this feature's worktree does not exist until approve) and re-render`);
@@ -633,6 +645,18 @@ export function checklistHash(items: ChecklistItem[]): string {
633
645
  .slice(0, 12);
634
646
  }
635
647
 
648
+ /** The files a release-prep commit is made of: the version manifest, the changelog, and npm's lock beside a package.json. */
649
+ export function prepFiles(cfg: Config): Set<string> {
650
+ return new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
651
+ }
652
+
653
+ /** True when every changed path is a release-prep file (and something changed): the bump and the changelog
654
+ * entry land after the checks by design, and re-running the whole suite over them proves nothing new. */
655
+ export function prepOnlyChange(cfg: Config, changed: string[]): boolean {
656
+ const prep = prepFiles(cfg);
657
+ return changed.length > 0 && changed.every((f) => prep.has(f));
658
+ }
659
+
636
660
  /** Fingerprint of the worktree state a tier-1 check ran against: the caller composes the working
637
661
  * tree's `git status --porcelain`, the hash of its uncommitted `git diff HEAD` (path presence and
638
662
  * tracked content move it), and `git rev-parse HEAD`. Deterministic and cheap; the sha is only
@@ -646,7 +670,7 @@ export function checkFingerprint(treeState: string, head: string): string {
646
670
  /**
647
671
  * Drop every check record that carries a fingerprint differing from the tree as it is now โ€” those
648
672
  * greens describe code that no longer exists, and a gate must not advance on them. The caller
649
- * re-runs what is missing (verify re-runs at the gate; the release gate asks for `flow check`).
673
+ * re-runs what is missing (verify and release both re-run at the gate).
650
674
  * `fp === null` means git could not be asked: a gate must not refuse on its own measurement
651
675
  * failure โ€” same rule as BranchState.commitsAhead. Records without a fingerprint (older builds)
652
676
  * are never proven stale.
@@ -1230,7 +1254,7 @@ export function bashFlowGuard(o: GuardCtx): string | null {
1230
1254
  // Shipping belongs to the release stage: a tag cut (or pushed) while the feature is still before release
1231
1255
  // leaves the gates unable to record it โ€” flow release then refuses "already tagged" and the flow cannot close.
1232
1256
  if (o.stage && BEFORE_RELEASE.has(o.stage)) {
1233
- if (git("tag") && tagCreates(c)) return `tagging is release work โ€” the feature is at ${o.stage}; run flow release first (it gates the version, then tags)${judgedIn}`;
1257
+ if (git("tag") && tagCreates(c)) return `tagging is release work โ€” the feature is at ${o.stage}; run flow release first (it gates the version, then tags). This call creates a tag (a tag name, or -a/-s/-m/-f); reading tags (git tag -l, --sort, --contains) is allowed at any stage${judgedIn}`;
1234
1258
  if (git("push")) {
1235
1259
  const refs = o.pushRefs ?? parsePushRefs(gitInvocation(c).pushes);
1236
1260
  if (/\s--(?:tags|follow-tags)\b/.test(c) || /refs\/tags\//.test(c) || refs.some((r) => r.kind === "tag")) return `pushing tags is release work โ€” the feature is at ${o.stage}; run flow release first${judgedIn}`;
@@ -1247,8 +1271,12 @@ export function tagCreates(command: string): boolean {
1247
1271
  if (!m) return false;
1248
1272
  const tok = m[1].trim().split(/\s+/).filter(Boolean);
1249
1273
  if (!tok.length) return false;
1274
+ // gh#221: a write is named by what writes โ€” an annotate/sign/message/force flag, or a tag name. The
1275
+ // old test allow-listed read flags, so `git tag --sort=-creatordate` read as a tag cut and the agent
1276
+ // ran the query in a clone the guard could not see.
1250
1277
  if (tok.some((t) => /^(-l|--list|-n\d*|--contains|--no-contains|--points-at|--merged|--no-merged|-v|--verify|-d|--delete)$/.test(t))) return false;
1251
- return true;
1278
+ if (tok.some((t) => /^(-a|--annotate|-s|--sign|-u|--local-user(=.*)?|-m|--message(=.*)?|-F|--file(=.*)?|-f|--force)$/.test(t) || /^-[asf]*m./.test(t))) return true;
1279
+ return tok.some((t) => !t.startsWith("-"));
1252
1280
  }
1253
1281
 
1254
1282
  /** Forge-side shipping (`gh pr merge`, `glab mr merge`, `gh|glab release create`) before the release stage, or null.
@@ -1261,7 +1289,7 @@ export function releaseOrderInvocation(command: string, stage: Stage | null): st
1261
1289
  if (/\bgh\s+pr\s+merge\b/.test(hay) || /\bglab\s+mr\s+merge\b/.test(hay))
1262
1290
  return `merging the PR is release work โ€” the feature is at ${stage}; ask the operator Release? and run flow release first (yolo pre-answers the question, it does not skip the gate)`;
1263
1291
  if (/\b(?:gh|glab)\s+release\s+create\b/.test(hay))
1264
- return `publishing a forge release is release work โ€” the feature is at ${stage}; run flow release, then flow release-done creates it`;
1292
+ return `publishing a forge release is release work โ€” the feature is at ${stage}; run flow release โ€” the release record creates it`;
1265
1293
  }
1266
1294
  return null;
1267
1295
  }
@@ -1590,7 +1618,7 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
1590
1618
  if (owner.state.stage === "plan") return `feature ${owner.state.slug} is in plan โ€” code is read-only until its plan is approved`;
1591
1619
  // the playbook copy inside a worktree: only operator-granted lightweight modes may change it
1592
1620
  if (path.basename(abs) === "project.md" && abs.includes(path.join(".dev-flow", "project.md")) && !owner.state.docs && !owner.state.patch)
1593
- return `project.md changes belong to a docs or patch flow โ€” ${owner.state.slug} is a normal feature (flow start <slug> --docs --confirmed)`;
1621
+ return `project.md changes belong to a docs or patch flow โ€” ${owner.state.slug} is a normal feature (flow start <slug> --docs)`;
1594
1622
  return null; // implement/pre-release/release: own worktree is the working area
1595
1623
  }
1596
1624
  // Scratch outside the checkout is not a repo write: every stage (and an unbound session) may use it. It
@@ -1916,8 +1944,8 @@ export interface ReflectionRoute {
1916
1944
  route: string;
1917
1945
  }
1918
1946
 
1919
- const DOCS_ROUTE = "docs flow (flow start fold-<topic> --docs --confirmed) โ€” project.md edits only pass its worktree";
1920
- const CODE_ROUTE = "patch flow (flow start fix-<topic> --patch --confirmed), normal flow when bigger";
1947
+ const DOCS_ROUTE = "docs flow (flow start fold-<topic> --docs) โ€” project.md edits only pass its worktree";
1948
+ const CODE_ROUTE = "patch flow (flow start fix-<topic> --patch), normal flow when bigger";
1921
1949
 
1922
1950
  export function reflectionRoutes(items: ReflectItem[], selfRepo: boolean): ReflectionRoute[] {
1923
1951
  return items.map((it) => {
@@ -2088,7 +2116,7 @@ export function reflectionNudges(text: string, today: string, opts: { recurred?:
2088
2116
  if (code && opts.between) why.push("between flows");
2089
2117
  let fix: string | null = null;
2090
2118
  if (open.length && why.length) {
2091
- const split = [docs ? `${docs} playbook item(s) โ†’ one docs flow (flow start fold-<topic> --docs --confirmed)` : "", code ? `${code} code item(s) โ†’ patch flow (flow start fix-<topic> --patch --confirmed)` : ""].filter(Boolean).join("; ");
2119
+ const split = [docs ? `${docs} playbook item(s) โ†’ one docs flow (flow start fold-<topic> --docs)` : "", code ? `${code} code item(s) โ†’ patch flow (flow start fix-<topic> --patch)` : ""].filter(Boolean).join("; ");
2092
2120
  fix = `โš‘ fix the open reflections now? (${why.join(", ")}) โ€” ${split}`;
2093
2121
  }
2094
2122
  const closedLines = text.split("\n").filter(isDoneItem);
@@ -2269,7 +2297,7 @@ export function compactionStateBlock(state: FlowState, cfg: Config): string {
2269
2297
  export function nextHint(state: FlowState, cfg: Config): string {
2270
2298
  switch (state.stage) {
2271
2299
  case "plan":
2272
- if (state.patch || state.docs) return `${state.patch ? "patch" : "docs"}: describe the change in one line, ask Approve? in chat, then flow approve --confirmed โ€” no plan file${state.docs ? ", no tier-1 checks" : ""}`;
2300
+ if (state.patch || state.docs) return `${state.patch ? "patch" : "docs"} (proposed โ€” the Approve? answer grants the mode): describe the change in one line, ask Approve? in chat naming the mode, then flow approve --confirmed โ€” no plan file${state.docs ? ", no tier-1 checks" : ""}`;
2273
2301
  return `clarify the direction in chat, write .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask Approve? and run flow approve --confirmed on the answer`;
2274
2302
  case "implement":
2275
2303
  if (state.docs) {
@@ -2282,14 +2310,15 @@ export function nextHint(state: FlowState, cfg: Config): string {
2282
2310
  const vc = state.versionChoice;
2283
2311
  const auto = cfg.release.ask !== "always" ? " (release.ask = on-change: it asks Release? only when something beyond the prep changed)" : "";
2284
2312
  if (vc === "unreleased")
2285
- 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)` : ""}, flow check; show the PR summary, then run flow release${auto || " and ask Release?"}`;
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?"}`;
2286
2314
  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 ");
2287
- 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}, flow check; show the PR summary, version and changelog, then run flow release${auto || " and ask Release?"}`;
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?"}`;
2288
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`;
2289
- return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${prep ? `, ${prep}` : ""}, flow check; show the PR summary, version and changelog, ask Release? and run flow release`;
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`;
2290
2318
  }
2291
2319
  case "release":
2292
2320
  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?)`;
2321
+ if (state.publish) return `flow release publishes (push, PR, CI wait, merge${state.noVersion ? "" : ", tag"}) and records the release โ€” re-run it after a "publish stopped" or "publish waiting" result; then flow finish`;
2293
2322
  return `publish: push the branch, open the PR, merge once CI is green (gh pr checks <n> --watch)${mergeHintFor(cfg)}${state.noVersion ? " โ€” unversioned: no bump, no tag" : ", push the annotated tag"}; then flow finish records the release and closes out`;
2294
2323
  }
2295
2324
  }
package/src/projectmd.ts CHANGED
@@ -18,6 +18,8 @@ export interface ParsedMd {
18
18
  global: Record<string, string>;
19
19
  flow: Record<MdStage, Record<string, string>>;
20
20
  checks: StageCheck[];
21
+ /** flow-check blocks under ## release โ€” run by flow finish from the main checkout */
22
+ releaseChecks: StageCheck[];
21
23
  guard: GuardRules;
22
24
  checklist: Record<string, ChecklistItem[]>;
23
25
  prose: Record<string, string>;
@@ -68,6 +70,9 @@ const KEYMAP: Record<string, Record<string, string>> = {
68
70
  reflect: "release.reflect", // when finish runs the closing reflection: on-friction (default) | always
69
71
  version: "release.version", // who decides versioned vs unreleased: ask (with Verified?, default) | versioned | unversioned (gh#198)
70
72
  ask: "release.ask", // when Release? is asked: on-change (default) | always (gh#198)
73
+ finish: "release.finish", // when Finish? is asked: on-change (default, a clean flow closes itself) | always
74
+ publish: "release.publish", // who runs push, PR, merge and tag after Release?: gate (default on GitHub) | manual
75
+ recheck: "release.recheck", // checks after a release-prep-only commit: prep-skip (default, keep the green records) | always
71
76
  },
72
77
  };
73
78
  // pre-release owns release preparation; the release keys are accepted under both sections so
@@ -125,7 +130,7 @@ function parseGuardRules(entries: { line: string; where: string }[], stage: stri
125
130
  }
126
131
 
127
132
  export function parseProjectMd(text: string): ParsedMd {
128
- const p: ParsedMd = { hard: [], warn: [], global: {}, flow: Object.fromEntries(MD_STAGES.map((s) => [s, {}])) as Record<MdStage, Record<string, string>>, checks: [], guard: structuredClone(DEFAULTS.guard), checklist: {}, prose: {}, workerPreamble: [] };
133
+ const p: ParsedMd = { hard: [], warn: [], global: {}, flow: Object.fromEntries(MD_STAGES.map((s) => [s, {}])) as Record<MdStage, Record<string, string>>, checks: [], releaseChecks: [], guard: structuredClone(DEFAULTS.guard), checklist: {}, prose: {}, workerPreamble: [] };
129
134
  let stage: string | null = null;
130
135
  const prose: Record<string, string[]> = {};
131
136
  let inFence: string | null = null; // "flow" | "flow-check" | other lang
@@ -141,7 +146,8 @@ export function parseProjectMd(text: string): ParsedMd {
141
146
  const cmd = checkBody.join("\n").trim();
142
147
  if (!checkName) p.hard.push(`${where}: flow-check block missing a name`);
143
148
  else if (!cmd) p.hard.push(`${lastLine}: flow-check "${checkName}" is empty`);
144
- else if (stage !== "implement") p.warn.push(`${where}: flow-check "${checkName}" ignored (tier-1 checks belong to ## implement)`);
149
+ else if (stage === "release") p.releaseChecks.push({ name: checkName, cmd });
150
+ else if (stage !== "implement") p.warn.push(`${where}: flow-check "${checkName}" ignored (checks belong to ## implement, or to ## release for after-merge checks)`);
145
151
  else p.checks.push({ name: checkName, cmd });
146
152
  }
147
153
  if (inFence === "flow-guard") {
@@ -190,6 +196,18 @@ export function parseProjectMd(text: string): ParsedMd {
190
196
  p.warn.push(`${where}: ask = "${m[2]}" โ€” expected on-change or always, keeping on-change`);
191
197
  return;
192
198
  }
199
+ if (mapped === "release.finish" && !/^(always|on-change)$/.test(m[2].trim())) {
200
+ p.warn.push(`${where}: finish = "${m[2]}" โ€” expected on-change or always, keeping on-change`);
201
+ return;
202
+ }
203
+ if (mapped === "release.publish" && !/^(gate|manual)$/.test(m[2].trim())) {
204
+ p.warn.push(`${where}: publish = "${m[2]}" โ€” expected gate or manual, keeping gate`);
205
+ return;
206
+ }
207
+ if (mapped === "release.recheck" && !/^(always|prep-skip)$/.test(m[2].trim())) {
208
+ p.warn.push(`${where}: recheck = "${m[2]}" โ€” expected prep-skip or always, keeping prep-skip`);
209
+ return;
210
+ }
193
211
  p.flow[stage as MdStage][mapped] = m[2];
194
212
  }
195
213
  }
@@ -271,6 +289,7 @@ export function mdToConfig(p: ParsedMd): Config {
271
289
  ...(c.commands.health && !named.has("health") ? [{ name: "health", cmd: c.commands.health }] : []),
272
290
  ...p.checks.map((x) => ({ name: x.name, cmd: x.cmd })),
273
291
  ];
292
+ c.releaseChecks = p.releaseChecks.map((x) => ({ name: x.name, cmd: x.cmd }));
274
293
  c.checklist = p.checklist;
275
294
  c.prose = p.prose;
276
295
  if (p.workerPreamble.length) c.workerPreamble = [...p.workerPreamble];
@@ -236,7 +236,7 @@ export async function releaseTags(root: string): Promise<string[] | null> {
236
236
  }
237
237
 
238
238
  export const GATE_HELP =
239
- "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=valueโ€ฆ|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui] [--no-ui|--patch|--docs --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] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] โ€” state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog โ€” verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack โ€” --ui on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs, --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 โ€” release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose โ€” finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes โ€” release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed โ€” recorded, never a block โ€” reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes โ€” dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones โ€” roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped) โ€” a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir โ€” doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief โ€” version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
239
+ "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=valueโ€ฆ|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--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)";
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");
@@ -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 { checkFingerprint, DEFAULTS, freshenChecks, healthProbe, 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, 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, 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, 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. */
@@ -28,6 +28,26 @@ export const devPortsFile = (root: string) => path.join(dfDir(root), "dev-ports.
28
28
  export const slotKey = (port: number | undefined) => (port === undefined ? "default" : String(port));
29
29
 
30
30
  /** Live slots only: a slot whose flow finished (state.json gone) or was aborted holds nothing. */
31
+ /** Close a flow's hold on the dev stack: stop a side-by-side instance (a port the operator picked at verify)
32
+ * and give its dev-port entries back. The default port's stack stays up โ€” it is the machine's shared app,
33
+ * and the next flow redeploys over it. Returns the note for the gate's result ("" when nothing ran). */
34
+ export async function releaseDevSlot(root: string, state: FlowState, cfg: Config): Promise<string> {
35
+ let note = "";
36
+ if (state.devPort !== undefined && state.devPort !== cfg.devPort) {
37
+ if (cfg.commands.devDown) {
38
+ const down = await sh(cfg.commands.devDown, gateCwd(root, state), 5 * 60_000, devEnv(root, state, cfg));
39
+ note = down.ok ? ` dev instance on port ${state.devPort} stopped (${cfg.commands.devDown}).` : ` dev instance on port ${state.devPort} did NOT stop (${cfg.commands.devDown}) โ€” stop it by hand:\n${tail(down.out)}\n`;
40
+ } else note = ` dev instance on port ${state.devPort} is still running โ€” the playbook has no devDown to stop it; stop it by hand.`;
41
+ }
42
+ const reg = readDevPorts(root);
43
+ const mine = Object.keys(reg).filter((k) => reg[k].slug === state.slug);
44
+ if (mine.length) {
45
+ for (const k of mine) delete reg[k];
46
+ writeDevPorts(root, reg);
47
+ }
48
+ return note;
49
+ }
50
+
31
51
  export function readDevPorts(root: string): Record<string, DevSlot> {
32
52
  let raw: Record<string, DevSlot>;
33
53
  try {
@@ -249,9 +269,45 @@ export async function worktreeFingerprint(cwd: string): Promise<string | null> {
249
269
  /** Stamp freshly recorded checks with the tree they ran against โ€” taken AFTER the run, so a check
250
270
  * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
251
271
  export async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
252
- const fp = await worktreeFingerprint(gateCwd(root, state));
272
+ const cwd = gateCwd(root, state);
273
+ const fp = await worktreeFingerprint(cwd);
253
274
  if (!fp) return;
254
- for (const n of names) if (state.checks[n]) state.checks[n].wt = fp;
275
+ // a clean tree is exactly its HEAD: only then can a later gate reason about what was committed since
276
+ const st = await sh("git status --porcelain", cwd);
277
+ const head = st.ok && !st.out.trim() ? (await sh("git rev-parse HEAD", cwd)).out.trim() : "";
278
+ for (const n of names)
279
+ if (state.checks[n]) {
280
+ state.checks[n].wt = fp;
281
+ if (head) state.checks[n].head = head;
282
+ else delete state.checks[n].head;
283
+ }
284
+ }
285
+
286
+ /** Green records survive a commit that holds nothing but release prep (the bump, the changelog entry): they
287
+ * are restamped onto the current tree instead of going stale, so the suite does not run twice to prove a
288
+ * version string. Only on a clean tree, only for records taken on a clean tree, and never under
289
+ * `recheck = always`. Returns the names it kept. */
290
+ export async function keepThroughPrep(root: string, state: FlowState, cfg: Config, fp: string | null): Promise<string[]> {
291
+ if (!fp || cfg.release.recheck === "always") return [];
292
+ const cwd = gateCwd(root, state);
293
+ const st = await sh("git status --porcelain", cwd);
294
+ if (!st.ok || st.out.trim()) return [];
295
+ const head = (await sh("git rev-parse HEAD", cwd)).out.trim();
296
+ const kept: string[] = [];
297
+ const verdict = new Map<string, boolean>();
298
+ for (const [name, rec] of Object.entries(state.checks)) {
299
+ if (!rec.ok || !rec.wt || rec.wt === fp || !rec.head || !head) continue;
300
+ if (!verdict.has(rec.head)) {
301
+ const d = await sh(`git diff --name-only ${sq(rec.head)} HEAD`, cwd);
302
+ verdict.set(rec.head, d.ok && prepOnlyChange(cfg, d.out.split("\n").map((l) => l.trim()).filter(Boolean)));
303
+ }
304
+ if (!verdict.get(rec.head)) continue;
305
+ rec.wt = fp;
306
+ rec.head = head;
307
+ rec.prep = true;
308
+ kept.push(name);
309
+ }
310
+ return kept;
255
311
  }
256
312
 
257
313
  /** Commits the feature branch holds over its merge base with the default branch, plus how many
@@ -336,7 +392,41 @@ export async function presentRun(args: string[], root: string, key: string, res:
336
392
  facts = undefined;
337
393
  }
338
394
  const view = presentGate(sub, res.text, !!res.isError, state, cfg, facts);
339
- return { agent: agentText(res.text, view), view };
395
+ // gh#218: a session running an older build than the disk ships must hear it on every gate, not only at
396
+ // start and status โ€” a fix already released never reached the session that needed it
397
+ let agent = agentText(res.text, view);
398
+ if (initiated(root) && !SKEW_SAYS_ITSELF.has(sub)) {
399
+ const skew = buildSkew(root);
400
+ if (skew.line && !agent.includes(skew.line)) agent += `\n${AGENT_MARK}warning: ${skew.line}. Gates in this session run the older build โ€” tell the operator at the next safe point.`;
401
+ }
402
+ return { agent, view };
403
+ }
404
+
405
+ /** Gates that print the build skew in their own words. */
406
+ const SKEW_SAYS_ITSELF = new Set(["start", "status", "version", "release", "help"]);
407
+
408
+ /** gh#209: say at check time that the branch fell behind the default branch, and which files both sides
409
+ * touched โ€” verify's rebase is the right convenience, but it must not be where a conflict is first seen.
410
+ * "" when up to date or when git cannot say. Read-only: nothing is rebased or merged here. */
411
+ export async function behindNote(root: string, state: FlowState, cfg: Config): Promise<string> {
412
+ const cwd = gateCwd(root, state);
413
+ if (cwd === root) return "";
414
+ const d = cfg.defaultBranch;
415
+ const hasOrigin = !!(await originUrl(root));
416
+ if (hasOrigin) await sh(`git fetch -q origin ${sq(d)}`, cwd, 20_000);
417
+ const base = hasOrigin && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, cwd)).ok ? `origin/${d}` : d;
418
+ const r = await sh(`git rev-list --count HEAD..${sq(base)}`, cwd);
419
+ const behind = Number.parseInt(r.out.trim(), 10);
420
+ if (!r.ok || !Number.isFinite(behind) || behind === 0) return "";
421
+ const mb = (await sh(`git merge-base HEAD ${sq(base)}`, cwd)).out.trim();
422
+ const names = async (range: string) => new Set(mb ? (await sh(`git diff --name-only ${range}`, cwd)).out.split("\n").map((l) => l.trim()).filter(Boolean) : []);
423
+ const mine = await names(`${sq(mb)} HEAD`);
424
+ const both = [...(await names(`${sq(mb)} ${sq(base)}`))].filter((f) => mine.has(f));
425
+ // merge-tree predicts the conflicts without touching the tree (git โ‰ฅ 2.38); an older git just lists the overlap
426
+ const mt = await sh(`git merge-tree --write-tree --name-only --no-messages HEAD ${sq(base)}`, cwd);
427
+ const conflicts = !mt.ok ? mt.out.split("\n").slice(1).map((l) => l.trim()).filter((l) => l && !/^(fatal|error|usage)/i.test(l)) : [];
428
+ const list = (xs: string[]) => `${xs.slice(0, 8).join(", ")}${xs.length > 8 ? ` โ€ฆ(${xs.length - 8} more)` : ""}`;
429
+ return `branch is ${behind} commit(s) behind ${base} โ€” flow verify rebases it before the review deploy${conflicts.length ? `; that rebase would conflict in: ${list(conflicts)} โ€” rebase by hand now (git rebase ${base}) and read what ${d} changed there` : both.length ? `; both sides changed: ${list(both)} (no conflict predicted)` : ""}`;
340
430
  }
341
431
 
342
432
  export function describeBranchState(b: BranchState, defaultBranch: string): string {