pi-dev-flow 0.85.0 → 0.86.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.
@@ -0,0 +1,719 @@
1
+ /** dev-flow runtime — The gate runner and the gates that do not ship anything. Moved out of extensions/dev-flow.ts as is (exports added). */
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { approveGate, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapOpenCount, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState } from "../core.ts";
5
+ import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
6
+ import { linkedTag } from "../fold.ts";
7
+ import { detectProject } from "../detect.ts";
8
+ import { AGENT_MARK } from "../present.ts";
9
+ import { GATE_HELP, SELF_BUILD, type Ui, buildSkew, copyWarning, currentBranch, dfDir, featDir, featureEnv, flagValue, gateCwd, gitConsistency, initiated, loadedVersion, mergeHistoryEvidence, needState, now, originUrl, publishedVersion, readClaim, readReflections, readReflectionsText, readRoadmap, readState, roadmapFile, sh, stateFile, tail, unfinishedStates, writePlaybookMergePolicy, writeState } from "./base.ts";
10
+ import { type RunResult, type Session, ago, pendingChecks, probeHealth, readDevPorts, runChecks, stampChecks, triedNote } from "./checks.ts";
11
+ import { GIT_TRACK_NOTE, isSelfRepo, renderQuestions, setupQuestions, tagPatternEvidence } from "./setup.ts";
12
+ import { foldRows, foldView, legacyPluginRows, pluginUpstream, reflectDoneNote, reflectList, reflectMoveNote, reflectNote, reflectTidy } from "./reflect.ts";
13
+ import { gateFinish, gateRelease, gateReleaseDone, gateVerify } from "./ship.ts";
14
+
15
+ /** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
16
+ export interface FlowHooks {
17
+ reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean }>;
18
+ }
19
+
20
+ /** Single runner for both the /flow command and the flow tool. */
21
+ export async function runFlow(args: string[], root: string, ui: Ui, sess: Session, hooks: FlowHooks = {}): Promise<RunResult> {
22
+ const [sub = "status", ...rest] = args;
23
+ // help and version are questions about the plugin, not the repo: answerable with no .dev-flow/ at all
24
+ if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, loadedVersion()) : `usage: flow <sub> — ${GATE_HELP}` };
25
+ // an uninitiated folder is dormant: every gate verb but init and version needs the operator playbook (project.md)
26
+ if (!initiated(root) && sub !== "init" && sub !== "version") return { text: "dev-flow is not initiated here — no .dev-flow/project.md — run flow init first", isError: true };
27
+ const cfg = loadProject(dfDir(root)).cfg;
28
+ const flag = (name: string) => rest.includes(`--${name}`);
29
+ // the yolo word at Verified?/Release?/Finish?: the operator said it in chat, then re-run with --confirmed; checks and guardrails stay enforced
30
+ const takeYoloWord = (state: FlowState): string | null => {
31
+ if (!flag("yolo")) return null;
32
+ if (!state.yolo && !flag("confirmed")) return "yolo is the operator's word — the operator must have said it in chat, then re-run with --yolo --confirmed";
33
+ state.yolo = true;
34
+ return null;
35
+ };
36
+ const slugArg = rest.find((a) => !a.startsWith("--"));
37
+ const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord, hooks };
38
+
39
+ switch (sub) {
40
+ case "init":
41
+ return gateInit(o);
42
+
43
+ case "start":
44
+ return gateStart(o);
45
+
46
+ case "status":
47
+ return gateStatus(o);
48
+
49
+ case "reflect":
50
+ return gateReflect(o);
51
+
52
+ case "roadmap":
53
+ return gateRoadmap(o);
54
+
55
+ case "doctor":
56
+ return gateDoctor(o);
57
+
58
+ case "version":
59
+ return gateVersion(o);
60
+
61
+ case "approve":
62
+ return gateApprove(o);
63
+
64
+ case "test":
65
+ return gateTest(o);
66
+
67
+ case "verify":
68
+ return gateVerify(o);
69
+
70
+ case "check":
71
+ return gateCheck(o);
72
+
73
+ case "health":
74
+ return gateHealth(o);
75
+
76
+ case "release":
77
+ return gateRelease(o);
78
+
79
+ case "release-done":
80
+ return gateReleaseDone(o);
81
+
82
+ case "finish":
83
+ return gateFinish(o);
84
+
85
+ case "use":
86
+ return gateUse(o);
87
+
88
+ case "abort":
89
+ return gateAbort(o);
90
+
91
+ default:
92
+ return { text: `unknown subcommand "${sub}" — ${GATE_HELP}`, isError: true };
93
+ }
94
+ }
95
+ /** Records the checkpoint word a gate asked for and has not been given: the footer shows 💬 (“operator,
96
+ * your turn”, the legend in docs/playbook.md) while a session is parked on an answer. Presentation only —
97
+ * no verdict reads it — and the same gate clears it when the word arrives (or when the answer is no and the
98
+ * turn returns to the agent). */
99
+ export function markPendingAsk(root: string, state: FlowState, word: string): void {
100
+ state.pendingAsk = word;
101
+ writeState(root, state);
102
+ }
103
+
104
+ /** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
105
+ export const mainHookBody = (branch: string) =>
106
+ `branch=$(git rev-parse --abbrev-ref HEAD)\nif [ "$branch" = "${branch}" ] && [ -z "$DEV_FLOW_ALLOW_MAIN" ]; then\n echo "dev-flow: direct commits to ${branch} are forbidden — use a feature worktree and a PR" >&2\n exit 1\nfi\n`;
107
+
108
+ /** Value tokens of a multi-value flag: everything after `--name` up to the next `--flag`. */
109
+ export function flagValues(rest: string[], name: string): string[] {
110
+ const i = rest.indexOf(`--${name}`);
111
+ if (i === -1) return [];
112
+ const out: string[] = [];
113
+ for (let j = i + 1; j < rest.length && !rest[j].startsWith("--"); j++) out.push(rest[j]);
114
+ return out;
115
+ }
116
+
117
+ export async function gateInit(o: GateCtx): Promise<RunResult> {
118
+ const { root, ui, rest, flag } = o;
119
+ // a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
120
+ // only sanctioned agent path to the playbook: claiming "created" when the folder was already
121
+ // there sends the agent diffing its own config for damage that never happened (#39).
122
+ const dfExisted = existsSync(dfDir(root));
123
+ mkdirSync(dfDir(root), { recursive: true });
124
+ const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
125
+ // self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
126
+ writeFileSync(path.join(dfDir(root), ".gitignore"), "*\n!project.md\n");
127
+ const mdFile = path.join(dfDir(root), "project.md");
128
+ const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
129
+ const curBr = await currentBranch(root);
130
+ // never propose a feature branch (contains "/") as the default branch
131
+ const branch = (head.ok ? head.out.match(/refs\/remotes\/origin\/(.+)/)?.[1] : undefined) || (curBr.includes("/") ? undefined : curBr) || "main";
132
+ const det = detectProject(root, branch);
133
+ const origin = await originUrl(root);
134
+ det.partial.forge = origin ? detectForge(origin) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
135
+ const mergeEv = await mergeHistoryEvidence(root, branch); // "what do you actually do when a PR merges", read off the log
136
+ det.partial.merge = mergeEv?.note;
137
+ const tagEv = await tagPatternEvidence(root);
138
+ if (tagEv) {
139
+ det.partial.versionTag = tagEv.pattern;
140
+ det.report.push(`tags: ${tagEv.note} → versionTag = ${tagEv.pattern}`);
141
+ }
142
+ const draftFresh = buildDraft(det);
143
+ const questions = setupQuestions(det, { merge: mergeEv, tag: tagEv });
144
+ if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
145
+ // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
146
+ const ghosts = ghostFeatureDirs(root);
147
+ if (ghosts.length) {
148
+ if (!ui.hasUI) notes.push(`${ghosts.length} ghost feature dir(s) — a plan/ with no state.json, no flow owns them (${ghosts.join(", ")}); adopt one with flow start <slug> --confirmed, delete them, or run flow init interactively`);
149
+ else if (await ui.confirm("Remove ghost feature dirs?", `${ghosts.map((g) => `${g} — plan/ with no state.json`).join("\n")}\n\nNo flow owns these; their plan/*.md is not recoverable afterwards. To keep one as a new feature's draft, decline and run flow start <slug> --confirmed.`)) {
150
+ for (const g of ghosts) rmSync(path.join(root, g), { recursive: true, force: true });
151
+ notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
152
+ } else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
153
+ }
154
+ const current = existsSync(mdFile) ? readFileSync(mdFile, "utf8") : null;
155
+ /** Validate, back up what was there (the operator's rules are not regenerable), write. */
156
+ const writeMd = (text: string): { rej: RunResult } | { warn: string[] } => {
157
+ const parsed = parseProjectMd(text);
158
+ if (parsed.hard.length) return { rej: { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true } };
159
+ if (existsSync(mdFile)) copyFileSync(mdFile, `${mdFile}.bak`);
160
+ writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
161
+ return { warn: parsed.warn };
162
+ };
163
+ /** After a write: the playbook belongs in git — commit it on the operator's word, else say how. */
164
+ const afterWrite = async (w: { warn: string[] }, before: string | null, after: string, offer = false): Promise<void> => {
165
+ notes.push(`changes:\n${lineDiff(before ?? "", after)}`);
166
+ if (w.warn.length) notes.push("warnings:", ...w.warn.map((x) => ` ${x}`));
167
+ // the dialog belongs to the human-driven first init only: an agent write (--write/--answers) follows a chat
168
+ // confirmation and must not open a second question — it commits on --track
169
+ const track = flag("track") || (offer && ui.hasUI && (await ui.confirm("Commit project.md?", "The playbook belongs in git. Commit .dev-flow/project.md now (only that file, as a playbook chore)?")));
170
+ if (!track) {
171
+ notes.push(GIT_TRACK_NOTE, AGENT_MARK + "(or re-run the same call with --track on the operator's word)");
172
+ return;
173
+ }
174
+ const c = await sh(`git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(before ? "chore: update dev-flow playbook" : "chore: add dev-flow playbook")} -- .dev-flow/project.md`, root, 60_000);
175
+ notes.push(c.ok ? "project.md committed (git add -f + playbook chore)" : `commit failed — ${c.out.split("\n").find(Boolean) ?? "?"}; ${GIT_TRACK_NOTE}`);
176
+ };
177
+ const answerToks = [...flagValues(rest, "answers"), ...(flag("answers-file") ? (() => { const f = flagValues(rest, "answers-file")[0]; return f && existsSync(path.resolve(root, f)) ? readFileSync(path.resolve(root, f), "utf8").split("\n") : [`<missing answers file ${f ?? ""}>`]; })() : [])];
178
+ if (flag("answers") || flag("answers-file")) {
179
+ // the operator's answers, applied as targeted edits onto the draft (first init) or the current file —
180
+ // hand-written lines survive; the result is previewed until the operator's word anchors the write
181
+ const parsed = parseAnswers(answerToks);
182
+ if (parsed.errors.length) return { text: `answers REJECTED:\n- ${parsed.errors.join("\n- ")}`, isError: true };
183
+ if (!parsed.answers.length) return { text: "usage: flow init --answers key=value [key=value …] | --answers-file <path> (one key=value per line)", isError: true };
184
+ const base = current ?? draftFresh;
185
+ const applied = applyAnswers(base, parsed.answers);
186
+ const lint = parseProjectMd(applied.text);
187
+ if (lint.hard.length) return { text: `project.md REJECTED:\n- ${lint.hard.join("\n- ")}`, isError: true };
188
+ const preview = [`${current ? "playbook" : "draft"} with ${parsed.answers.length} answer(s):`, ...applied.changes.map((c) => ` ${c}`), "", mdDigest(applied.text)];
189
+ const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Write project.md?", preview.join("\n"))));
190
+ if (!ok) {
191
+ const open = questions.filter((x) => !parsed.answers.some(([k]) => k === x.key || (x.key === "check.<name>" && (k.startsWith("check.") || ["test", "build", "run"].includes(k)))));
192
+ return { text: [...preview, "", `changes:\n${lineDiff(base, applied.text)}`, "", "not written — present this to the operator; on their confirmation re-run the same call with --confirmed", ...(open.length ? ["still unanswered:", ...renderQuestions(open)] : [])].join("\n") };
193
+ }
194
+ const w = writeMd(applied.text);
195
+ if ("rej" in w) return w.rej;
196
+ notes.push(`project.md written with ${parsed.answers.length} answer(s)`);
197
+ await afterWrite(w, current, applied.text);
198
+ } else if (flag("write") || flag("write-file")) {
199
+ let content: string | undefined;
200
+ if (flag("write-file")) {
201
+ const f = flagValues(rest, "write-file")[0];
202
+ if (!f || !existsSync(path.resolve(root, f))) return { text: `usage: flow init --write-file <path> — ${f ? `${f} does not exist` : "no path given"}`, isError: true };
203
+ content = readFileSync(path.resolve(root, f), "utf8");
204
+ } else {
205
+ content = rest[rest.indexOf("--write") + 1];
206
+ if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>" (or --write-file <path>)', isError: true };
207
+ }
208
+ const w = writeMd(content);
209
+ if ("rej" in w) return w.rej;
210
+ notes.push("project.md written (operator-owned playbook)");
211
+ await afterWrite(w, current, content);
212
+ } else if (!current) {
213
+ // first init: never write silently. The questions come first — a dialog that offered the bare detection
214
+ // draft before them wrote a playbook with the merge style, forge and versioning still unanswered.
215
+ const brief = [
216
+ "setup — project.md not written yet; nothing is drafted to disk until the operator confirms.",
217
+ "detected:",
218
+ ...det.report.map((r) => ` ${r}`),
219
+ "questions for the operator (detected value shown; `accept` is the answer that keeps it):",
220
+ ...renderQuestions(questions),
221
+ AGENT_MARK + "ask these in chat — group the ones with an `accept` line as \"keep these?\", explain the rest in a line each. Then apply every answer in one call: flow init --answers key=value … (previews the digest and diff, writes nothing); on the operator's confirmation re-run it with --confirmed (add --track to commit the playbook). Free-text additions — checklist items, prose, flow-guard rules — go in through flow init --write-file <path> with the full file (flow init --draft prints the current draft).",
222
+ ];
223
+ let wrote = false;
224
+ if (ui.hasUI) {
225
+ const accepts = questions.filter((x) => x.accept).map((x) => x.accept!);
226
+ const withAccepts = applyAnswers(draftFresh, parseAnswers(accepts).answers).text;
227
+ const ok = await ui.confirm("Accept the detected setup?", `${mdDigest(withAccepts)}\n\nWrite this now, keeping every detected value? ${questions.length - accepts.length} question(s) have no detected answer (${questions.filter((x) => !x.accept).map((x) => x.key).join(", ")}) — decline to answer them in chat first.`);
228
+ if (ok) {
229
+ const w = writeMd(withAccepts);
230
+ if ("rej" in w) return w.rej;
231
+ wrote = true;
232
+ notes.push("wrote .dev-flow/project.md from detection with the detected values accepted — change any of them with flow init --answers key=value", ...det.report.map((r) => ` ${r}`));
233
+ const open = questions.filter((x) => !x.accept);
234
+ if (open.length) notes.push("still open (answer any time):", ...renderQuestions(open));
235
+ await afterWrite(w, null, withAccepts, true);
236
+ }
237
+ }
238
+ if (!wrote) notes.push(...brief);
239
+ } else if (flag("force")) {
240
+ // a destructive reset of the operator's own file needs their word: --confirmed for an agent, one dialog for a human
241
+ const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Overwrite project.md?", `flow init --force replaces the operator playbook with a fresh detection draft. Hand-written rules, checklist items and guidance are lost (a copy is kept as project.md.bak).`)));
242
+ if (!ok) return { text: "flow init --force overwrites the operator playbook — that needs the operator's word: re-run with --confirmed (the current file is kept as project.md.bak)", isError: true };
243
+ copyFileSync(mdFile, `${mdFile}.bak`);
244
+ writeFileSync(mdFile, draftFresh);
245
+ notes.push("project.md OVERWRITTEN (--force; previous copy kept as project.md.bak):", ...det.report.map((r) => ` ${r}`), GIT_TRACK_NOTE);
246
+ } else {
247
+ // re-init is the doctor's file-level check: findings are printed, the playbook is never regenerated —
248
+ // a draft cannot reproduce hand-written prose, items and keys. Edit the file, or flow init --write.
249
+ const loaded = loadProject(dfDir(root));
250
+ const findings = doctorFindings(root, loaded.cfg, loaded.md);
251
+ notes.push("project.md already exists — kept (edit it directly, flow init --answers key=value for one knob, --write-file to replace it, --force to redraft)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
252
+ }
253
+ const initCfg = loadProject(dfDir(root)).cfg;
254
+ if (initCfg.mainHook) {
255
+ // a hook manager (husky, lefthook…) points core.hooksPath elsewhere: git never runs .git/hooks then,
256
+ // so a hook installed there would guard nothing — print the lines for the manager's own hook instead
257
+ const hp = await sh("git config --get core.hooksPath", root, 10_000);
258
+ const hooksPath = hp.ok ? hp.out.trim() : ""; // unset exits 1, and sh() then carries the error text
259
+ const hookDir = path.join(root, ".git", "hooks");
260
+ const hook = path.join(hookDir, "pre-commit");
261
+ const body = mainHookBody(initCfg.defaultBranch);
262
+ if (hooksPath && path.resolve(root, hooksPath) !== hookDir) {
263
+ const theirs = path.join(hooksPath, "pre-commit");
264
+ const has = existsSync(path.resolve(root, theirs)) && readFileSync(path.resolve(root, theirs), "utf8").includes("DEV_FLOW_ALLOW_MAIN");
265
+ if (!has) notes.push(`core.hooksPath = ${hooksPath} — git runs hooks from there, not .git/hooks, so dev-flow installed none; to block main commits outside Pi, add to ${theirs}:\n${body}`);
266
+ } else if (existsSync(hookDir) && !existsSync(hook)) {
267
+ writeFileSync(hook, `#!/bin/sh\n# installed by dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden (override: DEV_FLOW_ALLOW_MAIN=1)\n${body}`, { mode: 0o755 });
268
+ notes.push("pre-commit hook installed (blocks commits on main)");
269
+ } else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow") && !readFileSync(hook, "utf8").includes("DEV_FLOW_ALLOW_MAIN")) {
270
+ notes.push(`existing pre-commit hook found — dev-flow did not replace it; main commits outside Pi stay unguarded until you add to .git/hooks/pre-commit:\n${body}`);
271
+ }
272
+ }
273
+ return { text: notes.join("\n") };
274
+ }
275
+
276
+ export async function gateStart(o: GateCtx): Promise<RunResult> {
277
+ const { root, sess, cfg, rest, flag, slugArg } = o;
278
+ if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --ui/--patch/--docs are operator-granted — ask the operator in chat, then add --confirmed", isError: true };
279
+ // a ghost (plan/ but no state.json — typically a spin-off someone wrote by hand) is adopted, never a dead end:
280
+ // "already exists, flow use it" sent the agent to use, which found no state, and doctor offered to delete it
281
+ const ghost = existsSync(featDir(root, slugArg)) && !existsSync(stateFile(root, slugArg)) && existsSync(path.join(featDir(root, slugArg), "plan"));
282
+ if (ghost && !flag("confirmed")) {
283
+ const files = listFiles(path.join(featDir(root, slugArg), "plan"));
284
+ return { text: `.dev-flow/${slugArg}/ is a ghost — plan/ (${files.join(", ") || "empty"}) but no state.json, so no flow owns it. Adopt it as this feature's draft plan: flow start ${slugArg} --confirmed (the operator agrees in chat), or delete the dir to start clean`, isError: true };
285
+ }
286
+ if (existsSync(featDir(root, slugArg)) && !ghost) {
287
+ // --ui on the plan-stage feature this session drives: the operator asked for mockups after the start,
288
+ // so turn the mockup gate on instead of refusing — a UI feature left at ui=false skips the mockup
289
+ // proof at approve and every (ui) checklist item (lettuce rail-ui-fixes shipped 20 ungated mockups)
290
+ const existing = readState(root, slugArg);
291
+ if (flag("ui") && existing && sess.slug === slugArg) {
292
+ if (!flag("confirmed")) return { text: "--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate; ask the operator, then re-run with --confirmed", isError: true };
293
+ if (existing.ui) return { text: `feature ${slugArg} already has the ui flag` };
294
+ if (existing.stage !== "plan") return { text: `feature ${slugArg} is at ${existing.stage} — the ui flag can be set only at plan (the mockup gate is approve's); render the screens anyway and say so in the verify report`, isError: true };
295
+ writeState(root, { ...existing, ui: true });
296
+ return { text: `ui flag set on existing feature ${slugArg} (plan stage): the approve gate now requires rendered mockups under plan/mockups/ (${cfg.mockupGlobs.join(", ")}), each embedded in plan.md, and the (ui) checklist items apply` };
297
+ }
298
+ return { text: `feature ${slugArg} already exists — flow use ${slugArg} to resume it${existing?.stage === "plan" ? `; to add the mockup gate at plan, run flow start ${slugArg} --ui --confirmed from the session bound to it` : ""}`, isError: true };
299
+ }
300
+ // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
301
+ if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
302
+ const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
303
+ // every grant start needs goes into one question: a refusal for one names the others still open, so
304
+ // the operator answers mode, mockups and merge policy in a single message
305
+ const alsoMerge = !cfg.release.merge && flagValue(rest, "merge") === null ? `\n${AGENT_MARK}the playbook also has no merge policy — put it in the same question (squash | merge | rebase | any) and pass --merge=<style> on the same re-run` : "";
306
+ if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — the operator must grant it in chat, then re-run with --confirmed${alsoMerge}`, isError: true };
307
+ // --ui adds the rendered-mockup gate to plan: worth it only when screens change, and the operator says so
308
+ if (flag("ui") && !flag("confirmed")) return { text: `--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate, so use it only when the feature changes screens; ask the operator, then re-run with --confirmed${alsoMerge}`, isError: true };
309
+ // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
310
+ const curBr = await currentBranch(root);
311
+ if (curBr !== cfg.defaultBranch && !flag("force")) return { text: `main checkout is on ${curBr}, not ${cfg.defaultBranch} — check out ${cfg.defaultBranch} first (git checkout ${cfg.defaultBranch} && git pull) or flow use an unfinished feature; --force to override`, isError: true };
312
+ // --- preflight: is this session running the current build, and is the playbook complete? ---
313
+ const notes: string[] = [];
314
+ const skew = buildSkew(root);
315
+ if (skew.line) notes.push(`warning: ${skew.line}`);
316
+ const dupStart = copyWarning();
317
+ if (dupStart) notes.push(dupStart);
318
+ if (flag("check-upstream")) {
319
+ const newest = await publishedVersion(root);
320
+ notes.push(newest ? `published dev-flow: ${newest} (this build: ${loadedVersion() ?? "?"})${loadedVersion() && newest !== loadedVersion() ? " — an update is available" : ""}` : "could not read the published dev-flow version (offline?)");
321
+ }
322
+ // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
323
+ const gaps = doctorFindings(root, cfg, loadProject(dfDir(root)).md).filter((x) => !x.startsWith("no merge policy"));
324
+ if (gaps.length) notes.push(`playbook gaps (${gaps.length}) — advisory, flow doctor reviews and routes them:\n${gaps.slice(0, 5).map((g) => ` ${g}`).join("\n")}`);
325
+ // the merge policy is the one blocking gap: it decides the shape of the default branch and nobody can
326
+ // reconstruct it afterwards. Ask once in chat (a checkpoint word like any other), write the answer, continue.
327
+ const styleArg = flagValue(rest, "merge");
328
+ const style = styleArg === null ? null : parseMergeStyle(styleArg);
329
+ if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
330
+ if (!cfg.release.merge || (style && style !== cfg.release.merge)) {
331
+ if (!style) {
332
+ const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
333
+ return {
334
+ text: needsOperator(
335
+ `how should a merged PR land on ${cfg.defaultBranch}: squash, merge (a merge commit), rebase, or any (no policy)?${ev ? ` ${ev.note}${ev.recent ? ` Detected suggestion: ${ev.recent}.` : ""}` : ""} The answer is written into the playbook once.`,
336
+ "Merge policy?",
337
+ `ask the operator — in the same message as any mode or --ui grant you propose — then re-run once with everything: flow start ${slugArg} --merge=<style> [--ui] [--patch|--docs] --confirmed`,
338
+ ),
339
+ isError: true,
340
+ };
341
+ }
342
+ if (!flag("confirmed")) return { text: `writing merge = ${style} changes the operator playbook — the operator must answer it in chat first, then re-run with --confirmed`, isError: true };
343
+ const written = await writePlaybookMergePolicy(root, style);
344
+ if ("err" in written) return { text: written.err, isError: true };
345
+ // the flow that just wrote the policy must see it: nextHint and the merge guard read this config
346
+ cfg.release.merge = style;
347
+ notes.push(written.note);
348
+ }
349
+ // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling.
350
+ // the stamp is what ran, not what the disk claims (that mismatch is the warning above).
351
+ const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), loadedVersion() ?? undefined);
352
+ const planDir = path.join(featDir(root, slugArg), "plan");
353
+ if (ghost) notes.push(`adopted ghost .dev-flow/${slugArg}/ — its plan/ (${listFiles(planDir).join(", ") || "empty"}) is this feature's draft`);
354
+ mkdirSync(planDir, { recursive: true });
355
+ // a roadmap item stamped for this slug carries its brief into the plan: the spin-off's context outlives the session that split it
356
+ const picked = roadmapBriefFor(readRoadmap(root), slugArg);
357
+ if (picked) {
358
+ const planMd = path.join(planDir, "plan.md");
359
+ const carried = `> Carried over from the roadmap: ${picked.item}${picked.brief ? `\n>\n${picked.brief.split("\n").map((l) => `> ${l}`.trimEnd()).join("\n")}` : ""}\n`;
360
+ if (!existsSync(planMd)) {
361
+ writeFileSync(planMd, `# ${slugArg} — plan (draft)\n\n${carried}`);
362
+ notes.push(`roadmap item "${picked.item}" seeded plan/plan.md${picked.brief ? " with its brief" : ""} — a draft: plan it out and approve as usual`);
363
+ } else notes.push(`roadmap item "${picked.item}"${picked.brief ? ` — brief:\n${picked.brief}` : ""}`);
364
+ }
365
+ writeState(root, state);
366
+ sess.bind(slugArg);
367
+ sess.rename(slugArg);
368
+ return { text: `feature ${slugArg} started at stage plan (ui=${state.ui}${state.patch ? ", patch" : state.docs ? ", docs" : ""}${state.flowVersion ? `, dev-flow ${state.flowVersion}` : ""}); session renamed to ${slugArg}.${notes.length ? `\n${notes.join("\n")}` : ""}\n${AGENT_MARK}next: ${nextHint(state, cfg)}` };
369
+ }
370
+
371
+ export async function gateApprove(o: GateCtx): Promise<RunResult> {
372
+ const { root, ui, sess, cfg, flag, slugArg } = o;
373
+ const { state, err } = needState(root, sess, slugArg);
374
+ if (err) return err;
375
+ const planDir = path.join(featDir(root, state!.slug), "plan");
376
+ // the embed proofs read the plan document itself: a render that exists on disk but is not
377
+ // embedded in plan.md is one the operator would never be shown
378
+ const planMd = path.join(planDir, "plan.md");
379
+ const planFiles = listFiles(planDir);
380
+ const mockupHtml = planFiles.filter((f) => /^mockups\/.+\.html?$/i.test(f)).map((f) => ({ file: f, html: readFileSync(path.join(planDir, f), "utf8") }));
381
+ const errs = approveGate(state!, cfg, planFiles, existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined, foreignWorktreeLinks(dfDir(root), state!.slug, mockupHtml));
382
+ if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
383
+ const planItems = applicableItems(cfg, state!, "plan");
384
+ let audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
385
+ const askPending = !flag("confirmed");
386
+ if (askPending) {
387
+ markPendingAsk(root, state!, "Approve?");
388
+ if (!ui.hasUI) {
389
+ return { text: needsOperator("the plan is waiting for your approval", "Approve?", "re-run with --confirmed once the operator answered in chat"), isError: true };
390
+ }
391
+ const ok = await ui.confirm("Approve plan", `Approve ${state!.slug}${state!.ui ? " (UI)" : ""}${state!.patch ? " (patch)" : state!.docs ? " (docs)" : ""}? Creates the worktree.${flag("yolo") ? " YOLO: all later gate questions (Verified?/Release?/Finish?) are pre-confirmed — checks and guardrails stay in place." : ""}`);
392
+ if (!ok) {
393
+ delete state!.pendingAsk;
394
+ writeState(root, state!);
395
+ return { text: "approval declined — keep iterating on the plan" };
396
+ }
397
+ audit = " (confirmed in dialog)";
398
+ }
399
+ // the operator's word at Approve?, recorded only once given: every later gate question is pre-confirmed; checks and guardrails stay
400
+ if (flag("yolo")) state!.yolo = true;
401
+ if (planItems.length) state!.confirmations = { ...state!.confirmations, plan: { hash: checklistHash(planItems), at: now() } };
402
+ const branch = subst(cfg.branchPattern, state!.slug);
403
+ const wtRel = subst(cfg.worktreeDir, state!.slug);
404
+ const wt = path.resolve(root, wtRel);
405
+ let setupNote = "";
406
+ if (!existsSync(wt)) {
407
+ // branch discipline: features branch off the default branch — never from a stale checkout HEAD
408
+ const base = (await sh(`git rev-parse --verify -q origin/${cfg.defaultBranch}`, root)).ok ? `origin/${cfg.defaultBranch}` : cfg.defaultBranch;
409
+ const res = await sh(`git worktree add ${sq(wt)} -b ${branch} ${base}`, root);
410
+ if (!res.ok) return { text: `worktree creation failed:\n${res.out}`, isError: true };
411
+ }
412
+ // setup is worktree work of a normal feature: a docs flow runs no project command at all (#49),
413
+ // and a worktree left behind by a setup that never succeeded must be retried — "fix it and run
414
+ // approve again" was a silent no-op on the reused directory (#49). setup is expected to be idempotent.
415
+ const setupCmd = state!.docs ? undefined : cfg.commands.setup;
416
+ if (setupCmd && !state!.setupAt) {
417
+ const s = await sh(setupCmd, wt);
418
+ if (!s.ok) return { text: `setup failed in ${wtRel} — fix commands.setup, then run flow approve again (the worktree is kept and setup retried):\n${tail(s.out)}`, isError: true };
419
+ state!.setupAt = now();
420
+ setupNote = `\nsetup ran in the worktree (${setupCmd}).`;
421
+ } else if (state!.docs && cfg.commands.setup) {
422
+ setupNote = "\nsetup skipped (docs mode — no project commands run).";
423
+ }
424
+ state!.branch = branch;
425
+ state!.worktree = wtRel;
426
+ state!.stage = "implement";
427
+ state!.approvals.plan = now();
428
+ delete state!.pendingAsk;
429
+ writeState(root, state!);
430
+ return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${setupNote}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
431
+ }
432
+
433
+ export async function gateStatus(o: GateCtx): Promise<RunResult> {
434
+ const { root, sess, cfg, flag, slugArg } = o;
435
+ const df = dfDir(root);
436
+ const { md } = loadProject(df);
437
+ // cheap fs probes only (no git subprocesses) — status is a glance, `flow doctor` is the full list
438
+ const findings = md ? doctorFindings(root, cfg, md) : [];
439
+ // a session running an older build than the disk ships is the one thing a glance must say: every
440
+ // gate proof printed since the drift began belongs to the older code.
441
+ const skew = buildSkew(root);
442
+ // hints read as something the operator could say; the agent's command for each rides an agent-only line
443
+ const warn = [
444
+ ...(findings.length ? [`⚠ ${findings.length} playbook finding(s) — say "check the playbook" to go through them`, `${AGENT_MARK}playbook findings: run flow doctor`] : []),
445
+ ...(skew.line ? [`⚠ ${skew.line}`] : []),
446
+ ...(copyWarning() ? [copyWarning()!] : []),
447
+ ];
448
+ // the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
449
+ const rmap = roadmapOpenCount(readRoadmap(root));
450
+ const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — say "show the roadmap"`, `${AGENT_MARK}roadmap: flow roadmap lists them`] : [];
451
+ const slugs = slugArg ? [slugArg] : unfinishedStates(root).map((s) => s.slug);
452
+ const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
453
+ if (flag("json")) {
454
+ const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
455
+ return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
456
+ }
457
+ if (!slugs.length) return { text: ["no features in flight — describe what you want built to start one", `${AGENT_MARK}start one: flow start <slug> [--ui] [--patch|--docs --confirmed]`, ...warn, ...rmapLine].join("\n") };
458
+ // one readable row per feature for the operator; the identifiers an agent needs stay on agent-only lines
459
+ const lines = slugs.flatMap((s) => {
460
+ const st = readState(root, s);
461
+ if (!st) return [];
462
+ const checks = Object.entries(st.checks).map(([k, v]) => `${k} ${v.ok ? "✓" : "✗"}`).join(" ");
463
+ const tags = [st.ui ? "ui" : "", st.patch ? "patch" : st.docs ? "docs" : "", st.yolo ? "yolo" : "", st.noVersion ? "no-version" : ""].filter(Boolean);
464
+ const row = [
465
+ `${STAGE_EMOJI[st.stage]} ${st.stage}`,
466
+ ...(tags.length ? [tags.join(", ")] : []),
467
+ ...(checks ? [`checks ${checks}`] : []),
468
+ ...(st.confirmations?.implement ? ["checklist ✓"] : []),
469
+ ...(st.pendingAsk ? [`💬 waiting on you: ${st.pendingAsk}`] : []),
470
+ ];
471
+ return [
472
+ `${s === cur ? "→" : "-"} **${s}**${s === cur ? " (this session)" : ""} — ${row.join(" · ")}`,
473
+ `${AGENT_MARK}${s}: stage=${st.stage} branch=${st.branch || "-"} worktree=${st.worktree || "-"}${st.flowVersion ? ` flow=${st.flowVersion}` : ""} approvals: ${Object.keys(st.approvals).join(", ") || "none"}`,
474
+ `${AGENT_MARK}${s} next: ${nextHint(st, cfg)}`,
475
+ ];
476
+ });
477
+ // who holds the dev stack: the one thing two parallel flows on one machine must not guess
478
+ for (const [k, v] of Object.entries(readDevPorts(root))) lines.push(`dev ${k === "default" ? "stack" : `port ${k}`} → ${v.slug} @ ${v.head.slice(0, 7)}, deployed ${ago(v.at)}`);
479
+ if (warn.length) lines.push(...warn);
480
+ // which identity this session's state is keyed by: a claim fight is undiagnosable when the key
481
+ // could be a session id or a shared directory and the output does not say which
482
+ lines.push(`${AGENT_MARK}session: ${sess.key}${sess.key.startsWith("cwd:") ? " — no session id from pi, so every pi session in this directory shares one dev-flow binding (pass flow use <slug> in each)" : ""}`);
483
+ const refl = readReflections(root);
484
+ if (refl.length) lines.push(`↻ ${refl.length} reflection(s) open — say "review the reflections" to go through them`, `${AGENT_MARK}reflections: run flow doctor (it reviews and routes them)`);
485
+ lines.push(...rmapLine);
486
+ return { text: lines.join("\n") || "no features" };
487
+ }
488
+
489
+ export async function gateReflect(o: GateCtx): Promise<RunResult> {
490
+ const { root, sess, rest, flag } = o;
491
+ // gate flags belong to the state verbs — pasted into the note they read as part of the operator's
492
+ // own sentence in reflections.md (#43). --plugin/--playbook/--both are reflect's own: they state
493
+ // the filing instead of leaving it to a keyword guess.
494
+ const words = rest.filter((a) => !a.startsWith("--"));
495
+ const forced: ReflectTarget | null = flag("plugin") ? "plugin" : flag("code") ? "code" : flag("playbook") || flag("docs") ? "playbook" : null;
496
+ // single words are verbs (roadmap-style); a note merely starting with one stays a note
497
+ if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
498
+ if (words.length === 1 && words[0] === "list") return await reflectList(root);
499
+ if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
500
+ if (words[0] === "done") return reflectDoneNote(root, sess, words.slice(1));
501
+ if (words.length) return await reflectNote(root, sess, words, forced);
502
+ const self = pluginVersion(import.meta.dirname);
503
+ const upstream = await pluginUpstream(root);
504
+ const refl = readReflections(root);
505
+ const fold = await foldView(root, refl);
506
+ const nudges = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: !sess.slug });
507
+ return {
508
+ text: reflectProtocol(refl, isSelfRepo(root), {
509
+ version: self.version,
510
+ upstream,
511
+ bound: !!sess.slug,
512
+ fix: nudges.fix,
513
+ tidy: nudges.tidy,
514
+ ghFold: fold.state === "ok" && fold.open ? { repo: fold.slug, open: fold.open, similar: fold.result.similar.length } : undefined,
515
+ }).join("\n"),
516
+ };
517
+ }
518
+
519
+ export async function gateRoadmap(o: GateCtx): Promise<RunResult> {
520
+ const { root, sess, rest } = o;
521
+ // the backlog is advisory — no state, no gating; direct file edits stay allowed like reflections.md
522
+ const words = rest.filter((a) => !a.startsWith("--")); // gate flags are not backlog prose (#43 applies here too)
523
+ const [verb = "list", ...args] = words;
524
+ const text = readRoadmap(root);
525
+ const open = roadmapOpenCount(text);
526
+ const done = doneItemCount(text);
527
+ const save = (next: string) => writeFileSync(roadmapFile(root), next); // .dev-flow/ existence is runFlow's precondition
528
+ const idx = Number(args[0]);
529
+ const validIdx = Number.isInteger(idx) && idx >= 1 && idx <= open;
530
+ switch (verb) {
531
+ case "list": {
532
+ if (!open) return { text: done ? `roadmap: nothing open (${done} done — flow roadmap tidy drops them)` : "roadmap: empty — flow roadmap add \"<future feature>\"" };
533
+ return { text: [`roadmap — ${open} open (${done} done):`, ...openChecklistItems(text).map((l, i) => ` ${i + 1}. ${l.slice(6)}`)].join("\n") };
534
+ }
535
+ case "add": {
536
+ if (!args.length) return { text: 'usage: flow roadmap add "<future feature>" [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]', isError: true };
537
+ // a spin-off: --slug stamps it like pick (flow start finds it), the brief carries what was worked
538
+ // out in chat into the new feature's plan, and a bound session records where it was split from
539
+ const slug = flagValue(rest, "slug");
540
+ if (slug !== null && !validSlug(slug)) return { text: `--slug=${slug} is not a slug (lowercase, dashes)`, isError: true };
541
+ const briefFile = flagValue(rest, "brief-file");
542
+ if (briefFile !== null && !existsSync(path.resolve(root, briefFile))) return { text: `--brief-file=${briefFile} does not exist`, isError: true };
543
+ const brief = briefFile !== null ? readFileSync(path.resolve(root, briefFile), "utf8") : (flagValue(rest, "brief") ?? "");
544
+ const item = [args.join(" "), sess.slug && sess.slug !== slug ? `— split from ${sess.slug}` : "", slug ? `(${slug})` : ""].filter(Boolean).join(" ");
545
+ save(appendRoadmapItem(text, item, brief));
546
+ return { text: `roadmap: added — ${open + 1} open${slug ? `; stamped for ${slug}${brief.trim() ? " with a brief" : ""} — flow start ${slug} seeds its plan from it${sess.slug ? ` (after ${sess.slug} ships)` : ""}` : ""}` };
547
+ }
548
+ case "pick": {
549
+ const slug = args[1] ?? "";
550
+ if (!validIdx) return { text: `pick: open item 1–${open} required — flow roadmap lists them`, isError: true };
551
+ if (!slug || !validSlug(slug)) return { text: `usage: flow roadmap pick <n> <slug> — the slug flow start will use (lowercase, dashes)`, isError: true };
552
+ save(roadmapPick(text, idx, slug)!);
553
+ return { text: `roadmap: item ${idx} picked for ${slug} — now: flow start ${slug} (flow finish checks the item off when it ships)` };
554
+ }
555
+ case "done": {
556
+ if (!validIdx) return { text: `done: open item 1–${open} required — flow roadmap lists them`, isError: true };
557
+ // stamped with date + bound slug, so history says what shipped it
558
+ save(roadmapDone(text, idx, [new Date().toISOString().slice(0, 10), sess.slug].filter(Boolean).join(" "))!);
559
+ return { text: `roadmap: item ${idx} marked done (${open - 1} open)` };
560
+ }
561
+ case "tidy": {
562
+ if (!done) return { text: `roadmap: nothing to tidy (${open} open, 0 done)` };
563
+ save(roadmapTidy(text));
564
+ return { text: `roadmap: dropped ${done} done item(s) — ${open} open` };
565
+ }
566
+ default:
567
+ return { text: "usage: flow roadmap [list|add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy]", isError: true };
568
+ }
569
+ }
570
+
571
+ export async function gateDoctor(o: GateCtx): Promise<RunResult> {
572
+ const { root, rest } = o;
573
+ // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
574
+ const df = dfDir(root);
575
+ const loaded = loadProject(df);
576
+ const findings = doctorFindings(root, loaded.cfg, loaded.md);
577
+ findings.push(...(await gitConsistency(root, loaded.cfg)));
578
+ const refl = readReflections(root);
579
+ const fold = await foldView(root, refl);
580
+ if (refl.length) {
581
+ findings.push(`reflection review — ${refl.length} open item(s); doctor never implements: investigate each, present the fix, the operator confirms, then the routed flow implements it:`);
582
+ // labelled from the heading each item sits under — the file is the record, re-guessing from the
583
+ // note text made doctor's table disagree with where the note was actually filed
584
+ reflectionRoutes(refl, isSelfRepo(root)).forEach((r, i) => {
585
+ const link = fold.state === "ok" ? fold.result.linked.find((l) => l.item === i) : undefined;
586
+ findings.push(` [${r.sections.join("+")}] ${r.text}${link ? linkedTag(link.issue) : ""}\n → ${r.route}${link ? ` — already upstream (gh#${link.issue}); check off with — filed: gh#${link.issue} once it lands` : ""}`);
587
+ });
588
+ }
589
+ findings.push(...foldRows(fold, isSelfRepo(root)));
590
+ const reflText = readReflectionsText(root);
591
+ const unfiled = reflectUnfiledCount(reflText);
592
+ if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## code — flow reflect list shows them, flow reflect move <n> --playbook|--code files them`);
593
+ findings.push(...legacyPluginRows(reflText, isSelfRepo(root)).map((r) => ` ${r}`));
594
+ const nudges = reflectionNudges(reflText, now().slice(0, 10), { between: !o.sess.slug });
595
+ if (nudges.fix) findings.push(nudges.fix);
596
+ if (nudges.tidy) findings.push(nudges.tidy);
597
+ if (!rest.length) return { text: findings.length ? `doctor: ${findings.length} finding(s)\n${findings.map((f) => ` ${f}`).join("\n")}` : "doctor: no findings — playbook, flow state and git layout are consistent" };
598
+ // flow doctor <note>: a fresh observation gets an investigation brief and a fix route
599
+ return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
600
+ }
601
+
602
+ /** What a gate handler needs from the runFlow preamble. */
603
+ export interface GateCtx {
604
+ root: string;
605
+ ui: Ui;
606
+ sess: Session;
607
+ cfg: Config;
608
+ rest: string[];
609
+ flag: (name: string) => boolean;
610
+ slugArg?: string;
611
+ takeYoloWord: (state: FlowState) => string | null;
612
+ hooks: FlowHooks;
613
+ }
614
+
615
+ export async function gateVersion(o: GateCtx): Promise<RunResult> {
616
+ const { root, flag } = o;
617
+ // the plugin's own version — separate from the project's versioning.file version the release gates use
618
+ const { disk: self, behind } = buildSkew(root);
619
+ const head = self.version ? `dev-flow ${self.version} (pi-dev-flow at ${self.dir})` : `dev-flow version unknown — no pi-dev-flow package.json above ${self.dir}`;
620
+ // in the dev-flow repo head names the checkout, so name where the stale code actually lives
621
+ const from = SELF_BUILD.dir !== self.dir ? ` (from ${SELF_BUILD.dir})` : "";
622
+ const dupNote = copyWarning();
623
+ // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
624
+ if (flag("check-upstream")) {
625
+ const newest = await publishedVersion(root);
626
+ return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
627
+ }
628
+ return { text: `${behind ? `${head} — but this session runs ${behind}${from}; /reload to run ${self.version} \u2014 in a shared-process host (pi-web) reload cannot swap loaded code: only a host restart does` : head}${dupNote ? `\n${dupNote}` : ""}` };
629
+ }
630
+
631
+ export async function gateTest(o: GateCtx): Promise<RunResult> {
632
+ const { root, sess, cfg, slugArg } = o;
633
+ const { state, err } = needState(root, sess, slugArg);
634
+ if (err) return err;
635
+ if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
636
+ const res = await sh(cfg.commands.test, gateCwd(root, state!), undefined, featureEnv(root, state!));
637
+ state!.checks.test = { ok: res.ok, at: now() };
638
+ await stampChecks(root, state!, ["test"]);
639
+ writeState(root, state!);
640
+ return { text: `test: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.test})\n${tail(res.out)}` };
641
+ }
642
+
643
+ export async function gateCheck(o: GateCtx): Promise<RunResult> {
644
+ const { root, sess, cfg, slugArg } = o;
645
+ const { state, err } = needState(root, sess, slugArg);
646
+ if (err) return err;
647
+ // a docs flow runs no project command anywhere else — pendingChecks, verifyGate and releaseGate all skip
648
+ // it — so running tier-1 here only produced a FAIL that read like a broken deploy in a checkout that
649
+ // never built the binary (#96)
650
+ // shortcut: --docs is the operator's word, nothing checks the changeset is docs-only, so a mislabelled
651
+ // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
652
+ if (state!.docs) return { text: "docs mode: project commands skipped — a docs flow runs no tier-1 checks (CI on the tag and the artifact proof still do)" };
653
+ if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
654
+ const ran = await runChecks(root, state!, cfg, cfg.checkList);
655
+ return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
656
+ }
657
+
658
+ export async function gateHealth(o: GateCtx): Promise<RunResult> {
659
+ const { root, sess, cfg, slugArg } = o;
660
+ const { state, err } = needState(root, sess, slugArg);
661
+ if (err) return err;
662
+ // commands.health and a flow-check named health are the same probe (healthProbe reads both)
663
+ const probe = healthProbe(cfg);
664
+ if (!probe) return { text: "no health check configured — add `health = <command>` (or a flow-check health block) under ## implement in .dev-flow/project.md", isError: true };
665
+ const res = await probeHealth(root, state!, cfg, probe);
666
+ if ("seedFail" in res) return res.seedFail;
667
+ return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${probe}${triedNote(res.attempts)})\n${tail(res.out)}` };
668
+ }
669
+
670
+ export async function gateUse(o: GateCtx): Promise<RunResult> {
671
+ const { root, sess, slugArg } = o;
672
+ if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
673
+ const st = readState(root, slugArg);
674
+ if (!st) {
675
+ const ghost = existsSync(path.join(featDir(root, slugArg), "plan"));
676
+ return { text: ghost ? `.dev-flow/${slugArg}/ is a ghost — plan/ but no state.json, so there is nothing to resume: flow start ${slugArg} --confirmed adopts its plan as a new feature` : `no unfinished feature ${slugArg}`, isError: true };
677
+ }
678
+ const prior = readClaim(root, slugArg);
679
+ const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
680
+ sess.bind(slugArg);
681
+ sess.rename(slugArg);
682
+ // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
683
+ // must not inherit a 💬 for a question it never posed
684
+ if (st.pendingAsk) {
685
+ delete st.pendingAsk;
686
+ writeState(root, st);
687
+ }
688
+ return { text: `this session is now bound to ${slugArg} (stage ${st.stage})${st.worktree ? ` — work in its worktree: ${st.worktree} (branch ${st.branch})` : ""}; session renamed to ${slugArg}${takeover}` };
689
+ }
690
+
691
+ export async function gateAbort(o: GateCtx): Promise<RunResult> {
692
+ const { root, ui, sess, flag, slugArg } = o;
693
+ // Unbinds the session only; state and worktree stay for manual recovery.
694
+ const target = slugArg ?? sess.slug;
695
+ if (!target) return { text: "nothing bound — pass a slug", isError: true };
696
+ const st = readState(root, target);
697
+ // a live claim locks the whole feature, not only its gates: aborting it out from under the session
698
+ // that works it erases the plan that session is still writing (same rule needState applies)
699
+ const claim = readClaim(root, target);
700
+ if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (pid ${claim!.pid}) — flow use ${target} takes it over explicitly`, isError: true };
701
+ if (st && !st.worktree) {
702
+ // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
703
+ // as a ghost the doctor flags (a plan/ whose state.json is gone). A written plan is the
704
+ // operator's work too — it is not dropped without their word.
705
+ const written = listFiles(path.join(featDir(root, target), "plan"));
706
+ if (written.length && !flag("confirmed")) {
707
+ const ok = ui.hasUI && (await ui.confirm("Drop plan?", `Abort ${target}? Its plan/ (${written.join(", ")}) is deleted for good.`));
708
+ if (!ok) return { text: needsOperator(`aborting ${target} deletes its written plan (${written.join(", ")})`, "Drop plan?", "ask the operator, then re-run with --confirmed"), isError: true };
709
+ }
710
+ if (sess.slug === target) sess.bind(null);
711
+ rmSync(featDir(root, target), { recursive: true, force: true });
712
+ return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
713
+ }
714
+ if (sess.slug === target) sess.bind(null);
715
+ // the scratch dir is the bound session's working junk — it does not outlive the binding
716
+ rmSync(featureTmpDir(dfDir(root), target), { recursive: true, force: true });
717
+ if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
718
+ return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
719
+ }