pi-dev-flow 0.85.1 → 0.86.1

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.
@@ -0,0 +1,629 @@
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
+ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
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 } from "../core.ts";
5
+ import { AGENT_MARK } from "../present.ts";
6
+ 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";
7
+ import { type RunResult, branchState, catchUp, describeBranchState, devEnv, devPortOf, devSlotCheck, healthRerunsAfterDeploy, pendingChecks, probeHealth, readDevPorts, runChecks, slotKey, triedNote, unreleasedOnMain, worktreeFingerprint, writeDevPorts } from "./checks.ts";
8
+ import { type GateCtx, markPendingAsk } from "./gates.ts";
9
+
10
+ export async function gateVerify(o: GateCtx): Promise<RunResult> {
11
+ const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
12
+ const { state, err } = needState(root, sess, slugArg);
13
+ if (err) return err;
14
+ const items = applicableItems(cfg, state!, "implement");
15
+ // the operator reviews the tree that ships: catch up with the default branch before anything runs
16
+ const caught = state!.stage === "implement" ? await catchUp(root, state!, cfg, flag("confirmed")) : { note: "" };
17
+ if ("text" in caught) return caught;
18
+ const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
19
+ if (branch.commitsAhead === 0 && cfg.versioning.file) branch.unreleased = await unreleasedOnMain(gateCwd(root, state!), cfg.versioning.pattern);
20
+ const branchLine = describeBranchState(branch, cfg.defaultBranch);
21
+ // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
22
+ // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
23
+ // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
24
+ const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
25
+ if (staleAtGate.length) writeState(root, state!);
26
+ const pending = pendingChecks(state!, cfg);
27
+ const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
28
+ if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
29
+ // tier-1 gate first (tier-2 confirmation is recorded by this very command, so it is excluded here)
30
+ const preGate = verifyGate({ ...state!, confirmations: { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } } }, cfg, branch);
31
+ if (preGate.length) return { text: `verify gate FAILED:\n- ${preGate.join("\n- ")}\n${branchLine}`, isError: true };
32
+ // a stack another flow is reviewing or releasing on is not this gate's to take — ask before deploying
33
+ const slotted = cfg.commands.dev && !state!.docs ? await devSlotCheck(o, state!) : { note: "" };
34
+ if ("text" in slotted) return slotted;
35
+ // commands that take minutes and touch live services must say so (#38): a terse gate let the
36
+ // agent tell the operator the dev deploy had never run, right after it recreated a container.
37
+ const did: string[] = [];
38
+ if (caught.note) did.push(caught.note);
39
+ if (slotted.note) did.push(slotted.note);
40
+ if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
41
+ if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
42
+ if (state!.docs) {
43
+ // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
44
+ did.push("docs mode: project commands skipped (build/dev/health)");
45
+ } else {
46
+ if (cfg.commands.build) {
47
+ const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
48
+ state!.checks.build = { ok: res.ok, at: now() };
49
+ writeState(root, state!);
50
+ if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
51
+ did.push(`build ran (${cfg.commands.build})`);
52
+ }
53
+ // deploy to dev before asking — the operator reviews the running dev app, not a promise
54
+ const probe = healthProbe(cfg);
55
+ if (cfg.commands.dev) {
56
+ const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
57
+ state!.checks.dev = { ok: res.ok, at: now() };
58
+ writeState(root, state!);
59
+ if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
60
+ did.push(`dev ran (${cfg.commands.dev})${devPortOf(state!, cfg) !== undefined ? ` on port ${devPortOf(state!, cfg)}` : ""}`);
61
+ // the deploy is what must be proven, not just run: a container that came back unhealthy, or
62
+ // still serves the previous build, must not pass on a health PASS recorded before it was
63
+ // recreated. What "the expected version" means is the project's business — the probe runs in
64
+ // the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
65
+ if (!probe) did.push("health: none configured");
66
+ else {
67
+ const probed = await probeHealth(root, state!, cfg, probe);
68
+ if ("seedFail" in probed) return probed.seedFail;
69
+ if (!probed.ok) return { text: `post-deploy probe FAILED (${probe}) — the deploy is not healthy / not serving this build (gave up after ${probed.attempts} attempt(s), healthWait ${cfg.healthWait}s):\n${tail(probed.out)}`, isError: true };
70
+ did.push(`health: PASS (${probe}${triedNote(probed.attempts)})`);
71
+ }
72
+ } else if (!probe) did.push("dev: none configured");
73
+ else {
74
+ // no deploy to prove, but the operator still reviews a live app — and a green health record
75
+ // survives a killed server (process death dirties no worktree fingerprint), so the record
76
+ // cannot stand for liveness: re-probe, before anyone is asked.
77
+ const probed = await probeHealth(root, state!, cfg, probe);
78
+ if ("seedFail" in probed) return probed.seedFail;
79
+ if (!probed.ok)
80
+ return { text: `live probe FAILED (${probe}) — nothing is answering and no dev deploy is configured: the app the operator must review has to be running before verify — start it and rerun (gave up after ${probed.attempts} attempt(s), healthWait ${cfg.healthWait}s):\n${tail(probed.out)}`, isError: true };
81
+ did.push(`health: live re-probe PASS (${probe}${triedNote(probed.attempts)})`);
82
+ }
83
+ }
84
+ if (!state!.docs && cfg.commands.servedBuild) {
85
+ // "something answers" is not "this branch answers": the served commit must be the worktree's HEAD
86
+ const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
87
+ const sb = await sh(cfg.commands.servedBuild, gateCwd(root, state!), 60_000, devEnv(root, state!, cfg));
88
+ if (!sb.ok || !servedBuildMatches(sb.out, head))
89
+ return { text: `served-build check FAILED (${cfg.commands.servedBuild}) — the app is up but does not serve this branch's HEAD ${head.slice(0, 12)}:\n${tail(sb.out)}`, isError: true };
90
+ did.push(`serves ${head.slice(0, 7)} (HEAD)`);
91
+ }
92
+ if (!state!.docs && cfg.commands.dev) {
93
+ const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
94
+ writeDevPorts(root, { ...readDevPorts(root), [slotKey(devPortOf(state!, cfg))]: { slug: state!.slug, head, at: now() } });
95
+ }
96
+ const ran = [branchLine, ...did].join("; ");
97
+ // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
98
+ const yoloWord = takeYoloWord(state!);
99
+ if (yoloWord) return { text: yoloWord, isError: true };
100
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
101
+ const askPending = !flag("confirmed") && !state!.yolo;
102
+ if (askPending) {
103
+ markPendingAsk(root, state!, "Verified?"); // pending however it is asked — a chat question or a dialog
104
+ // the agent's call never opens a dialog (#181): this is the review deploy — the app is up for the
105
+ // operator, and the answer comes back in chat as flow verify --confirmed
106
+ if (!ui.hasUI) {
107
+ const port = devPortOf(state!, cfg);
108
+ const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : "live app re-probed for review";
109
+ return { text: `${needsOperator(`${what} — the app stays up until you answer`, "Verified?", "look at the change in the running app yourself first (the playbook's self-check), then ask the operator Verified? in chat and run flow verify --confirmed once they answer. Keep it running until they answer.")}\n${ran}` };
110
+ }
111
+ const ok = await ui.confirm("Operator verification", `Verified? All checks green${cfg.commands.dev && !state!.docs ? `; dev deploy is up for review (${cfg.commands.dev})` : ""} \u2014 does it work?`);
112
+ if (!ok) {
113
+ delete state!.pendingAsk;
114
+ writeState(root, state!);
115
+ return { text: "verification declined — stay in implement and fix what failed" };
116
+ }
117
+ audit = " (confirmed in dialog)";
118
+ }
119
+ state!.confirmations = { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } };
120
+ const final = verifyGate(state!, cfg, branch);
121
+ if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
122
+ state!.approvals.verify = now();
123
+ if (isReleaseOnly(cfg, branch)) state!.releaseOnly = true;
124
+ else delete state!.releaseOnly;
125
+ // the tree the word was given over (#162) — a git that cannot answer leaves it unset, never a refusal
126
+ const vHead = await sh("git rev-parse HEAD", gateCwd(root, state!));
127
+ if (vHead.ok && vHead.out.trim()) state!.verifiedHead = vHead.out.trim();
128
+ else delete state!.verifiedHead;
129
+ state!.stage = "pre-release";
130
+ delete state!.pendingAsk;
131
+ writeState(root, state!);
132
+ return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
133
+ }
134
+
135
+ export async function gateRelease(o: GateCtx): Promise<RunResult> {
136
+ const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
137
+ const { state, err } = needState(root, sess, slugArg);
138
+ if (err) return err;
139
+ // operator's word at Release?: this flow ships without a version bump or tag — recorded only once Release? is answered
140
+ const noVersion = flag("no-version") || !!state!.noVersion;
141
+ // (versioned) items stand down on an unversioned flow — the set confirmed here is the one that applies to it
142
+ const items = applicableItems(cfg, { ...state!, noVersion }, "pre-release");
143
+ // yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
144
+ const yoloWord = takeYoloWord(state!);
145
+ if (yoloWord) return { text: yoloWord, isError: true };
146
+ // prep evidence is read from the worktree: the bump and changelog entry exist on the branch before the PR merges
147
+ const wtCwd = gateCwd(root, state!);
148
+ // gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix
149
+ // that never ships. verify shows the operator uncommitted paths; release proves them away. A git
150
+ // that cannot answer is a measurement failure, never a refusal — same stance as the merge-base probes.
151
+ const dirtyWt = await sh("git status --porcelain", wtCwd);
152
+ if (dirtyWt.ok && dirtyWt.out.trim()) {
153
+ const n = dirtyWt.out.split("\n").filter((l) => l.trim()).length;
154
+ 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 };
155
+ }
156
+ const branchProof = await branchState(wtCwd, cfg.defaultBranch);
157
+ const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
158
+ ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
159
+ : null;
160
+ // tags are only needed on the versioned path; a project without versioning must not be held up by an offline origin
161
+ const remoteTags = cfg.versioning.file && !noVersion ? await releaseTags(root) : [];
162
+ if (remoteTags === null) return { text: "release gate FAILED:\n- cannot list tags on origin (offline?) — retry; local tags do not decide what is already released", isError: true };
163
+ const changelog =
164
+ cfg.release.changelog && existsSync(path.join(wtCwd, cfg.release.changelog))
165
+ ? { file: cfg.release.changelog, content: readFileSync(path.join(wtCwd, cfg.release.changelog), "utf8") }
166
+ : null;
167
+ // The changelog's baseline is what was pending before this release. The newest tag wins over the
168
+ // merge base: it is what actually shipped, and a rebase or squash merge can leave the merge base
169
+ // unreachable — a git-topology accident must not refuse a legal release (#97).
170
+ let changelogChanged: boolean | null = null;
171
+ const changelogBase: { pending: string[]; source: "tag" | "merge-base" | "none" } = { pending: [], source: "none" };
172
+ if (changelog) {
173
+ const p = sq(cfg.release.changelog!);
174
+ const mbRef = await mergeBase(wtCwd, cfg.defaultBranch);
175
+ // proof the branch touched the changelog: local refs only, so the check stays offline-safe
176
+ if (mbRef) {
177
+ const changes = await sh(`git diff --name-only ${sq(mbRef)} -- ${p} 2>/dev/null; git ls-files --others --exclude-standard -- ${p}`, wtCwd);
178
+ changelogChanged = changes.out.split("\n").some((l) => l.trim());
179
+ }
180
+ const newest = !noVersion && cfg.versioning.file ? newestTaggedVersion(cfg.versioning.pattern, remoteTags) : null;
181
+ // tag first, merge base as the understudy: `releaseTags` asks origin, so a clone that has not
182
+ // fetched the tag yet must still get a baseline instead of losing the fold proof
183
+ const bases: { ref: string; source: "tag" | "merge-base" }[] = [];
184
+ if (newest) bases.push({ ref: cfg.versioning.pattern.replace("{version}", newest), source: "tag" });
185
+ if (mbRef) bases.push({ ref: mbRef, source: "merge-base" });
186
+ for (const b of bases) {
187
+ const base = await sh(`git show ${sq(b.ref)}:${p} 2>/dev/null || true`, wtCwd);
188
+ if (base.out.trim()) {
189
+ changelogBase.pending = pendingEntryLines(base.out);
190
+ changelogBase.source = b.source;
191
+ break;
192
+ }
193
+ }
194
+ }
195
+ // #164: a hand-resolved merge can commit a leftover marker — content to git, so nothing else catches it
196
+ const markerBase = await mergeBase(wtCwd, cfg.defaultBranch);
197
+ const markerDiff = markerBase ? await sh(`git diff -U0 --no-color --no-ext-diff ${sq(markerBase)} HEAD`, wtCwd) : null;
198
+ const conflictMarkers = markerDiff?.ok ? conflictMarkerLines(markerDiff.out) : undefined;
199
+ const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check"), conflictMarkers, noMarkerCheck: flag("no-marker-check") };
200
+ // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
201
+ if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
202
+ // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
203
+ const preGate = preReleaseGate({ ...state!, noVersion, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
204
+ if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
205
+ // the build the tag will trigger, proven before anything ships: a broken artifact build found after the
206
+ // tag costs follow-up PRs and a re-cut tag
207
+ if (cfg.release.preflight) {
208
+ const pf = await sh(cfg.release.preflight, wtCwd);
209
+ if (!pf.ok) return { text: `release gate FAILED:\n- release.preflight failed in ${state!.worktree} (${cfg.release.preflight}) — fix it on the branch before anything ships:\n${tail(pf.out)}`, isError: true };
210
+ }
211
+ // a stale session build is the operator's decision, never a block: publishing under an older gate is a
212
+ // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
213
+ // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
214
+ // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
215
+ const { disk: selfBuild, behind } = buildSkew(root);
216
+ // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
217
+ // has every proof the checkout would run, and asking about it would be noise.
218
+ const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
219
+ let staleAsk = "";
220
+ let staleNote = "";
221
+ if (stale) {
222
+ const clPath = path.join(selfBuild.dir, "CHANGELOG.md");
223
+ const missing = existsSync(clPath) && selfBuild.version ? changelogVersionsBetween(readFileSync(clPath, "utf8"), behind, selfBuild.version) : [];
224
+ staleAsk =
225
+ ` This session runs dev-flow ${behind}, ${selfBuild.label} ships ${selfBuild.version ?? "?"} — gate proofs shipped between the two will NOT run. ` +
226
+ (missing.length
227
+ ? `Shipped since ${behind}: ${missing.slice(0, 8).join(", ")}${missing.length > 8 ? ` …(${missing.length} total)` : ""} — see ${clPath}. `
228
+ : `What shipped between them is not readable from the checkout's CHANGELOG.md — read it before deciding. `) +
229
+ `Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
230
+ staleNote = `released under dev-flow ${behind} (${selfBuild.label} ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
231
+ }
232
+ // #162: Verified? was answered over one tree; commits after it ship under that word unless someone says
233
+ // so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
234
+ let postVerify = "";
235
+ if (state!.verifiedHead) {
236
+ // gh#180: upstream work merged in after the verdict was approved on its own branch — only the branch's
237
+ // own commits are news to the operator; the merged-in ones are a count, not a list to wade through
238
+ const d = cfg.defaultBranch;
239
+ const upstream = (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, wtCwd)).ok ? `origin/${d}` : (await sh(`git rev-parse --verify -q ${sq(`refs/heads/${d}`)}`, wtCwd)).ok ? d : "";
240
+ const since = await sh(`git log --oneline --no-decorate ${upstream ? "--no-merges " : ""}${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`, wtCwd);
241
+ const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
242
+ const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
243
+ const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
244
+ // a release-only flow commits its bump and changelog after verify by design — only other files count
245
+ const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
246
+ const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
247
+ const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
248
+ if (commits.length && !prepOnly)
249
+ postVerify = `${commits.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${commits.slice(0, 6).join(" | ")}${commits.length > 6 ? ` …(${commits.length - 6} more)` : ""}${mergedIn ? ` (+${mergedIn} merged in from ${upstream}, not listed)` : ""} — the verify verdict does not cover them: if behaviour changed, have the operator check the current build before Release?, and either way say in the PR body which commit the verdict was given over`;
250
+ }
251
+ // a standing yolo (given at an earlier checkpoint) stops short of Release? when the playbook says so, or
252
+ // when commits landed after Verified? — the word was given before those commits existed (gh#176).
253
+ // --confirmed is the operator's own answer at this checkpoint, yolo-at-Release? included: it always stands.
254
+ const yoloHeld = !state!.yolo || flag("confirmed")
255
+ ? ""
256
+ : cfg.release.yolo === "until-release"
257
+ ? "the playbook sets yolo = until-release: a yolo given earlier never answers Release? — ask it"
258
+ : postVerify
259
+ ? "a yolo given earlier does not cover commits that landed after Verified? — ask Release? with them named"
260
+ : "";
261
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
262
+ const askPending = !flag("confirmed") && (!state!.yolo || !!yoloHeld);
263
+ if (askPending) {
264
+ markPendingAsk(root, state!, "Release?");
265
+ if (!ui.hasUI) {
266
+ return { text: needsOperator(`ready to publish${yoloHeld ? ` (${yoloHeld})` : ""}${stale ? ` — also: ${staleAsk}` : ""}${postVerify ? ` — ${postVerify}` : ""}`, "Release?", `re-run with --confirmed once the operator answered 'Release?' in chat${stale ? " (and the stale-build question)" : ""}`), isError: true };
267
+ }
268
+ const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}${postVerify ? `\n\n${postVerify}` : ""}${yoloHeld ? `\n\n(${yoloHeld})` : ""}`);
269
+ if (!ok) {
270
+ delete state!.pendingAsk;
271
+ writeState(root, state!);
272
+ return { text: "release declined — keep preparing in pre-release" };
273
+ }
274
+ audit = " (confirmed in dialog)";
275
+ }
276
+ if (noVersion) state!.noVersion = true;
277
+ state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
278
+ state!.approvals["pre-release"] = now();
279
+ state!.stage = "release";
280
+ // a skipped proof is never silent: the gate says which one and why (#97)
281
+ const foldNote = !changelog
282
+ ? ""
283
+ : flag("no-fold-check")
284
+ ? " Warning: the changelog fold proofs were skipped (--no-fold-check) — check that the entry carries what was pending."
285
+ : changelogBase.source === "none"
286
+ ? " Warning: no tag or merge base to compare against, so the changelog fold was not proven — check the entry by hand."
287
+ : "";
288
+ // the version of record is fixed here, from the manifest this gate validated: release-done must not
289
+ // re-read a checkout that may still be behind (#52)
290
+ if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
291
+ if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
292
+ delete state!.pendingAsk;
293
+ writeState(root, state!);
294
+ return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}${postVerify ? ` Warning: ${postVerify}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
295
+ }
296
+
297
+ export async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
298
+ const { root, sess, cfg, flag, slugArg } = o;
299
+ const { state, err } = needState(root, sess, slugArg);
300
+ if (err) return err;
301
+ const errs = releaseGate(state!);
302
+ // the version of record is what flow release approved (#52) — never a re-read of a checkout that may be behind
303
+ const manifestVer: string | null = state!.releaseVersion ?? null;
304
+ if (cfg.versioning.file && !state!.noVersion && !manifestVer) errs.push(`flow release approved no version (versioning.file "${cfg.versioning.file}" was set after it?) — fix the playbook, or ship this flow unversioned`);
305
+ const expectedTag = manifestVer ? cfg.versioning.pattern.replace("{version}", manifestVer) : null;
306
+ const origin = await originUrl(root);
307
+ const hasOrigin = origin !== null;
308
+ const forgeName = forgeOf(cfg, origin);
309
+ // one round-trip answers both questions about the tag: is it there, and did it leave this laptop (#52)
310
+ const tags = expectedTag ? await releaseTags(root) : [];
311
+ if (tags === null) errs.push("cannot list tags on origin (offline?) — retry: local tags must not decide what is already released");
312
+ else if (expectedTag && manifestVer) {
313
+ const verrs = versionTagGate(manifestVer, cfg.versioning.pattern, tags);
314
+ if (verrs.length) {
315
+ // the actionable version of "not on the forge": the tag exists but never got pushed
316
+ const local = hasOrigin ? (await sh(`git tag --list ${sq(expectedTag)}`, root)).out.trim() : "";
317
+ if (local) errs.push(`tag ${expectedTag} is local-only — git push origin ${expectedTag} (git push --follow-tags silently skips lightweight tags; tag with git tag -a and push the ref explicitly)`);
318
+ else errs.push(...verrs);
319
+ }
320
+ // never publish behind what the forge already has — that is how a stale manifest republished
321
+ // the previous version and its artifact probe passed (#52)
322
+ const newest = newestTaggedVersion(cfg.versioning.pattern, tags);
323
+ if (newest && cmpVersions(newest, manifestVer) > 0) errs.push(`${cfg.versioning.pattern.replace("{version}", newest)} is already tagged — refusing to release ${expectedTag} behind it`);
324
+ if (!verrs.length) {
325
+ const reach = await sh(`git merge-base --is-ancestor ${sq(expectedTag)} origin/${cfg.defaultBranch} 2>/dev/null || git merge-base --is-ancestor ${sq(expectedTag)} ${cfg.defaultBranch}`, root);
326
+ if (!reach.ok) errs.push(`tag ${expectedTag} is not reachable from ${cfg.defaultBranch} — tag what actually shipped on ${cfg.defaultBranch}`);
327
+ }
328
+ }
329
+ let artNote = "";
330
+ if (expectedTag && cfg.release.artifact) {
331
+ if (flag("no-artifact-check")) artNote = "Artifact check skipped (--no-artifact-check).";
332
+ else {
333
+ const cmd = cfg.release.artifact.replaceAll("{version}", manifestVer!).replaceAll("{tag}", expectedTag);
334
+ const art = await sh(cmd, root);
335
+ if (art.ok) artNote = `Artifact verified for ${manifestVer}.`;
336
+ else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
337
+ }
338
+ }
339
+ // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
340
+ // refuses the release record; what dev-flow cannot see stays an advisory — the split the changelog
341
+ // proofs learned (#97): an invisible topology never blocks a legal release.
342
+ let mergeNote = "";
343
+ if (cfg.release.merge && cfg.release.merge !== "any" && state!.branch) {
344
+ const br = state!.branch;
345
+ await sh(`git fetch -q origin ${sq(br)} 2>/dev/null; git fetch -q origin ${sq(cfg.defaultBranch)} 2>/dev/null`, root);
346
+ const refsOk = hasOrigin && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${br}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
347
+ // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
348
+ // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
349
+ const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
350
+ const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeName, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
351
+ if (proof.errors.length) errs.push(...proof.errors);
352
+ else mergeNote = proof.note;
353
+ }
354
+ if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
355
+ // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
356
+ const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false;
357
+ let ghNote = "";
358
+ let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
359
+ let bodyNote = "";
360
+ if (manifestVer && flag("no-release-create")) ghNote = "Forge release skipped (--no-release-create).";
361
+ else if (manifestVer && !releasesWanted) ghNote = "no forge release created (release.releases = false — the playbook says publication is manual; a stale key is how a repo ends up with tags and an empty Releases page #85).";
362
+ else if (manifestVer && releasesWanted) {
363
+ // forge release for the verified tag — gh for GitHub, glab for GitLab. A failed create is no
364
+ // longer the end of the story: the proof below asks the forge whether anything is there (#63, #85)
365
+ const tag = expectedTag!;
366
+ if (forgeName === "self") ghNote = "Forge release skipped (forge=self — publication stays manual).";
367
+ else {
368
+ // the body is the changelog entry for this version (#97); the tag annotation only stands in
369
+ // when the changelog has no entry for it — and never the output of a failed command, which
370
+ // is how a shell error became a release body (#51)
371
+ const notesRes = await sh(tagNotesCommand(tag), root);
372
+ const annotation = notesRes.ok ? notesRes.out.trim() : "";
373
+ let changelogText: string | null = null;
374
+ if (cfg.release.changelog) {
375
+ const cl = path.join(gateCwd(root, state!), cfg.release.changelog);
376
+ if (existsSync(cl)) changelogText = readFileSync(cl, "utf8");
377
+ }
378
+ const picked = pickReleaseNotes({ changelog: changelogText, version: manifestVer, annotation });
379
+ const notes = picked.notes;
380
+ if (picked.source === "changelog") bodyOfRecord = notes;
381
+ let notesNote = "";
382
+ if (picked.source === "changelog") notesNote = `notes from ${cfg.release.changelog}. `;
383
+ else if (picked.source === "annotation") notesNote = `notes from the ${tag} tag annotation — ${cfg.release.changelog ?? "no changelog"} has no ${manifestVer} entry, so the release page does not read like the changelog. `;
384
+ else if (!notesRes.ok) notesNote = `no release notes (the tag command failed: ${tail(notesRes.out)}). `;
385
+ else if (annotation && looksLikeShellError(annotation)) notesNote = "no release notes (the tag command returned a shell error, not a body). ";
386
+ else notesNote = `no release notes (tag ${tag} carries no annotation${cfg.release.changelog ? ` and ${cfg.release.changelog} has no ${manifestVer} entry` : ""} — tag with git tag -a). `;
387
+ const cmd = forgeName === "gitlab"
388
+ ? `glab release create ${sq(tag)} --name ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`
389
+ : `gh release create ${sq(tag)} --title ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`;
390
+ const gr = await sh(cmd, root);
391
+ // a failed create is the operator's call to decline, never a choice we make for them — stamp it so finish names it (#63)
392
+ if (gr.ok) delete state!.forgeReleaseSkipped; // a successful retry lifts the stamp
393
+ else state!.forgeReleaseSkipped = tail(gr.out);
394
+ ghNote = gr.ok ? `${forgeName} release ${tag} created. ${notesNote}`.trim() : `${forgeName} release skipped: ${tail(gr.out)}`;
395
+ }
396
+ }
397
+ const skew = buildSkew(root);
398
+ const openRelease = checklistPending(cfg, state!, "release");
399
+ // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
400
+ // name them at the last objective gate — on the way out too, or the refusal hides half the story
401
+ const openNote = openRelease ? `release-stage checklist still open (${openRelease}): ${applicableItems(cfg, state!, "release").map((i) => i.text).join(" | ")} — close these with the operator before finishing.` : "";
402
+ // #85: ask the forge whether the release exists instead of trusting the attempt. #51, #60 and #63
403
+ // were three ways of recording a release nothing published, and the artifact probe saw none of them
404
+ if (releasesWanted && expectedTag && forgeName !== "self") {
405
+ const view = forgeName === "gitlab" ? `glab release view ${sq(expectedTag)}` : `gh release view ${sq(expectedTag)}`;
406
+ if (!(await sh(view, root)).ok) {
407
+ return { text: `release gate FAILED:\n- no ${forgeName} release exists for ${expectedTag} — create it (${view.split(" ")[0]} release create ${expectedTag}) or, if publication is deliberately manual, say so with release.releases = false in project.md${ghNote ? `. ${ghNote}` : ""}${openNote ? ` ${openNote}` : ""}`, isError: true };
408
+ }
409
+ delete state!.forgeReleaseSkipped; // the forge has it, whatever the create call reported
410
+ ghNote += `${ghNote ? " " : ""}Release ${expectedTag} verified on ${forgeName}.`;
411
+ // #97: the changelog entry is the release body — prove the forge kept it. gh normalizes the
412
+ // markdown it stored, so the comparison normalizes too; on another forge say it was skipped
413
+ // rather than guess at a JSON shape nobody pinned.
414
+ if (bodyOfRecord !== null) {
415
+ if (forgeName !== "github") bodyNote = `Release body proof skipped (forge=${forgeName}).`;
416
+ else {
417
+ const got = await sh(`gh release view ${sq(expectedTag)} --json body --jq .body`, root);
418
+ if (!got.ok) bodyNote = `warning: could not read back the ${expectedTag} release body — compare it with ${cfg.release.changelog} by hand.`;
419
+ else if (normalizeReleaseBody(got.out) !== normalizeReleaseBody(bodyOfRecord))
420
+ return {
421
+ text: `release gate FAILED:\n- the ${expectedTag} release body is not the ${cfg.release.changelog} entry for ${manifestVer} — publish the entry as the body: gh release edit ${expectedTag} --title ${expectedTag} --notes-file <(the entry)\n forge body starts: ${tail(normalizeReleaseBody(got.out), 4)}\n changelog entry starts: ${tail(normalizeReleaseBody(bodyOfRecord), 4)}`,
422
+ isError: true,
423
+ };
424
+ else bodyNote = `Release ${expectedTag} body matches ${cfg.release.changelog}.`;
425
+ }
426
+ }
427
+ }
428
+ state!.approvals.release = now();
429
+ const tailNote = [
430
+ // a session that shipped from behind: the code it runs is not the code the checkout just released
431
+ state!.staleBuild
432
+ ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
433
+ : skew.behind
434
+ // #117: the pair (session vs what the disk ships) makes the warning actionable where it prints;
435
+ // a second registered copy is what made the skew confusing on the report — name it too
436
+ ? `warning: ${skew.line}.${copyWarning() ? ` ${copyWarning()}` : ""}`
437
+ : "",
438
+ mergeNote,
439
+ openNote,
440
+ ghNote,
441
+ bodyNote,
442
+ artNote,
443
+ ].filter(Boolean).join(" ");
444
+ writeState(root, state!);
445
+ return { text: `release recorded as complete${state!.noVersion ? " (unversioned — the changelog entry ships under Unreleased; the next versioned release folds it)" : ""}.${tailNote ? ` ${tailNote}` : ""}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
446
+ }
447
+
448
+ /** finish, with the release record folded in: published but not yet recorded, finish runs release-done's
449
+ * proofs itself — that gate asks nothing, so a separate call was a round trip with no decision in it.
450
+ * Its refusal is finish's refusal; its report heads finish's. */
451
+ export async function gateFinish(o: GateCtx): Promise<RunResult> {
452
+ const { state, err } = needState(o.root, o.sess, o.slugArg);
453
+ if (err || !state || state.approvals.release || state.stage !== "release" || !state.approvals["pre-release"]) return gateFinishCore(o);
454
+ const rec = await gateReleaseDone({ ...o, rest: o.rest.filter((a) => a !== "--confirmed" && a !== "--yolo") });
455
+ if (rec.isError) return rec;
456
+ const fin = await gateFinishCore(o);
457
+ const recorded = rec.text.split("\n").filter((l) => !l.startsWith(AGENT_MARK)).join("\n");
458
+ return { ...fin, text: `${recorded}\n\n${fin.text}` };
459
+ }
460
+
461
+ export async function gateFinishCore(o: GateCtx): Promise<RunResult> {
462
+ const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
463
+ const { state, err } = needState(root, sess, slugArg);
464
+ if (err) return err;
465
+ if (!state!.approvals.release)
466
+ return { text: `finish closes a released feature — stage is "${state!.stage}" and no release is recorded; run flow release-done first (to abandon an unfinished feature, run flow abort)`, isError: true };
467
+ // after this the flow state is gone: nothing may sit uncommitted or unpushed
468
+ const dirty = await sh("git status --porcelain", root);
469
+ 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 };
470
+ const origin = await originUrl(root);
471
+ const hasOriginF = origin !== null;
472
+ if (hasOriginF) {
473
+ const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
474
+ if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
475
+ }
476
+ // close-out also syncs the main checkout: a released flow must never leave local
477
+ // <default> trailing origin — the push check above proved nothing local-only remains, so a
478
+ // differing sha means local trails and the fast-forward is safe. never a merge: a diverged
479
+ // or not-checked-out main prints the operator's exact command instead of touching anything
480
+ let syncNote = "";
481
+ if (hasOriginF) {
482
+ const headSha = await sh("git rev-parse HEAD", root);
483
+ const originSha = await sh(`git rev-parse ${sq(`origin/${cfg.defaultBranch}`)}`, root);
484
+ if (headSha.ok && originSha.ok && headSha.out.trim() !== originSha.out.trim()) {
485
+ const onDefault = (await currentBranch(root)) === cfg.defaultBranch;
486
+ const ff = onDefault ? await sh(`git merge --ff-only ${sq(`origin/${cfg.defaultBranch}`)}`, root) : { ok: false, out: "" };
487
+ syncNote = ff.ok
488
+ ? ` local ${cfg.defaultBranch} fast-forwarded to origin/${cfg.defaultBranch}.`
489
+ : ` local ${cfg.defaultBranch} trails origin/${cfg.defaultBranch} and did not fast-forward cleanly — sync by hand: git -C ${sq(root)} pull --ff-only`;
490
+ }
491
+ }
492
+ // the cleanup part of closing out: drop the worktree and branch the release consumed
493
+ const wt = worktreeAbs(root, state!);
494
+ let closeNote: string;
495
+ let unmergedNote = "";
496
+ if (wt && existsSync(wt)) {
497
+ const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
498
+ const unmerged = await sh(`git -C ${sq(wt)} log origin/${cfg.defaultBranch}..HEAD --oneline 2>/dev/null || git -C ${sq(wt)} log ${cfg.defaultBranch}..HEAD --oneline`, root);
499
+ const unmergedLines = unmerged.out.split("\n").filter(Boolean);
500
+ // the refusal names the paths, not just the count — same proof verify and release print (gh#131)
501
+ if (status.out.trim()) return { text: `finish blocked:\n- worktree has uncommitted changes — commit or discard them first:\n${tail(status.out)}`, isError: true };
502
+ if (unmergedLines.length) {
503
+ const policy = cfg.release.merge;
504
+ // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
505
+ // or a branch that was never pushed, the same count describes a local-only repo, not a squash
506
+ const measurable = hasOriginF && !!state!.branch && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${state!.branch}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
507
+ unmergedNote =
508
+ policy && policy !== "merge" && policy !== "any"
509
+ ? ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
510
+ : policy === "merge" && measurable
511
+ ? ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} although the playbook says merge = merge — that PR did not land as a merge commit`
512
+ : ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
513
+ // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
514
+ // answer it, only the operator does
515
+ if (policy === "merge" && measurable && !flag("confirmed")) {
516
+ markPendingAsk(root, state!, "Merge policy violation?");
517
+ return { text: needsOperator(`the playbook says merge = merge, but ${unmergedLines.length} commit(s) of ${state!.slug} are not on ${cfg.defaultBranch} — the PR landed as a squash or a rebase`, "Merge policy violation?", "ask the operator how to proceed, then re-run with --confirmed"), isError: true };
518
+ }
519
+ }
520
+ }
521
+ // a forge release that failed at release-done is still the operator's call — but they must see it before the state vanishes (#63)
522
+ const forgeSkipNote = state!.forgeReleaseSkipped ? ` WARNING: the forge release was not created (${state!.forgeReleaseSkipped}) — recreate it manually or re-run release-done before finishing.` : "";
523
+ // the one finish question — asked after the safety checks so it can never be a wasted question
524
+ // yolo works uniformly at every gate: at Finish? nothing later remains to pre-confirm, the flag just answers this one
525
+ const yoloWord = takeYoloWord(state!);
526
+ if (yoloWord) return { text: yoloWord, isError: true };
527
+ // The closing reflection runs here, before anything is removed: the worker reads this session's
528
+ // transcripts and .dev-flow/<slug>/tmp, and finish is about to drop that folder and the binding — a
529
+ // reflection asked for after finish has nothing bound to run against. Only the operator's explicit
530
+ // --no-reflect skips it; yolo never does (it answers checkpoints, it does not waive the review).
531
+ const skipReflect = flag("no-reflect");
532
+ if (skipReflect && !flag("confirmed")) return { text: "--no-reflect is the operator's word — ask them whether to skip the closing reflection, then re-run with --no-reflect --confirmed", isError: true };
533
+ // a flow that never hit a refusal or a guard block, with no friction note from the operator, has nothing
534
+ // for the reflection worker to find — skip the worker run unless the playbook says reflect = always
535
+ const note = flagValue(o.rest, "note") ?? "";
536
+ const quiet = !state!.reflectedAt && !skipReflect && cfg.release.reflect !== "always" && !(state!.friction ?? 0) && !note.trim();
537
+ if (quiet) {
538
+ state!.reflectedAt = now();
539
+ writeState(root, state!);
540
+ }
541
+ const quietNote = quiet ? " closing reflection skipped: no refusals or guard blocks this flow (playbook reflect = always runs it anyway)." : "";
542
+ if (!state!.reflectedAt && !skipReflect) {
543
+ const skipHint = "or — only on the operator's explicit word — flow finish --no-reflect --confirmed";
544
+ if (!o.hooks.reflect) return { text: `finish: no reflection recorded for ${state!.slug} and no reflect worker available here — run flow_stage(op: "reflect") first, ${skipHint}`, isError: true };
545
+ const r = await o.hooks.reflect(state!, flagValue(o.rest, "note") ?? "");
546
+ const cur = readState(root, state!.slug) ?? state!; // the worker stamped reflectedAt on disk
547
+ if (!r.recorded)
548
+ return { text: `finish: the closing reflection did not report — nothing was removed.\n\n${r.text}\n\nNext: re-run flow finish to retry, or review inline (bare flow reflect prints the protocol) and then flow_stage(op: "reflect"), ${skipHint}.`, isError: true };
549
+ if (!r.findings) {
550
+ markPendingAsk(root, cur, "Finish?");
551
+ return { text: needsOperator(`the closing reflection found nothing new to fold — nothing was removed yet; on your word the worktree, branch and .dev-flow/${state!.slug}/ go.\n\n${r.text}`, "Finish?", "ask the operator Finish? and run flow finish --confirmed when they answer"), isError: true };
552
+ }
553
+ markPendingAsk(root, cur, "Fold or drop?");
554
+ return { text: needsOperator(`the closing reflection has findings — nothing was removed yet; your fold/drop answer also finishes the feature.\n\n${r.text}`, "Fold or drop?", `the fold/drop answer is the Finish? answer: apply it, then run flow finish --confirmed without asking again — the worktree, branch and .dev-flow/${state!.slug}/ go on that run`), isError: true };
555
+ }
556
+ const reflectSkipNote = skipReflect && !state!.reflectedAt ? ` Reflection skipped on the operator's word — nothing re-checked this session or the open reflections.` : "";
557
+ const askPending = !flag("confirmed") && !state!.yolo;
558
+ if (askPending) {
559
+ markPendingAsk(root, state!, "Finish?");
560
+ if (!ui.hasUI) {
561
+ return { text: needsOperator(`cleanup removes the worktree, branch and feature folder.${quietNote}${forgeSkipNote}`, "Finish?", "ask the operator Finish? in chat, then re-run with --confirmed"), isError: true };
562
+ }
563
+ const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
564
+ if (!ok) {
565
+ delete state!.pendingAsk;
566
+ writeState(root, state!);
567
+ return { text: "finish declined" };
568
+ }
569
+ }
570
+ // a side-by-side dev instance (a port the operator picked at verify) is this flow's to stop; the default
571
+ // port's stack stays up — it is the machine's shared app, and the next flow redeploys over it
572
+ let devDownNote = "";
573
+ if (state!.devPort !== undefined && state!.devPort !== cfg.devPort) {
574
+ if (cfg.commands.devDown) {
575
+ const down = await sh(cfg.commands.devDown, gateCwd(root, state!), 5 * 60_000, devEnv(root, state!, cfg));
576
+ devDownNote = 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`;
577
+ } else devDownNote = ` dev instance on port ${state!.devPort} is still running — the playbook has no devDown to stop it; stop it by hand.`;
578
+ }
579
+ const reg = readDevPorts(root);
580
+ const mine = Object.keys(reg).filter((k) => reg[k].slug === state!.slug);
581
+ if (mine.length) {
582
+ for (const k of mine) delete reg[k];
583
+ writeDevPorts(root, reg);
584
+ }
585
+ if (wt && existsSync(wt)) {
586
+ const rm = await sh(`git worktree remove ${sq(wt)} && git branch -D ${sq(state!.branch)}`, root);
587
+ if (!rm.ok) return { text: `worktree removal failed:\n${rm.out}\nif files are owned by another user (e.g. root-owned docker build output), remove ${state!.worktree} manually and rerun flow finish`, isError: true };
588
+ closeNote = `worktree and branch ${state!.branch} removed`;
589
+ } else {
590
+ await sh("git worktree prune", root);
591
+ closeNote = "worktree already gone";
592
+ if (state!.branch && (await sh(`git rev-parse --verify --quiet refs/heads/${state!.branch}`, root)).ok) {
593
+ const del = await sh(`git branch -d ${sq(state!.branch)}`, root);
594
+ closeNote = del.ok ? `branch ${state!.branch} deleted` : `branch ${state!.branch} kept (not fully merged — git branch -D if sure)`;
595
+ }
596
+ }
597
+ // remote cleanup: origin/<branch> is deleted only on proof it was released — being an ancestor of
598
+ // origin/<default> (merge-commit merges) or a merged PR via gh (squash merges); else it stays.
599
+ let remoteNote = "";
600
+ if (state!.branch && hasOriginF) {
601
+ const br = state!.branch;
602
+ const onRemote = await sh("git ls-remote --heads origin", root);
603
+ if (onRemote.out.split("\n").some((l) => l.endsWith(`\trefs/heads/${br}`))) {
604
+ await sh(`git fetch -q origin ${sq(br)}`, root);
605
+ let merged = (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok;
606
+ // squash merges leave no ancestry — ask the forge (gh/glab); self-hosted stays on ancestry proof
607
+ if (!merged) merged = (await forgeMergeStyle(root, forgeOf(cfg, origin), br)) !== null;
608
+ if (merged) remoteNote = (await sh(`git push origin --delete ${sq(`refs/heads/${br}`)}`, root)).ok
609
+ ? ` origin/${br} deleted (verified merged)`
610
+ : ` origin/${br} delete failed — git push origin --delete ${br}`;
611
+ else remoteNote = ` origin/${br} kept — merged state not verifiable from here (git push origin --delete ${br} when sure)`;
612
+ }
613
+ }
614
+ rmSync(featDir(root, state!.slug), { recursive: true, force: true });
615
+ if (sess.slug === state!.slug) sess.bind(null);
616
+ // a feature picked from the backlog closes its own item: check off what `roadmap pick` stamped (slug)
617
+ let roadmapNote = "";
618
+ if (existsSync(roadmapFile(root))) {
619
+ const r = roadmapDoneForSlug(readRoadmap(root), state!.slug, new Date().toISOString().slice(0, 10));
620
+ if (r.count) {
621
+ writeFileSync(roadmapFile(root), r.text);
622
+ roadmapNote = ` roadmap: ${r.count} item(s) marked done.`;
623
+ }
624
+ }
625
+ // finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
626
+ const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
627
+ const nudgeNote = [nudge.fix, nudge.tidy].filter(Boolean).map((n) => ` ${n} — offer it to the operator.`).join("");
628
+ return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${devDownNote}${roadmapNote}${forgeSkipNote}${reflectSkipNote}${quietNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
629
+ }