pi-dev-flow 0.64.1 → 0.64.3

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.
@@ -766,934 +766,1017 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
766
766
  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 };
767
767
  const cfg = loadProject(dfDir(root)).cfg;
768
768
  const flag = (name: string) => rest.includes(`--${name}`);
769
+ // the yolo word at Verified?/Release?/Finish?: the operator said it in chat, then re-run with --confirmed; checks and guardrails stay enforced
770
+ const takeYoloWord = (state: FlowState): string | null => {
771
+ if (!flag("yolo")) return null;
772
+ 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";
773
+ state.yolo = true;
774
+ return null;
775
+ };
769
776
  const slugArg = rest.find((a) => !a.startsWith("--"));
777
+ const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord };
770
778
 
771
779
  switch (sub) {
772
- case "init": {
773
- // a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
774
- // only sanctioned agent path to the playbook: claiming "created" when the folder was already
775
- // there sends the agent diffing its own config for damage that never happened (#39).
776
- const dfExisted = existsSync(dfDir(root));
777
- mkdirSync(dfDir(root), { recursive: true });
778
- const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
779
- // self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
780
- writeFileSync(path.join(dfDir(root), ".gitignore"), "*\n!project.md\n");
781
- rmSync(path.join(dfDir(root), ".current"), { force: true }); // migrate away the legacy repo-global pointer
782
- const mdFile = path.join(dfDir(root), "project.md");
783
- const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
784
- const curBr = await currentBranch(root);
785
- // never propose a feature branch (contains "/") as the default branch
786
- const branch = (head.ok ? head.out.match(/refs\/remotes\/origin\/(.+)/)?.[1] : undefined) || (curBr.includes("/") ? undefined : curBr) || "main";
787
- const det = detectProject(root, branch);
788
- const origin = await sh("git remote get-url origin", root);
789
- det.partial.forge = origin.ok && origin.out.trim() ? detectForge(origin.out) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
790
- det.partial.merge = (await mergeHistoryEvidence(root, branch))?.note; // "what do you actually do when a PR merges", read off the log
791
- const loaded = loadProject(dfDir(root));
792
- const draftFresh = buildDraft(det);
793
- const draftRefresh = buildDraft(det, loaded.cfg);
794
- const editHint = "to change anything: edit .dev-flow/project.md directly (flow init = doctor revalidates), or from an agent session: flow init --draft → discuss → --write";
795
- if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
796
- // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
797
- const ghosts = ghostFeatureDirs(root);
798
- if (ghosts.length) {
799
- if (!ui.hasUI) notes.push(`${ghosts.length} ghost feature dir(s) — a plan/ with no state.json, no flow owns them (${ghosts.join(", ")}); delete them or run flow init interactively`);
800
- 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.`)) {
801
- for (const g of ghosts) rmSync(path.join(root, g), { recursive: true, force: true });
802
- notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
803
- } else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
804
- }
805
- const writeMd = (text: string): RunResult | null => {
806
- const parsed = parseProjectMd(text);
807
- if (parsed.hard.length) return { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true };
808
- // the operator's rules are not regenerable — keep what was there before any overwrite
809
- if (existsSync(mdFile)) copyFileSync(mdFile, `${mdFile}.bak`);
810
- writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
811
- return null;
812
- };
813
- if (flag("write")) {
814
- const content = rest[rest.indexOf("--write") + 1];
815
- if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>"', isError: true };
816
- const parsed = parseProjectMd(content);
817
- const rej = writeMd(content);
818
- if (rej) return rej;
819
- notes.push("project.md written (operator-owned playbook)", GIT_TRACK_NOTE);
820
- if (parsed.warn.length) notes.push("warnings:", ...parsed.warn.map((w) => ` ${w}`));
821
- } else if (!existsSync(mdFile)) {
822
- // first init: never write silently. The setup brief lists what detection could not decide;
823
- // the agent relays the questions to the operator and applies the answers via flow init --write
824
- // (validated) after presenting the digest; an interactive init may confirm the draft right here.
825
- const brief = [
826
- "setup — project.md not written yet; nothing is drafted to disk until the operator confirms.",
827
- ...det.report.map((r) => ` ${r}`),
828
- "questions for the operator (one per unclear knob, with the detected default):",
829
- ...setupQuestions(det).map((line, i) => ` ${i + 1}. ${line}`),
830
- "agent: ask these in chat, fill the draft (flow init --draft), then apply with flow init --write \"<content>\" (hard-validated) — present the digest and get the operator's confirmation before writing.",
831
- GIT_TRACK_NOTE,
832
- ];
833
- if (ui.hasUI) {
834
- const ok = await ui.confirm("Write project.md draft?", `${mdDigest(draftFresh)}\n\nWrite this detection draft now? Declining leaves the setup questions open for chat clarification.`);
835
- if (ok) {
836
- const rej = writeMd(draftFresh);
837
- if (rej) return rej;
838
- notes.push("wrote .dev-flow/project.md from detection — review it and adjust as needed", GIT_TRACK_NOTE);
839
- } else notes.push("draft not written — answer the setup questions, then flow init --write");
840
- }
841
- notes.push(...brief);
842
- } else if (flag("force")) {
843
- // a destructive reset of the operator's own file needs their word: --confirmed for an agent, one dialog for a human
844
- 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).`)));
845
- 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 };
846
- copyFileSync(mdFile, `${mdFile}.bak`);
847
- writeFileSync(mdFile, draftFresh);
848
- notes.push("project.md OVERWRITTEN (--force; previous copy kept as project.md.bak):", ...det.report.map((r) => ` ${r}`), GIT_TRACK_NOTE);
849
- } else if (!ui.hasUI) {
850
- // the CI/agent path: the doctor's findings have to be printed, not just promised
851
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
852
- notes.push("project.md already exists — kept (flow init --force to overwrite, --write to edit)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
853
- } else if (existsSync(mdFile)) {
854
- // doctor mode: cheap consistency probes only — never runs project commands
855
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
856
- findings.push(...(await gitConsistency(root, loaded.cfg)));
857
- // a repo that never said how a PR merges gets the evidence next to the finding, so the answer is a choice and not a guess
858
- if (!loaded.cfg.release.merge) {
859
- const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
860
- if (ev?.recent) findings.push(`${ev.note} — write it into the playbook: merge = ${ev.recent} under ## release (or let the next flow start ask and write it)`);
861
- }
862
- for (const it of readReflections(root)) findings.push(`open reflection [${it.section}]: ${it.line.slice(6)}`);
863
- if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
864
- else {
865
- // a refresh is regenerated from detection + config: lines it cannot reproduce are
866
- // hand-written (prose, checklist items, hand-set keys) and would vanish silently.
867
- const dropped = droppableLines(readFileSync(mdFile, "utf8"), draftRefresh);
868
- let edited: string | undefined;
869
- if (dropped.length)
870
- notes.push(`doctor: refresh refused — a regenerated draft would drop ${dropped.length} hand-written line(s):`, ...dropped.slice(0, 8).map((l) => ` ${l}`), ...(dropped.length > 8 ? [` …(${dropped.length - 8} more)`] : []));
871
- else
872
- edited = ui.editor
873
- ? await ui.editor(`flow init — doctor: ${findings.length} finding(s) — edit & save to apply, Esc skips`, draftRefresh)
874
- : (await ui.confirm(`flow init — doctor: ${findings.length} finding(s)`, `${findings.join("\n")}
780
+ case "init":
781
+ return gateInit(o);
875
782
 
876
- Write refreshed project.md? Your file; cancel writes nothing.
877
- ${mdDigest(draftRefresh)}`))
878
- ? draftRefresh
879
- : undefined;
880
- if (edited === undefined) notes.push(dropped.length ? "findings — fix them by editing the file:" : "declined — project.md unchanged", ...findings.map((f) => ` ${f}`));
881
- else {
882
- const rej = writeMd(edited);
883
- if (rej) return rej;
884
- notes.push("project.md refreshed — findings addressed:", ...findings.map((f) => ` ${f}`), editHint);
885
- }
886
- }
783
+ case "start":
784
+ return gateStart(o);
785
+
786
+ case "status":
787
+ return gateStatus(o);
788
+
789
+ case "reflect":
790
+ return gateReflect(o);
791
+
792
+ case "roadmap":
793
+ return gateRoadmap(o);
794
+
795
+ case "doctor":
796
+ return gateDoctor(o);
797
+
798
+ case "version":
799
+ return gateVersion(o);
800
+
801
+ case "approve":
802
+ return gateApprove(o);
803
+
804
+ case "test":
805
+ return gateTest(o);
806
+
807
+ case "verify":
808
+ return gateVerify(o);
809
+
810
+ case "check":
811
+ return gateCheck(o);
812
+
813
+ case "health":
814
+ return gateHealth(o);
815
+
816
+ case "release":
817
+ return gateRelease(o);
818
+
819
+ case "release-done":
820
+ return gateReleaseDone(o);
821
+
822
+ case "finish":
823
+ return gateFinish(o);
824
+
825
+ case "use":
826
+ return gateUse(o);
827
+
828
+ case "abort":
829
+ return gateAbort(o);
830
+
831
+ default:
832
+ return { text: `unknown subcommand "${sub}" — ${GATE_HELP}`, isError: true };
833
+ }
834
+ }
835
+ async function gateVerify(o: GateCtx): Promise<RunResult> {
836
+ const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
837
+ const { state, err } = needState(root, sess, slugArg);
838
+ if (err) return err;
839
+ const items = applicableItems(cfg, state!, "implement");
840
+ const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
841
+ const branchLine = describeBranchState(branch, cfg.defaultBranch);
842
+ // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
843
+ // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
844
+ // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
845
+ const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
846
+ if (staleAtGate.length) writeState(root, state!);
847
+ const pending = pendingChecks(state!, cfg);
848
+ const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
849
+ if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
850
+ // tier-1 gate first (tier-2 confirmation is recorded by this very command, so it is excluded here)
851
+ const preGate = verifyGate({ ...state!, confirmations: { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } } }, cfg, branch);
852
+ if (preGate.length) return { text: `verify gate FAILED:\n- ${preGate.join("\n- ")}\n${branchLine}`, isError: true };
853
+ // commands that take minutes and touch live services must say so (#38): a terse gate let the
854
+ // agent tell the operator the dev deploy had never run, right after it recreated a container.
855
+ const did: string[] = [];
856
+ if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
857
+ if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
858
+ if (state!.docs) {
859
+ // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
860
+ did.push("docs mode: project commands skipped (build/dev/health)");
861
+ } else {
862
+ if (cfg.commands.build) {
863
+ const res = await sh(cfg.commands.build, gateCwd(root, state!));
864
+ state!.checks.build = { ok: res.ok, at: now() };
865
+ writeState(root, state!);
866
+ if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
867
+ did.push(`build ran (${cfg.commands.build})`);
868
+ }
869
+ // deploy to dev before asking — the operator reviews the running dev app, not a promise
870
+ if (cfg.commands.dev) {
871
+ const res = await sh(cfg.commands.dev, gateCwd(root, state!));
872
+ state!.checks.dev = { ok: res.ok, at: now() };
873
+ writeState(root, state!);
874
+ if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
875
+ did.push(`dev ran (${cfg.commands.dev})`);
876
+ // the deploy is what must be proven, not just run: a container that came back unhealthy, or
877
+ // still serves the previous build, must not pass on a health PASS recorded before it was
878
+ // recreated. What "the expected version" means is the project's business — the probe runs in
879
+ // the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
880
+ const probe = healthProbe(cfg);
881
+ if (!probe) did.push("health: none configured");
882
+ else {
883
+ const seedFail = await seedStep(root, state!, cfg);
884
+ if (seedFail) return seedFail;
885
+ const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
886
+ state!.checks.health = { ok: probed.ok, at: now() };
887
+ await stampChecks(root, state!, ["health"]);
888
+ writeState(root, state!);
889
+ // a probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42)
890
+ const tried = probed.attempts > 1 ? `, ${probed.attempts} attempts` : "";
891
+ 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 };
892
+ did.push(`health: PASS (${probe}${tried})`);
887
893
  }
888
- const initCfg = loadProject(dfDir(root)).cfg;
889
- if (initCfg.mainHook) {
890
- const hookDir = path.join(root, ".git", "hooks");
891
- const hook = path.join(hookDir, "pre-commit");
892
- if (existsSync(hookDir) && !existsSync(hook)) {
893
- writeFileSync(
894
- hook,
895
- `#!/bin/sh\n# installed by dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden (override: DEV_FLOW_ALLOW_MAIN=1)\nbranch=$(git rev-parse --abbrev-ref HEAD)\nif [ "$branch" = "${initCfg.defaultBranch}" ] && [ -z "$DEV_FLOW_ALLOW_MAIN" ]; then\n echo "dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden — use a feature worktree and a PR" >&2\n exit 1\nfi\n`,
896
- { mode: 0o755 },
897
- );
898
- notes.push("pre-commit hook installed (blocks commits on main)");
899
- } else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow")) {
900
- notes.push("existing pre-commit hook found — dev-flow hook NOT installed; main commits outside Pi are unguarded");
901
- }
894
+ } else did.push("dev: none configured");
895
+ }
896
+ const ran = [branchLine, ...did].join("; ");
897
+ // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
898
+ const yoloWord = takeYoloWord(state!);
899
+ if (yoloWord) return { text: yoloWord, isError: true };
900
+ const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
901
+ if (!flag("confirmed") && !state!.yolo) {
902
+ // these commands already ran — say so even on the way out
903
+ if (!ui.hasUI) return { text: `${needsOperator("verification needs the operator: confirm interactively, or re-run with --confirmed once the operator answered in chat.", "Verified?")}\n${ran}`, isError: true };
904
+ 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?`);
905
+ if (!ok) return { text: "verification declined — stay in implement and fix what failed" };
906
+ }
907
+ state!.confirmations = { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } };
908
+ const final = verifyGate(state!, cfg, branch);
909
+ if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
910
+ state!.approvals.verify = now();
911
+ state!.stage = "pre-release";
912
+ writeState(root, state!);
913
+ return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${nextHint(state!, cfg)}` };
914
+ }
915
+
916
+ async function gateRelease(o: GateCtx): Promise<RunResult> {
917
+ const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
918
+ const { state, err } = needState(root, sess, slugArg);
919
+ if (err) return err;
920
+ const items = applicableItems(cfg, state!, "pre-release");
921
+ if (flag("no-version")) state!.noVersion = true; // operator's word at Release?: this flow ships without a version bump or tag
922
+ // yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
923
+ const yoloWord = takeYoloWord(state!);
924
+ if (yoloWord) return { text: yoloWord, isError: true };
925
+ // prep evidence is read from the worktree: the bump and changelog entry exist on the branch before the PR merges
926
+ const wtCwd = gateCwd(root, state!);
927
+ const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
928
+ ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
929
+ : null;
930
+ // tags are only needed on the versioned path; a project without versioning must not be held up by an offline origin
931
+ const remoteTags = cfg.versioning.file && !state!.noVersion ? await releaseTags(root) : [];
932
+ 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 };
933
+ const changelog =
934
+ cfg.release.changelog && existsSync(path.join(wtCwd, cfg.release.changelog))
935
+ ? { file: cfg.release.changelog, content: readFileSync(path.join(wtCwd, cfg.release.changelog), "utf8") }
936
+ : null;
937
+ // The changelog's baseline is what was pending before this release. The newest tag wins over the
938
+ // merge base: it is what actually shipped, and a rebase or squash merge can leave the merge base
939
+ // unreachable — a git-topology accident must not refuse a legal release (#97).
940
+ let changelogChanged: boolean | null = null;
941
+ const changelogBase: { pending: string[]; source: "tag" | "merge-base" | "none" } = { pending: [], source: "none" };
942
+ if (changelog) {
943
+ const p = sq(cfg.release.changelog!);
944
+ const mb = await sh(`git merge-base origin/${sq(cfg.defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(cfg.defaultBranch)} HEAD 2>/dev/null || true`, wtCwd);
945
+ const mbRef = mb.ok ? mb.out.trim() : "";
946
+ // proof the branch touched the changelog: local refs only, so the check stays offline-safe
947
+ if (mbRef) {
948
+ const changes = await sh(`git diff --name-only ${sq(mbRef)} -- ${p} 2>/dev/null; git ls-files --others --exclude-standard -- ${p}`, wtCwd);
949
+ changelogChanged = changes.out.split("\n").some((l) => l.trim());
950
+ }
951
+ const newest = !state!.noVersion && cfg.versioning.file ? newestTaggedVersion(cfg.versioning.pattern, remoteTags) : null;
952
+ // tag first, merge base as the understudy: `releaseTags` asks origin, so a clone that has not
953
+ // fetched the tag yet must still get a baseline instead of losing the fold proof
954
+ const bases: { ref: string; source: "tag" | "merge-base" }[] = [];
955
+ if (newest) bases.push({ ref: cfg.versioning.pattern.replace("{version}", newest), source: "tag" });
956
+ if (mbRef) bases.push({ ref: mbRef, source: "merge-base" });
957
+ for (const b of bases) {
958
+ const base = await sh(`git show ${sq(b.ref)}:${p} 2>/dev/null || true`, wtCwd);
959
+ if (base.out.trim()) {
960
+ changelogBase.pending = pendingEntryLines(base.out);
961
+ changelogBase.source = b.source;
962
+ break;
902
963
  }
903
- return { text: notes.join("\n") };
904
964
  }
965
+ }
966
+ const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
967
+ // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
968
+ if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
969
+ // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
970
+ const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
971
+ if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
972
+ // a stale session build is the operator's decision, never a block: publishing under an older gate is a
973
+ // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
974
+ // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
975
+ // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
976
+ const selfBuild = checkoutBuild(root);
977
+ const behind = sessionRunsOlderBuild(loadedVersion(), selfBuild.version);
978
+ // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
979
+ // has every proof the checkout would run, and asking about it would be noise.
980
+ const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
981
+ let staleAsk = "";
982
+ let staleNote = "";
983
+ if (stale) {
984
+ const clPath = path.join(selfBuild.dir, "CHANGELOG.md");
985
+ const missing = existsSync(clPath) && selfBuild.version ? changelogVersionsBetween(readFileSync(clPath, "utf8"), behind, selfBuild.version) : [];
986
+ staleAsk =
987
+ ` This session runs dev-flow ${behind}, ${selfBuild.label} ships ${selfBuild.version ?? "?"} — gate proofs shipped between the two will NOT run. ` +
988
+ (missing.length
989
+ ? `Shipped since ${behind}: ${missing.slice(0, 8).join(", ")}${missing.length > 8 ? ` …(${missing.length} total)` : ""} — see ${clPath}. `
990
+ : `What shipped between them is not readable from the checkout's CHANGELOG.md — read it before deciding. `) +
991
+ `Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
992
+ staleNote = `released under dev-flow ${behind} (${selfBuild.label} ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
993
+ }
994
+ const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
995
+ if (!flag("confirmed") && !state!.yolo) {
996
+ if (!ui.hasUI) return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}`, "Release?"), isError: true };
997
+ const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${state!.noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${state!.noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}`);
998
+ if (!ok) return { text: "release declined — keep preparing in pre-release" };
999
+ }
1000
+ state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
1001
+ state!.approvals["pre-release"] = now();
1002
+ state!.stage = "release";
1003
+ // a skipped proof is never silent: the gate says which one and why (#97)
1004
+ const foldNote = !changelog
1005
+ ? ""
1006
+ : flag("no-fold-check")
1007
+ ? " Warning: the changelog fold proofs were skipped (--no-fold-check) — check that the entry carries what was pending."
1008
+ : changelogBase.source === "none"
1009
+ ? " Warning: no tag or merge base to compare against, so the changelog fold was not proven — check the entry by hand."
1010
+ : "";
1011
+ // the version of record is fixed here, from the manifest this gate validated: release-done must not
1012
+ // re-read a checkout that may still be behind (#52)
1013
+ if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
1014
+ if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1015
+ writeState(root, state!);
1016
+ 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}.` : ""}\n${nextHint(state!, cfg)}` };
1017
+ }
905
1018
 
906
- case "start": {
907
- if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs are operator-granted modes — ask the operator in chat, then add --confirmed", isError: true };
908
- if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
909
- // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
910
- if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
911
- const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
912
- if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — the operator must grant it in chat, then re-run with --confirmed`, isError: true };
913
- // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
914
- const curBr = await currentBranch(root);
915
- 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 };
916
- // --- preflight: is this session running the current build, and is the playbook complete? ---
917
- const notes: string[] = [];
918
- const disk = checkoutBuild(root);
919
- const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
920
- if (behind) notes.push(`warning: this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version} — /reload rebinds session state; only restarting the host swaps the code it runs`);
921
- const dupStart = copyWarning();
922
- if (dupStart) notes.push(dupStart);
923
- if (flag("check-upstream")) {
924
- const pub = await sh("npm view pi-dev-flow version", root);
925
- const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
926
- 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?)");
1019
+ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1020
+ const { root, sess, cfg, flag, slugArg } = o;
1021
+ const { state, err } = needState(root, sess, slugArg);
1022
+ if (err) return err;
1023
+ const errs = releaseGate(state!);
1024
+ let manifestVer: string | null = state!.releaseVersion ?? null;
1025
+ if (cfg.versioning.file && !state!.noVersion && !manifestVer) {
1026
+ // a flow approved before releaseVersion existed: the worktree copy is what the release gate
1027
+ // validated, the main checkout is the last resort (#52)
1028
+ for (const dir of [gateCwd(root, state!), root]) {
1029
+ const p = path.join(dir, cfg.versioning.file);
1030
+ if (!existsSync(p)) continue;
1031
+ manifestVer = parseVersion(cfg.versioning.file, readFileSync(p, "utf8"));
1032
+ if (manifestVer) break;
1033
+ }
1034
+ if (!manifestVer) errs.push(`versioning.file "${cfg.versioning.file}" has no parsable version — fix the playbook`);
1035
+ }
1036
+ const expectedTag = manifestVer ? cfg.versioning.pattern.replace("{version}", manifestVer) : null;
1037
+ const hasOrigin = (await sh("git remote get-url origin", root)).ok;
1038
+ // one round-trip answers both questions about the tag: is it there, and did it leave this laptop (#52)
1039
+ const tags = expectedTag ? await releaseTags(root) : [];
1040
+ if (tags === null) errs.push("cannot list tags on origin (offline?) — retry: local tags must not decide what is already released");
1041
+ else if (expectedTag && manifestVer) {
1042
+ const verrs = versionTagGate(manifestVer, cfg.versioning.pattern, tags);
1043
+ if (verrs.length) {
1044
+ // the actionable version of "not on the forge": the tag exists but never got pushed
1045
+ const local = hasOrigin ? (await sh(`git tag --list ${sq(expectedTag)}`, root)).out.trim() : "";
1046
+ 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)`);
1047
+ else errs.push(...verrs);
1048
+ }
1049
+ // never publish behind what the forge already has — that is how a stale manifest republished
1050
+ // the previous version and its artifact probe passed (#52)
1051
+ const newest = newestTaggedVersion(cfg.versioning.pattern, tags);
1052
+ if (newest && cmpVersions(newest, manifestVer) > 0) errs.push(`${cfg.versioning.pattern.replace("{version}", newest)} is already tagged — refusing to release ${expectedTag} behind it`);
1053
+ if (!verrs.length) {
1054
+ 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);
1055
+ if (!reach.ok) errs.push(`tag ${expectedTag} is not reachable from ${cfg.defaultBranch} — tag what actually shipped on ${cfg.defaultBranch}`);
1056
+ }
1057
+ }
1058
+ let artNote = "";
1059
+ if (expectedTag && cfg.release.artifact) {
1060
+ if (flag("no-artifact-check")) artNote = "Artifact check skipped (--no-artifact-check).";
1061
+ else {
1062
+ const cmd = cfg.release.artifact.replaceAll("{version}", manifestVer!).replaceAll("{tag}", expectedTag);
1063
+ const art = await sh(cmd, root);
1064
+ if (art.ok) artNote = `Artifact verified for ${manifestVer}.`;
1065
+ else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
1066
+ }
1067
+ }
1068
+ // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
1069
+ // refuses the release record; what dev-flow cannot see stays an advisory — the split the changelog
1070
+ // proofs learned (#97): an invisible topology never blocks a legal release.
1071
+ let mergeNote = "";
1072
+ if (cfg.release.merge && cfg.release.merge !== "any" && state!.branch) {
1073
+ const br = state!.branch;
1074
+ await sh(`git fetch -q origin ${sq(br)} 2>/dev/null; git fetch -q origin ${sq(cfg.defaultBranch)} 2>/dev/null`, root);
1075
+ const refsOk = hasOrigin && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${br}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1076
+ // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1077
+ // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1078
+ const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1079
+ const forgeProof = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1080
+ const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeProof, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1081
+ if (proof.errors.length) errs.push(...proof.errors);
1082
+ else mergeNote = proof.note;
1083
+ }
1084
+ if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1085
+ // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
1086
+ const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false; let ghNote = "";
1087
+ let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1088
+ let bodyNote = "";
1089
+ const forgeName = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1090
+ if (manifestVer && flag("no-release-create")) ghNote = "Forge release skipped (--no-release-create).";
1091
+ 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).";
1092
+ else if (manifestVer && releasesWanted) {
1093
+ // forge release for the verified tag — gh for GitHub, glab for GitLab. A failed create is no
1094
+ // longer the end of the story: the proof below asks the forge whether anything is there (#63, #85)
1095
+ const tag = expectedTag!;
1096
+ const forge = forgeName;
1097
+ if (forge === "self") ghNote = "Forge release skipped (forge=self — publication stays manual).";
1098
+ else {
1099
+ // the body is the changelog entry for this version (#97); the tag annotation only stands in
1100
+ // when the changelog has no entry for it — and never the output of a failed command, which
1101
+ // is how a shell error became a release body (#51)
1102
+ const notesRes = await sh(tagNotesCommand(tag), root);
1103
+ const annotation = notesRes.ok ? notesRes.out.trim() : "";
1104
+ let changelogText: string | null = null;
1105
+ if (cfg.release.changelog) {
1106
+ const cl = path.join(gateCwd(root, state!), cfg.release.changelog);
1107
+ if (existsSync(cl)) changelogText = readFileSync(cl, "utf8");
927
1108
  }
928
- // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
929
- const gaps = doctorFindings(root, cfg, loadProject(dfDir(root)).md).filter((x) => !x.startsWith("no merge policy"));
930
- 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")}`);
931
- // the merge policy is the one blocking gap: it decides the shape of the default branch and nobody can
932
- // reconstruct it afterwards. Ask once in chat (a checkpoint word like any other), write the answer, continue.
933
- const styleArg = flagValue(rest, "merge");
934
- const style = styleArg === null ? null : parseMergeStyle(styleArg);
935
- if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
936
- // with no playbook at all there is nothing to ask about: writing the playbook is `flow init`'s job, and
937
- // a repo that never ran init must not be refused a feature by a merge-policy question
938
- const hasPlaybook = existsSync(path.join(dfDir(root), "project.md"));
939
- if (!hasPlaybook) notes.push("no .dev-flow/project.md yet — flow init writes the playbook (it now asks for the merge policy too)");
940
- if (hasPlaybook && (!cfg.release.merge || (style && style !== cfg.release.merge))) {
941
- if (!style) {
942
- const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
1109
+ const picked = pickReleaseNotes({ changelog: changelogText, version: manifestVer, annotation });
1110
+ const notes = picked.notes;
1111
+ if (picked.source === "changelog") bodyOfRecord = notes;
1112
+ let notesNote = "";
1113
+ if (picked.source === "changelog") notesNote = `notes from ${cfg.release.changelog}. `;
1114
+ 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. `;
1115
+ else if (!notesRes.ok) notesNote = `no release notes (the tag command failed: ${tail(notesRes.out)}). `;
1116
+ else if (annotation && looksLikeShellError(annotation)) notesNote = "no release notes (the tag command returned a shell error, not a body). ";
1117
+ 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). `;
1118
+ const cmd = forge === "gitlab"
1119
+ ? `glab release create ${sq(tag)} --name ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`
1120
+ : `gh release create ${sq(tag)} --title ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`;
1121
+ const gr = await sh(cmd, root);
1122
+ // a failed create is the operator's call to decline, never a choice we make for them — stamp it so finish names it (#63)
1123
+ if (gr.ok) delete state!.forgeReleaseSkipped; // a successful retry lifts the stamp
1124
+ else state!.forgeReleaseSkipped = tail(gr.out);
1125
+ ghNote = gr.ok ? `${forge} release ${tag} created. ${notesNote}`.trim() : `${forge} release skipped: ${tail(gr.out)}`;
1126
+ }
1127
+ }
1128
+ const diskBuild = checkoutBuild(root);
1129
+ const behind = sessionRunsOlderBuild(loadedVersion(), diskBuild.version);
1130
+ const openRelease = checklistPending(cfg, state!, "release");
1131
+ // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
1132
+ // name them at the last objective gate — on the way out too, or the refusal hides half the story
1133
+ 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.` : "";
1134
+ // #85: ask the forge whether the release exists instead of trusting the attempt. #51, #60 and #63
1135
+ // were three ways of recording a release nothing published, and the artifact probe saw none of them
1136
+ if (releasesWanted && expectedTag && forgeName !== "self") {
1137
+ const view = forgeName === "gitlab" ? `glab release view ${sq(expectedTag)}` : `gh release view ${sq(expectedTag)}`;
1138
+ if (!(await sh(view, root)).ok) {
1139
+ 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 };
1140
+ }
1141
+ delete state!.forgeReleaseSkipped; // the forge has it, whatever the create call reported
1142
+ ghNote += `${ghNote ? " " : ""}Release ${expectedTag} verified on ${forgeName}.`;
1143
+ // #97: the changelog entry is the release body — prove the forge kept it. gh normalizes the
1144
+ // markdown it stored, so the comparison normalizes too; on another forge say it was skipped
1145
+ // rather than guess at a JSON shape nobody pinned.
1146
+ if (bodyOfRecord !== null) {
1147
+ if (forgeName !== "github") bodyNote = `Release body proof skipped (forge=${forgeName}).`;
1148
+ else {
1149
+ const got = await sh(`gh release view ${sq(expectedTag)} --json body --jq .body`, root);
1150
+ if (!got.ok) bodyNote = `warning: could not read back the ${expectedTag} release body — compare it with ${cfg.release.changelog} by hand.`;
1151
+ else if (normalizeReleaseBody(got.out) !== normalizeReleaseBody(bodyOfRecord))
943
1152
  return {
944
- text: needsOperator(
945
- `the playbook has no merge policy — ask the operator how a merged PR should land on ${cfg.defaultBranch}: squash, merge (a merge commit), rebase, or any (no policy).${ev ? ` ${ev.note}${ev.recent ? ` Detected suggestion: ${ev.recent}.` : ""}` : ""} Then re-run: flow start ${slugArg} --merge=<style> --confirmed (the answer is written into .dev-flow/project.md)`,
946
- "Merge policy?",
947
- ),
1153
+ 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)}`,
948
1154
  isError: true,
949
1155
  };
950
- }
951
- 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 };
952
- const written = await writePlaybookMergePolicy(root, style);
953
- if ("err" in written) return { text: written.err, isError: true };
954
- // the flow that just wrote the policy must see it: nextHint and the merge guard read this config
955
- cfg.release.merge = style;
956
- notes.push(written.note);
1156
+ else bodyNote = `Release ${expectedTag} body matches ${cfg.release.changelog}.`;
957
1157
  }
958
- // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling.
959
- // the stamp is what ran, not what the disk claims (that mismatch is the warning above).
960
- const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), loadedVersion() ?? undefined);
961
- mkdirSync(path.join(featDir(root, slugArg), "plan"), { recursive: true });
962
- writeState(root, state);
963
- sess.bind(slugArg);
964
- sess.rename(slugArg);
965
- 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${nextHint(state, cfg)}` };
966
1158
  }
1159
+ }
1160
+ state!.approvals.release = now();
1161
+ const tailNote = [
1162
+ // a session that shipped from behind: the code it runs is not the code the checkout just released
1163
+ state!.staleBuild
1164
+ ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
1165
+ : behind
1166
+ // #117: the pair (session vs what the disk ships) makes the warning actionable where it prints;
1167
+ // a second registered copy is what made the skew confusing on the report — name it too
1168
+ ? `warning: this session runs dev-flow ${behind}, ${diskBuild.label} ships ${diskBuild.version ?? "?"} — /reload before trusting what it printed.${copyWarning() ? ` ${copyWarning()}` : ""}`
1169
+ : "",
1170
+ mergeNote,
1171
+ openNote,
1172
+ ghNote,
1173
+ bodyNote,
1174
+ artNote,
1175
+ ].filter(Boolean).join(" ");
1176
+ writeState(root, state!);
1177
+ return { text: `release recorded as complete${state!.noVersion ? " (unversioned — the changelog entry ships under Unreleased; the next versioned release folds it)" : ""}.${tailNote ? ` ${tailNote}` : ""}\n${nextHint(state!, cfg)}` };
1178
+ }
967
1179
 
968
- case "status": {
969
- const df = dfDir(root);
970
- const { md } = loadProject(df);
971
- // cheap fs probes only (no git subprocesses) — status is a glance, `flow doctor` is the full list
972
- const findings = md ? doctorFindings(root, cfg, md) : [];
973
- // a session running an older build than the disk ships is the one thing a glance must say: every
974
- // gate proof printed since the drift began belongs to the older code.
975
- const disk = checkoutBuild(root);
976
- const staleBuild = sessionRunsOlderBuild(loadedVersion(), disk.version);
977
- const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(staleBuild ? [`⚠ this session runs dev-flow ${staleBuild}, ${disk.label} ships ${disk.version} — /reload rebinds; restart swaps code`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
978
- // the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
979
- const rmap = roadmapOpenCount(readRoadmap(root));
980
- const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
981
- const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
982
- const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
983
- if (flag("json")) {
984
- const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
985
- return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
986
- }
987
- if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
988
- const lines = slugs.flatMap((s) => {
989
- const st = readState(root, s);
990
- if (!st) return [];
991
- return [
992
- `${s === cur ? "→" : " "} ${s}: stage=${st.stage}${st.ui ? " [ui]" : ""}${st.yolo ? " [yolo]" : ""}${st.noVersion ? " [no-version]" : ""} branch=${st.branch || "-"} worktree=${st.worktree || "-"}${st.flowVersion ? ` flow=${st.flowVersion}` : ""}`,
993
- ` approvals: ${Object.keys(st.approvals).join(", ") || "none"} | checks: ${Object.entries(st.checks).map(([k, v]) => `${k}:${v.ok ? "ok" : "FAILED"}`).join(", ") || "none"}${st.confirmations?.implement ? " | checklist: confirmed" : ""}`,
994
- ` next: ${nextHint(st, cfg)}`,
995
- ];
996
- });
997
- if (warn.length) lines.push(...warn);
998
- // which identity this session's state is keyed by: a claim fight is undiagnosable when the key
999
- // could be a session id or a shared directory and the output does not say which
1000
- lines.push(`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)" : ""}`);
1001
- const refl = readReflections(root);
1002
- if (refl.length) lines.push(`↻ ${refl.length} reflection(s) open — run flow doctor (it reviews and routes them)`);
1003
- lines.push(...rmapLine);
1004
- return { text: lines.join("\n") || "no features" };
1180
+ async function gateFinish(o: GateCtx): Promise<RunResult> {
1181
+ const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
1182
+ const { state, err } = needState(root, sess, slugArg);
1183
+ if (err) return err;
1184
+ if (!state!.approvals.release)
1185
+ 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 };
1186
+ // after this the flow state is gone: nothing may sit uncommitted or unpushed
1187
+ const dirty = await sh("git status --porcelain", root);
1188
+ 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 };
1189
+ const hasOriginF = (await sh("git remote get-url origin", root)).ok;
1190
+ if (hasOriginF) {
1191
+ const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1192
+ if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
1193
+ }
1194
+ // close-out also syncs the main checkout: a released flow must never leave local
1195
+ // <default> trailing origin — the push check above proved nothing local-only remains, so a
1196
+ // differing sha means local trails and the fast-forward is safe. never a merge: a diverged
1197
+ // or not-checked-out main prints the operator's exact command instead of touching anything
1198
+ let syncNote = "";
1199
+ if (hasOriginF) {
1200
+ const headSha = await sh("git rev-parse HEAD", root);
1201
+ const originSha = await sh(`git rev-parse ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1202
+ if (headSha.ok && originSha.ok && headSha.out.trim() !== originSha.out.trim()) {
1203
+ const onDefault = (await currentBranch(root)) === cfg.defaultBranch;
1204
+ const ff = onDefault ? await sh(`git merge --ff-only ${sq(`origin/${cfg.defaultBranch}`)}`, root) : { ok: false, out: "" };
1205
+ syncNote = ff.ok
1206
+ ? ` local ${cfg.defaultBranch} fast-forwarded to origin/${cfg.defaultBranch}.`
1207
+ : ` local ${cfg.defaultBranch} trails origin/${cfg.defaultBranch} and did not fast-forward cleanly — sync by hand: git -C ${sq(root)} pull --ff-only`;
1005
1208
  }
1006
-
1007
- case "reflect": {
1008
- // gate flags belong to the state verbs — pasted into the note they read as part of the operator's
1009
- // own sentence in reflections.md (#43). --plugin/--playbook/--both are reflect's own: they state
1010
- // the filing instead of leaving it to a keyword guess.
1011
- const words = rest.filter((a) => !a.startsWith("--"));
1012
- const forced: ReflectSection[] | null = flag("both")
1013
- ? (["playbook", "plugin"] as ReflectSection[])
1014
- : flag("plugin")
1015
- ? (["plugin"] as ReflectSection[])
1016
- : flag("playbook")
1017
- ? (["playbook"] as ReflectSection[])
1018
- : null;
1019
- // single words are verbs (roadmap-style); a note merely starting with one stays a note
1020
- if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
1021
- if (words.length === 1 && words[0] === "list") return reflectList(root);
1022
- if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
1023
- if (words.length) return reflectNote(root, sess, words, forced);
1024
- // upstream for the update probe: the manifest's repository field; the dev-flow checkout itself falls back to its origin
1025
- const self = pluginVersion(import.meta.dirname);
1026
- const upstream = self.repo || (isSelfRepo(root) ? githubSlug((await sh("git remote get-url origin", root)).out) : "");
1027
- return { text: reflectProtocol(readReflections(root), isSelfRepo(root), { version: self.version, upstream, closed: closedReflectionCount(readReflectionsText(root)) }).join("\n") };
1209
+ }
1210
+ // the cleanup part of closing out: drop the worktree and branch the release consumed
1211
+ const wt = worktreeAbs(root, state!);
1212
+ let closeNote: string;
1213
+ let unmergedNote = "";
1214
+ if (wt && existsSync(wt)) {
1215
+ const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
1216
+ 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);
1217
+ const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1218
+ if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}`, isError: true };
1219
+ if (assess.unmerged.length) {
1220
+ const policy = cfg.release.merge;
1221
+ // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1222
+ // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1223
+ 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;
1224
+ unmergedNote =
1225
+ policy && policy !== "merge" && policy !== "any"
1226
+ ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1227
+ : policy === "merge" && measurable
1228
+ ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} although the playbook says merge = merge — that PR did not land as a merge commit`
1229
+ : ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1230
+ // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1231
+ // answer it, only the operator does
1232
+ if (policy === "merge" && measurable && !flag("confirmed"))
1233
+ return { text: needsOperator(`the playbook says merge = merge, but ${assess.unmerged.length} commit(s) of ${state!.slug} are not on ${cfg.defaultBranch} — the PR landed as a squash or a rebase. Ask the operator how to proceed, then re-run with --confirmed`, "Merge policy violation?"), isError: true };
1028
1234
  }
1029
-
1030
- case "roadmap": {
1031
- // the backlog is advisory — no state, no gating; direct file edits stay allowed like reflections.md
1032
- const words = rest.filter((a) => !a.startsWith("--")); // gate flags are not backlog prose (#43 applies here too)
1033
- const [verb = "list", ...args] = words;
1034
- const text = readRoadmap(root);
1035
- const open = roadmapOpenCount(text);
1036
- const done = roadmapDoneCount(text);
1037
- const save = (next: string) => writeFileSync(roadmapFile(root), next); // .dev-flow/ existence is runFlow's precondition
1038
- const idx = Number(args[0]);
1039
- const validIdx = Number.isInteger(idx) && idx >= 1 && idx <= open;
1040
- switch (verb) {
1041
- case "list": {
1042
- if (!open) return { text: done ? `roadmap: nothing open (${done} done — flow roadmap tidy drops them)` : "roadmap: empty — flow roadmap add \"<future feature>\"" };
1043
- return { text: [`roadmap — ${open} open (${done} done):`, ...openChecklistItems(text).map((l, i) => ` ${i + 1}. ${l.slice(6)}`)].join("\n") };
1044
- }
1045
- case "add": {
1046
- if (!args.length) return { text: 'usage: flow roadmap add "<future feature>"', isError: true };
1047
- save(appendRoadmapItem(text, args.join(" ")));
1048
- return { text: `roadmap: added — ${open + 1} open` };
1049
- }
1050
- case "pick": {
1051
- const slug = args[1] ?? "";
1052
- if (!validIdx) return { text: `pick: open item 1–${open} required — flow roadmap lists them`, isError: true };
1053
- if (!slug || !validSlug(slug)) return { text: `usage: flow roadmap pick <n> <slug> — the slug flow start will use (lowercase, dashes)`, isError: true };
1054
- save(roadmapPick(text, idx, slug)!);
1055
- return { text: `roadmap: item ${idx} picked for ${slug} — now: flow start ${slug} (flow finish checks the item off when it ships)` };
1056
- }
1057
- case "done": {
1058
- if (!validIdx) return { text: `done: open item 1–${open} required — flow roadmap lists them`, isError: true };
1059
- // stamped with date + bound slug, so history says what shipped it
1060
- save(roadmapDone(text, idx, [new Date().toISOString().slice(0, 10), sess.slug].filter(Boolean).join(" "))!);
1061
- return { text: `roadmap: item ${idx} marked done (${open - 1} open)` };
1062
- }
1063
- case "tidy": {
1064
- if (!done) return { text: `roadmap: nothing to tidy (${open} open, 0 done)` };
1065
- save(roadmapTidy(text));
1066
- return { text: `roadmap: dropped ${done} done item(s) — ${open} open` };
1067
- }
1068
- default:
1069
- return { text: "usage: flow roadmap [list|add <text>|pick <n> <slug>|done <n>|tidy]", isError: true };
1235
+ }
1236
+ // a forge release that failed at release-done is still the operator's call — but they must see it before the state vanishes (#63)
1237
+ const forgeSkipNote = state!.forgeReleaseSkipped ? ` WARNING: the forge release was not created (${state!.forgeReleaseSkipped}) — recreate it manually or re-run release-done before finishing.` : "";
1238
+ // the one finish question — asked after the safety checks so it can never be a wasted question
1239
+ // yolo works uniformly at every gate: at Finish? nothing later remains to pre-confirm, the flag just answers this one
1240
+ const yoloWord = takeYoloWord(state!);
1241
+ if (yoloWord) return { text: yoloWord, isError: true };
1242
+ if (!flag("confirmed") && !state!.yolo) {
1243
+ if (!ui.hasUI) return { text: needsOperator(`finish needs the operator: ask them Finish? in chat, then re-run with --confirmed (or run /flow finish interactively)${forgeSkipNote}`, "Finish?"), isError: true };
1244
+ const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1245
+ if (!ok) return { text: "finish declined" };
1246
+ }
1247
+ if (wt && existsSync(wt)) {
1248
+ const rm = await sh(`git worktree remove ${sq(wt)} && git branch -D ${sq(state!.branch)}`, root);
1249
+ 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 };
1250
+ closeNote = `worktree and branch ${state!.branch} removed`;
1251
+ } else {
1252
+ await sh("git worktree prune", root);
1253
+ closeNote = "worktree already gone";
1254
+ if (state!.branch && (await sh(`git rev-parse --verify --quiet refs/heads/${state!.branch}`, root)).ok) {
1255
+ const del = await sh(`git branch -d ${sq(state!.branch)}`, root);
1256
+ closeNote = del.ok ? `branch ${state!.branch} deleted` : `branch ${state!.branch} kept (not fully merged — git branch -D if sure)`;
1257
+ }
1258
+ }
1259
+ // remote cleanup: origin/<branch> is deleted only on proof it was released — being an ancestor of
1260
+ // origin/<default> (merge-commit merges) or a merged PR via gh (squash merges); else it stays.
1261
+ let remoteNote = "";
1262
+ if (state!.branch && (await sh("git remote get-url origin", root)).ok) {
1263
+ const br = state!.branch;
1264
+ const onRemote = await sh("git ls-remote --heads origin", root);
1265
+ if (onRemote.out.split("\n").some((l) => l.endsWith(`\trefs/heads/${br}`))) {
1266
+ await sh(`git fetch -q origin ${sq(br)}`, root);
1267
+ let merged = (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok;
1268
+ if (!merged) {
1269
+ // squash merges leave no ancestry — ask the forge: gh pr list, or the GitLab API via glab; self-hosted stays on ancestry proof
1270
+ const originUrl = await sh("git remote get-url origin", root);
1271
+ const forge = cfg.forge || detectForge(originUrl.out);
1272
+ if (forge === "gitlab") {
1273
+ const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${br}&state=merged&per_page=1`)}`, root);
1274
+ merged = mr.ok && mr.out.trim() !== "[]";
1275
+ } else if (forge === "github") {
1276
+ const pr = await sh(`gh pr list --state merged --head ${sq(br)} --json number --jq length`, root);
1277
+ merged = pr.ok && pr.out.trim() !== "0";
1070
1278
  }
1071
1279
  }
1072
-
1073
- case "doctor": {
1074
- // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
1075
- const df = dfDir(root);
1076
- const loaded = loadProject(df);
1077
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
1078
- findings.push(...(await gitConsistency(root, loaded.cfg)));
1079
- const refl = readReflections(root);
1080
- if (refl.length) {
1081
- 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:`);
1082
- // labelled from the heading each item sits under — the file is the record, re-guessing from the
1083
- // note text made doctor's table disagree with where the note was actually filed
1084
- for (const r of reflectionRoutes(refl, isSelfRepo(root))) findings.push(` [${r.sections.join("+")}] ${r.text}\n → ${r.route}`);
1085
- }
1086
- const unfiled = reflectUnfiledCount(readReflectionsText(root));
1087
- if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## plugin — flow reflect list shows them, flow reflect move <n> --plugin|--playbook files them`);
1088
- const closedRefl = closedReflectionCount(readReflectionsText(root));
1089
- if (closedRefl) findings.push(reflectionsTidyHint(closedRefl));
1090
- 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" };
1091
- // flow doctor <note>: a fresh observation gets an investigation brief and a fix route
1092
- return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
1280
+ if (merged) remoteNote = (await sh(`git push origin --delete ${sq(`refs/heads/${br}`)}`, root)).ok
1281
+ ? ` origin/${br} deleted (verified merged)`
1282
+ : ` origin/${br} delete failed — git push origin --delete ${br}`;
1283
+ else remoteNote = ` origin/${br} kept — merged state not verifiable from here (git push origin --delete ${br} when sure)`;
1093
1284
  }
1094
-
1095
- case "version": {
1096
- // the plugin's own version — separate from the project's versioning.file version the release gates use
1097
- const self = checkoutBuild(root);
1098
- const behind = sessionRunsOlderBuild(loadedVersion(), self.version);
1099
- 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}`;
1100
- // in the dev-flow repo head names the checkout, so name where the stale code actually lives
1101
- const from = SELF_BUILD.dir !== self.dir ? ` (from ${SELF_BUILD.dir})` : "";
1102
- const dupNote = copyWarning();
1103
- // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
1104
- if (flag("check-upstream")) {
1105
- const pub = await sh("npm view pi-dev-flow version", root);
1106
- const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1107
- return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
1108
- }
1109
- 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}` : ""}` };
1285
+ }
1286
+ rmSync(featDir(root, state!.slug), { recursive: true, force: true });
1287
+ if (sess.slug === state!.slug) sess.bind(null);
1288
+ // a feature picked from the backlog closes its own item: check off what `roadmap pick` stamped (slug)
1289
+ let roadmapNote = "";
1290
+ if (existsSync(roadmapFile(root))) {
1291
+ const r = roadmapDoneForSlug(readRoadmap(root), state!.slug, new Date().toISOString().slice(0, 10));
1292
+ if (r.count) {
1293
+ writeFileSync(roadmapFile(root), r.text);
1294
+ roadmapNote = ` roadmap: ${r.count} item(s) marked done.`;
1110
1295
  }
1296
+ }
1297
+ return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${syncNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
1298
+ }
1111
1299
 
1112
- case "approve": {
1113
- const { state, err } = needState(root, sess, slugArg);
1114
- if (err) return err;
1115
- const errs = approveGate(state!, cfg, listFiles(path.join(featDir(root, state!.slug), "plan")));
1116
- if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1117
- const planItems = applicableItems(cfg, state!, "plan");
1118
- if (flag("yolo")) state!.yolo = true; // operator's word at Approve? — every later gate question is pre-confirmed; checks and guardrails stay
1119
- const audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
1120
- if (!flag("confirmed")) {
1121
- if (!ui.hasUI) return { text: needsOperator("plan approval needs the operator: approve interactively, or re-run with --confirmed once the operator answered in chat", "Approve?"), isError: true };
1122
- 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." : ""}`);
1123
- if (!ok) return { text: "approval declined — keep iterating on the plan" };
1124
- }
1125
- if (planItems.length) state!.confirmations = { ...state!.confirmations, plan: { hash: checklistHash(planItems), at: now() } };
1126
- const branch = subst(cfg.branchPattern, state!.slug);
1127
- const wtRel = subst(cfg.worktreeDir, state!.slug);
1128
- const wt = path.resolve(root, wtRel);
1129
- let setupNote = "";
1130
- if (!existsSync(wt)) {
1131
- // branch discipline: features branch off the default branch — never from a stale checkout HEAD
1132
- const base = (await sh(`git rev-parse --verify -q origin/${cfg.defaultBranch}`, root)).ok ? `origin/${cfg.defaultBranch}` : cfg.defaultBranch;
1133
- const res = await sh(`git worktree add ${sq(wt)} -b ${branch} ${base}`, root);
1134
- if (!res.ok) return { text: `worktree creation failed:\n${res.out}`, isError: true };
1135
- }
1136
- // setup is worktree work of a normal feature: a docs flow runs no project command at all (#49),
1137
- // and a worktree left behind by a setup that never succeeded must be retried — "fix it and run
1138
- // approve again" was a silent no-op on the reused directory (#49). setup is expected to be idempotent.
1139
- const setupCmd = state!.docs ? undefined : cfg.commands.setup;
1140
- if (setupCmd && !state!.setupAt) {
1141
- const s = await sh(setupCmd, wt);
1142
- 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 };
1143
- state!.setupAt = now();
1144
- setupNote = `\nsetup ran in the worktree (${setupCmd}).`;
1145
- } else if (state!.docs && cfg.commands.setup) {
1146
- setupNote = "\nsetup skipped (docs mode — no project commands run).";
1147
- }
1148
- state!.branch = branch;
1149
- state!.worktree = wtRel;
1150
- state!.stage = "implement";
1151
- state!.approvals.plan = now();
1152
- writeState(root, state!);
1153
- return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${setupNote}\n${nextHint(state!, cfg)}` };
1300
+ async function gateInit(o: GateCtx): Promise<RunResult> {
1301
+ const { root, ui, cfg, rest, flag } = o;
1302
+ // a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
1303
+ // only sanctioned agent path to the playbook: claiming "created" when the folder was already
1304
+ // there sends the agent diffing its own config for damage that never happened (#39).
1305
+ const dfExisted = existsSync(dfDir(root));
1306
+ mkdirSync(dfDir(root), { recursive: true });
1307
+ const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
1308
+ // self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
1309
+ writeFileSync(path.join(dfDir(root), ".gitignore"), "*\n!project.md\n");
1310
+ rmSync(path.join(dfDir(root), ".current"), { force: true }); // migrate away the legacy repo-global pointer
1311
+ const mdFile = path.join(dfDir(root), "project.md");
1312
+ const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
1313
+ const curBr = await currentBranch(root);
1314
+ // never propose a feature branch (contains "/") as the default branch
1315
+ const branch = (head.ok ? head.out.match(/refs\/remotes\/origin\/(.+)/)?.[1] : undefined) || (curBr.includes("/") ? undefined : curBr) || "main";
1316
+ const det = detectProject(root, branch);
1317
+ const origin = await sh("git remote get-url origin", root);
1318
+ det.partial.forge = origin.ok && origin.out.trim() ? detectForge(origin.out) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
1319
+ det.partial.merge = (await mergeHistoryEvidence(root, branch))?.note; // "what do you actually do when a PR merges", read off the log
1320
+ const loaded = loadProject(dfDir(root));
1321
+ const draftFresh = buildDraft(det);
1322
+ const draftRefresh = buildDraft(det, loaded.cfg);
1323
+ const editHint = "to change anything: edit .dev-flow/project.md directly (flow init = doctor revalidates), or from an agent session: flow init --draft → discuss → --write";
1324
+ if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
1325
+ // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
1326
+ const ghosts = ghostFeatureDirs(root);
1327
+ if (ghosts.length) {
1328
+ if (!ui.hasUI) notes.push(`${ghosts.length} ghost feature dir(s) — a plan/ with no state.json, no flow owns them (${ghosts.join(", ")}); delete them or run flow init interactively`);
1329
+ 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.`)) {
1330
+ for (const g of ghosts) rmSync(path.join(root, g), { recursive: true, force: true });
1331
+ notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
1332
+ } else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
1333
+ }
1334
+ const writeMd = (text: string): RunResult | null => {
1335
+ const parsed = parseProjectMd(text);
1336
+ if (parsed.hard.length) return { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true };
1337
+ // the operator's rules are not regenerable — keep what was there before any overwrite
1338
+ if (existsSync(mdFile)) copyFileSync(mdFile, `${mdFile}.bak`);
1339
+ writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
1340
+ return null;
1341
+ };
1342
+ if (flag("write")) {
1343
+ const content = rest[rest.indexOf("--write") + 1];
1344
+ if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>"', isError: true };
1345
+ const parsed = parseProjectMd(content);
1346
+ const rej = writeMd(content);
1347
+ if (rej) return rej;
1348
+ notes.push("project.md written (operator-owned playbook)", GIT_TRACK_NOTE);
1349
+ if (parsed.warn.length) notes.push("warnings:", ...parsed.warn.map((w) => ` ${w}`));
1350
+ } else if (!existsSync(mdFile)) {
1351
+ // first init: never write silently. The setup brief lists what detection could not decide;
1352
+ // the agent relays the questions to the operator and applies the answers via flow init --write
1353
+ // (validated) after presenting the digest; an interactive init may confirm the draft right here.
1354
+ const brief = [
1355
+ "setup — project.md not written yet; nothing is drafted to disk until the operator confirms.",
1356
+ ...det.report.map((r) => ` ${r}`),
1357
+ "questions for the operator (one per unclear knob, with the detected default):",
1358
+ ...setupQuestions(det).map((line, i) => ` ${i + 1}. ${line}`),
1359
+ "agent: ask these in chat, fill the draft (flow init --draft), then apply with flow init --write \"<content>\" (hard-validated) — present the digest and get the operator's confirmation before writing.",
1360
+ GIT_TRACK_NOTE,
1361
+ ];
1362
+ if (ui.hasUI) {
1363
+ const ok = await ui.confirm("Write project.md draft?", `${mdDigest(draftFresh)}\n\nWrite this detection draft now? Declining leaves the setup questions open for chat clarification.`);
1364
+ if (ok) {
1365
+ const rej = writeMd(draftFresh);
1366
+ if (rej) return rej;
1367
+ notes.push("wrote .dev-flow/project.md from detection — review it and adjust as needed", GIT_TRACK_NOTE);
1368
+ } else notes.push("draft not written — answer the setup questions, then flow init --write");
1154
1369
  }
1155
-
1156
- case "test": {
1157
- const { state, err } = needState(root, sess, slugArg);
1158
- if (err) return err;
1159
- if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
1160
- const res = await sh(cfg.commands.test, gateCwd(root, state!));
1161
- state!.checks.test = { ok: res.ok, at: now() };
1162
- await stampChecks(root, state!, ["test"]);
1163
- writeState(root, state!);
1164
- return { text: `test: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.test})\n${tail(res.out)}` };
1370
+ notes.push(...brief);
1371
+ } else if (flag("force")) {
1372
+ // a destructive reset of the operator's own file needs their word: --confirmed for an agent, one dialog for a human
1373
+ 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).`)));
1374
+ 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 };
1375
+ copyFileSync(mdFile, `${mdFile}.bak`);
1376
+ writeFileSync(mdFile, draftFresh);
1377
+ notes.push("project.md OVERWRITTEN (--force; previous copy kept as project.md.bak):", ...det.report.map((r) => ` ${r}`), GIT_TRACK_NOTE);
1378
+ } else if (!ui.hasUI) {
1379
+ // the CI/agent path: the doctor's findings have to be printed, not just promised
1380
+ const findings = doctorFindings(root, loaded.cfg, loaded.md);
1381
+ notes.push("project.md already exists — kept (flow init --force to overwrite, --write to edit)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
1382
+ } else if (existsSync(mdFile)) {
1383
+ // doctor mode: cheap consistency probes only — never runs project commands
1384
+ const findings = doctorFindings(root, loaded.cfg, loaded.md);
1385
+ findings.push(...(await gitConsistency(root, loaded.cfg)));
1386
+ // a repo that never said how a PR merges gets the evidence next to the finding, so the answer is a choice and not a guess
1387
+ if (!loaded.cfg.release.merge) {
1388
+ const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
1389
+ if (ev?.recent) findings.push(`${ev.note} — write it into the playbook: merge = ${ev.recent} under ## release (or let the next flow start ask and write it)`);
1165
1390
  }
1391
+ for (const it of readReflections(root)) findings.push(`open reflection [${it.section}]: ${it.line.slice(6)}`);
1392
+ if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
1393
+ else {
1394
+ // a refresh is regenerated from detection + config: lines it cannot reproduce are
1395
+ // hand-written (prose, checklist items, hand-set keys) and would vanish silently.
1396
+ const dropped = droppableLines(readFileSync(mdFile, "utf8"), draftRefresh);
1397
+ let edited: string | undefined;
1398
+ if (dropped.length)
1399
+ notes.push(`doctor: refresh refused — a regenerated draft would drop ${dropped.length} hand-written line(s):`, ...dropped.slice(0, 8).map((l) => ` ${l}`), ...(dropped.length > 8 ? [` …(${dropped.length - 8} more)`] : []));
1400
+ else
1401
+ edited = ui.editor
1402
+ ? await ui.editor(`flow init — doctor: ${findings.length} finding(s) — edit & save to apply, Esc skips`, draftRefresh)
1403
+ : (await ui.confirm(`flow init — doctor: ${findings.length} finding(s)`, `${findings.join("\n")}
1166
1404
 
1167
- case "verify": {
1168
- const { state, err } = needState(root, sess, slugArg);
1169
- if (err) return err;
1170
- const items = applicableItems(cfg, state!, "implement");
1171
- const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
1172
- const branchLine = describeBranchState(branch, cfg.defaultBranch);
1173
- // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
1174
- // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
1175
- // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
1176
- const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1177
- if (staleAtGate.length) writeState(root, state!);
1178
- const pending = pendingChecks(state!, cfg);
1179
- const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
1180
- if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
1181
- // tier-1 gate first (tier-2 confirmation is recorded by this very command, so it is excluded here)
1182
- const preGate = verifyGate({ ...state!, confirmations: { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } } }, cfg, branch);
1183
- if (preGate.length) return { text: `verify gate FAILED:\n- ${preGate.join("\n- ")}\n${branchLine}`, isError: true };
1184
- // commands that take minutes and touch live services must say so (#38): a terse gate let the
1185
- // agent tell the operator the dev deploy had never run, right after it recreated a container.
1186
- const did: string[] = [];
1187
- if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
1188
- if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
1189
- if (state!.docs) {
1190
- // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
1191
- did.push("docs mode: project commands skipped (build/dev/health)");
1192
- } else {
1193
- if (cfg.commands.build) {
1194
- const res = await sh(cfg.commands.build, gateCwd(root, state!));
1195
- state!.checks.build = { ok: res.ok, at: now() };
1196
- writeState(root, state!);
1197
- if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
1198
- did.push(`build ran (${cfg.commands.build})`);
1199
- }
1200
- // deploy to dev before asking — the operator reviews the running dev app, not a promise
1201
- if (cfg.commands.dev) {
1202
- const res = await sh(cfg.commands.dev, gateCwd(root, state!));
1203
- state!.checks.dev = { ok: res.ok, at: now() };
1204
- writeState(root, state!);
1205
- if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
1206
- did.push(`dev ran (${cfg.commands.dev})`);
1207
- // the deploy is what must be proven, not just run: a container that came back unhealthy, or
1208
- // still serves the previous build, must not pass on a health PASS recorded before it was
1209
- // recreated. What "the expected version" means is the project's business — the probe runs in
1210
- // the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
1211
- const probe = healthProbe(cfg);
1212
- if (!probe) did.push("health: none configured");
1213
- else {
1214
- const seedFail = await seedStep(root, state!, cfg);
1215
- if (seedFail) return seedFail;
1216
- const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
1217
- state!.checks.health = { ok: probed.ok, at: now() };
1218
- await stampChecks(root, state!, ["health"]);
1219
- writeState(root, state!);
1220
- // a probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42)
1221
- const tried = probed.attempts > 1 ? `, ${probed.attempts} attempts` : "";
1222
- 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 };
1223
- did.push(`health: PASS (${probe}${tried})`);
1224
- }
1225
- } else did.push("dev: none configured");
1226
- }
1227
- const ran = [branchLine, ...did].join("; ");
1228
- // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones; --confirmed anchors it, checks and guardrails stay
1229
- if (flag("yolo")) {
1230
- if (!state!.yolo && !flag("confirmed")) return { text: "yolo is the operator's word — the operator must have said it in chat, then re-run with --yolo --confirmed", isError: true };
1231
- state!.yolo = true;
1232
- }
1233
- const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1234
- if (!flag("confirmed") && !state!.yolo) {
1235
- // these commands already ran — say so even on the way out
1236
- if (!ui.hasUI) return { text: `${needsOperator("verification needs the operator: confirm interactively, or re-run with --confirmed once the operator answered in chat.", "Verified?")}\n${ran}`, isError: true };
1237
- 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?`);
1238
- if (!ok) return { text: "verification declined — stay in implement and fix what failed" };
1405
+ Write refreshed project.md? Your file; cancel writes nothing.
1406
+ ${mdDigest(draftRefresh)}`))
1407
+ ? draftRefresh
1408
+ : undefined;
1409
+ if (edited === undefined) notes.push(dropped.length ? "findings — fix them by editing the file:" : "declined — project.md unchanged", ...findings.map((f) => ` ${f}`));
1410
+ else {
1411
+ const rej = writeMd(edited);
1412
+ if (rej) return rej;
1413
+ notes.push("project.md refreshed — findings addressed:", ...findings.map((f) => ` ${f}`), editHint);
1239
1414
  }
1240
- state!.confirmations = { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } };
1241
- const final = verifyGate(state!, cfg, branch);
1242
- if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
1243
- state!.approvals.verify = now();
1244
- state!.stage = "pre-release";
1245
- writeState(root, state!);
1246
- return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${nextHint(state!, cfg)}` };
1247
1415
  }
1248
-
1249
- case "check": {
1250
- const { state, err } = needState(root, sess, slugArg);
1251
- if (err) return err;
1252
- // a docs flow runs no project command anywhere else — pendingChecks, verifyGate and releaseGate all skip
1253
- // it — so running tier-1 here only produced a FAIL that read like a broken deploy in a checkout that
1254
- // never built the binary (#96)
1255
- // shortcut: --docs is the operator's word, nothing checks the changeset is docs-only, so a mislabelled
1256
- // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
1257
- 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)" };
1258
- if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
1259
- const ran = await runChecks(root, state!, cfg, cfg.checkList);
1260
- return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
1416
+ }
1417
+ const initCfg = loadProject(dfDir(root)).cfg;
1418
+ if (initCfg.mainHook) {
1419
+ const hookDir = path.join(root, ".git", "hooks");
1420
+ const hook = path.join(hookDir, "pre-commit");
1421
+ if (existsSync(hookDir) && !existsSync(hook)) {
1422
+ writeFileSync(
1423
+ hook,
1424
+ `#!/bin/sh\n# installed by dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden (override: DEV_FLOW_ALLOW_MAIN=1)\nbranch=$(git rev-parse --abbrev-ref HEAD)\nif [ "$branch" = "${initCfg.defaultBranch}" ] && [ -z "$DEV_FLOW_ALLOW_MAIN" ]; then\n echo "dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden — use a feature worktree and a PR" >&2\n exit 1\nfi\n`,
1425
+ { mode: 0o755 },
1426
+ );
1427
+ notes.push("pre-commit hook installed (blocks commits on main)");
1428
+ } else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow")) {
1429
+ notes.push("existing pre-commit hook found — dev-flow hook NOT installed; main commits outside Pi are unguarded");
1261
1430
  }
1431
+ }
1432
+ return { text: notes.join("\n") };
1433
+ }
1262
1434
 
1263
- case "health": {
1264
- const { state, err } = needState(root, sess, slugArg);
1265
- if (err) return err;
1266
- if (!cfg.commands.health) return { text: "no commands.health configured — add `health = <command>` (or a flow-check health block) under ## implement in .dev-flow/project.md", isError: true };
1267
- const seedFail = await seedStep(root, state!, cfg);
1268
- if (seedFail) return seedFail;
1269
- const res = await runHealthProbe(cfg.commands.health, gateCwd(root, state!), cfg.healthWait);
1270
- state!.checks.health = { ok: res.ok, at: now() };
1271
- await stampChecks(root, state!, ["health"]);
1272
- writeState(root, state!);
1273
- const tried = res.attempts > 1 ? `, ${res.attempts} attempts` : "";
1274
- return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.health}${tried})\n${tail(res.out)}` };
1435
+ async function gateStart(o: GateCtx): Promise<RunResult> {
1436
+ const { root, ui, sess, cfg, rest, flag, slugArg } = o;
1437
+ if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs are operator-granted modes — ask the operator in chat, then add --confirmed", isError: true };
1438
+ if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
1439
+ // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
1440
+ if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
1441
+ const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
1442
+ if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — the operator must grant it in chat, then re-run with --confirmed`, isError: true };
1443
+ // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
1444
+ const curBr = await currentBranch(root);
1445
+ 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 };
1446
+ // --- preflight: is this session running the current build, and is the playbook complete? ---
1447
+ const notes: string[] = [];
1448
+ const disk = checkoutBuild(root);
1449
+ const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
1450
+ if (behind) notes.push(`warning: this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version} — /reload rebinds session state; only restarting the host swaps the code it runs`);
1451
+ const dupStart = copyWarning();
1452
+ if (dupStart) notes.push(dupStart);
1453
+ if (flag("check-upstream")) {
1454
+ const pub = await sh("npm view pi-dev-flow version", root);
1455
+ const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1456
+ 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?)");
1457
+ }
1458
+ // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
1459
+ const gaps = doctorFindings(root, cfg, loadProject(dfDir(root)).md).filter((x) => !x.startsWith("no merge policy"));
1460
+ 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")}`);
1461
+ // the merge policy is the one blocking gap: it decides the shape of the default branch and nobody can
1462
+ // reconstruct it afterwards. Ask once in chat (a checkpoint word like any other), write the answer, continue.
1463
+ const styleArg = flagValue(rest, "merge");
1464
+ const style = styleArg === null ? null : parseMergeStyle(styleArg);
1465
+ if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
1466
+ // with no playbook at all there is nothing to ask about: writing the playbook is `flow init`'s job, and
1467
+ // a repo that never ran init must not be refused a feature by a merge-policy question
1468
+ const hasPlaybook = existsSync(path.join(dfDir(root), "project.md"));
1469
+ if (!hasPlaybook) notes.push("no .dev-flow/project.md yet — flow init writes the playbook (it now asks for the merge policy too)");
1470
+ if (hasPlaybook && (!cfg.release.merge || (style && style !== cfg.release.merge))) {
1471
+ if (!style) {
1472
+ const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
1473
+ return {
1474
+ text: needsOperator(
1475
+ `the playbook has no merge policy — ask the operator how a merged PR should land on ${cfg.defaultBranch}: squash, merge (a merge commit), rebase, or any (no policy).${ev ? ` ${ev.note}${ev.recent ? ` Detected suggestion: ${ev.recent}.` : ""}` : ""} Then re-run: flow start ${slugArg} --merge=<style> --confirmed (the answer is written into .dev-flow/project.md)`,
1476
+ "Merge policy?",
1477
+ ),
1478
+ isError: true,
1479
+ };
1275
1480
  }
1481
+ 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 };
1482
+ const written = await writePlaybookMergePolicy(root, style);
1483
+ if ("err" in written) return { text: written.err, isError: true };
1484
+ // the flow that just wrote the policy must see it: nextHint and the merge guard read this config
1485
+ cfg.release.merge = style;
1486
+ notes.push(written.note);
1487
+ }
1488
+ // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling.
1489
+ // the stamp is what ran, not what the disk claims (that mismatch is the warning above).
1490
+ const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), loadedVersion() ?? undefined);
1491
+ mkdirSync(path.join(featDir(root, slugArg), "plan"), { recursive: true });
1492
+ writeState(root, state);
1493
+ sess.bind(slugArg);
1494
+ sess.rename(slugArg);
1495
+ 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${nextHint(state, cfg)}` };
1496
+ }
1276
1497
 
1277
- case "release": {
1278
- const { state, err } = needState(root, sess, slugArg);
1279
- if (err) return err;
1280
- const items = applicableItems(cfg, state!, "pre-release");
1281
- if (flag("no-version")) state!.noVersion = true; // operator's word at Release?: this flow ships without a version bump or tag
1282
- // yolo is the operator's word at Release? — answers this question and pre-confirms Finish?; publishing guardrails stay enforced
1283
- if (flag("yolo")) {
1284
- if (!state!.yolo && !flag("confirmed")) return { text: "yolo is the operator's word — the operator must have said it in chat, then re-run with --yolo --confirmed", isError: true };
1285
- state!.yolo = true;
1286
- }
1287
- // prep evidence is read from the worktree: the bump and changelog entry exist on the branch before the PR merges
1288
- const wtCwd = gateCwd(root, state!);
1289
- const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
1290
- ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
1498
+ async function gateApprove(o: GateCtx): Promise<RunResult> {
1499
+ const { root, ui, sess, cfg, flag, slugArg } = o;
1500
+ const { state, err } = needState(root, sess, slugArg);
1501
+ if (err) return err;
1502
+ const errs = approveGate(state!, cfg, listFiles(path.join(featDir(root, state!.slug), "plan")));
1503
+ if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1504
+ const planItems = applicableItems(cfg, state!, "plan");
1505
+ if (flag("yolo")) state!.yolo = true; // operator's word at Approve? — every later gate question is pre-confirmed; checks and guardrails stay
1506
+ const audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
1507
+ if (!flag("confirmed")) {
1508
+ if (!ui.hasUI) return { text: needsOperator("plan approval needs the operator: approve interactively, or re-run with --confirmed once the operator answered in chat", "Approve?"), isError: true };
1509
+ 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." : ""}`);
1510
+ if (!ok) return { text: "approval declined — keep iterating on the plan" };
1511
+ }
1512
+ if (planItems.length) state!.confirmations = { ...state!.confirmations, plan: { hash: checklistHash(planItems), at: now() } };
1513
+ const branch = subst(cfg.branchPattern, state!.slug);
1514
+ const wtRel = subst(cfg.worktreeDir, state!.slug);
1515
+ const wt = path.resolve(root, wtRel);
1516
+ let setupNote = "";
1517
+ if (!existsSync(wt)) {
1518
+ // branch discipline: features branch off the default branch — never from a stale checkout HEAD
1519
+ const base = (await sh(`git rev-parse --verify -q origin/${cfg.defaultBranch}`, root)).ok ? `origin/${cfg.defaultBranch}` : cfg.defaultBranch;
1520
+ const res = await sh(`git worktree add ${sq(wt)} -b ${branch} ${base}`, root);
1521
+ if (!res.ok) return { text: `worktree creation failed:\n${res.out}`, isError: true };
1522
+ }
1523
+ // setup is worktree work of a normal feature: a docs flow runs no project command at all (#49),
1524
+ // and a worktree left behind by a setup that never succeeded must be retried — "fix it and run
1525
+ // approve again" was a silent no-op on the reused directory (#49). setup is expected to be idempotent.
1526
+ const setupCmd = state!.docs ? undefined : cfg.commands.setup;
1527
+ if (setupCmd && !state!.setupAt) {
1528
+ const s = await sh(setupCmd, wt);
1529
+ 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 };
1530
+ state!.setupAt = now();
1531
+ setupNote = `\nsetup ran in the worktree (${setupCmd}).`;
1532
+ } else if (state!.docs && cfg.commands.setup) {
1533
+ setupNote = "\nsetup skipped (docs mode — no project commands run).";
1534
+ }
1535
+ state!.branch = branch;
1536
+ state!.worktree = wtRel;
1537
+ state!.stage = "implement";
1538
+ state!.approvals.plan = now();
1539
+ writeState(root, state!);
1540
+ return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${setupNote}\n${nextHint(state!, cfg)}` };
1541
+ }
1542
+
1543
+ async function gateStatus(o: GateCtx): Promise<RunResult> {
1544
+ const { root, ui, sess, cfg, flag, slugArg } = o;
1545
+ const df = dfDir(root);
1546
+ const { md } = loadProject(df);
1547
+ // cheap fs probes only (no git subprocesses) — status is a glance, `flow doctor` is the full list
1548
+ const findings = md ? doctorFindings(root, cfg, md) : [];
1549
+ // a session running an older build than the disk ships is the one thing a glance must say: every
1550
+ // gate proof printed since the drift began belongs to the older code.
1551
+ const disk = checkoutBuild(root);
1552
+ const staleBuild = sessionRunsOlderBuild(loadedVersion(), disk.version);
1553
+ const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(staleBuild ? [`⚠ this session runs dev-flow ${staleBuild}, ${disk.label} ships ${disk.version} — /reload rebinds; restart swaps code`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
1554
+ // the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
1555
+ const rmap = roadmapOpenCount(readRoadmap(root));
1556
+ const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
1557
+ const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
1558
+ const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
1559
+ if (flag("json")) {
1560
+ const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
1561
+ return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
1562
+ }
1563
+ if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
1564
+ const lines = slugs.flatMap((s) => {
1565
+ const st = readState(root, s);
1566
+ if (!st) return [];
1567
+ return [
1568
+ `${s === cur ? "→" : " "} ${s}: stage=${st.stage}${st.ui ? " [ui]" : ""}${st.yolo ? " [yolo]" : ""}${st.noVersion ? " [no-version]" : ""} branch=${st.branch || "-"} worktree=${st.worktree || "-"}${st.flowVersion ? ` flow=${st.flowVersion}` : ""}`,
1569
+ ` approvals: ${Object.keys(st.approvals).join(", ") || "none"} | checks: ${Object.entries(st.checks).map(([k, v]) => `${k}:${v.ok ? "ok" : "FAILED"}`).join(", ") || "none"}${st.confirmations?.implement ? " | checklist: confirmed" : ""}`,
1570
+ ` next: ${nextHint(st, cfg)}`,
1571
+ ];
1572
+ });
1573
+ if (warn.length) lines.push(...warn);
1574
+ // which identity this session's state is keyed by: a claim fight is undiagnosable when the key
1575
+ // could be a session id or a shared directory and the output does not say which
1576
+ lines.push(`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)" : ""}`);
1577
+ const refl = readReflections(root);
1578
+ if (refl.length) lines.push(`↻ ${refl.length} reflection(s) open — run flow doctor (it reviews and routes them)`);
1579
+ lines.push(...rmapLine);
1580
+ return { text: lines.join("\n") || "no features" };
1581
+ }
1582
+
1583
+ async function gateReflect(o: GateCtx): Promise<RunResult> {
1584
+ const { root, sess, rest, flag } = o;
1585
+ // gate flags belong to the state verbs — pasted into the note they read as part of the operator's
1586
+ // own sentence in reflections.md (#43). --plugin/--playbook/--both are reflect's own: they state
1587
+ // the filing instead of leaving it to a keyword guess.
1588
+ const words = rest.filter((a) => !a.startsWith("--"));
1589
+ const forced: ReflectSection[] | null = flag("both")
1590
+ ? (["playbook", "plugin"] as ReflectSection[])
1591
+ : flag("plugin")
1592
+ ? (["plugin"] as ReflectSection[])
1593
+ : flag("playbook")
1594
+ ? (["playbook"] as ReflectSection[])
1291
1595
  : null;
1292
- // tags are only needed on the versioned path; a project without versioning must not be held up by an offline origin
1293
- const remoteTags = cfg.versioning.file && !state!.noVersion ? await releaseTags(root) : [];
1294
- 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 };
1295
- const changelog =
1296
- cfg.release.changelog && existsSync(path.join(wtCwd, cfg.release.changelog))
1297
- ? { file: cfg.release.changelog, content: readFileSync(path.join(wtCwd, cfg.release.changelog), "utf8") }
1298
- : null;
1299
- // The changelog's baseline is what was pending before this release. The newest tag wins over the
1300
- // merge base: it is what actually shipped, and a rebase or squash merge can leave the merge base
1301
- // unreachable — a git-topology accident must not refuse a legal release (#97).
1302
- let changelogChanged: boolean | null = null;
1303
- const changelogBase: { pending: string[]; source: "tag" | "merge-base" | "none" } = { pending: [], source: "none" };
1304
- if (changelog) {
1305
- const p = sq(cfg.release.changelog!);
1306
- const mb = await sh(`git merge-base origin/${sq(cfg.defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(cfg.defaultBranch)} HEAD 2>/dev/null || true`, wtCwd);
1307
- const mbRef = mb.ok ? mb.out.trim() : "";
1308
- // proof the branch touched the changelog: local refs only, so the check stays offline-safe
1309
- if (mbRef) {
1310
- const changes = await sh(`git diff --name-only ${sq(mbRef)} -- ${p} 2>/dev/null; git ls-files --others --exclude-standard -- ${p}`, wtCwd);
1311
- changelogChanged = changes.out.split("\n").some((l) => l.trim());
1312
- }
1313
- const newest = !state!.noVersion && cfg.versioning.file ? newestTaggedVersion(cfg.versioning.pattern, remoteTags) : null;
1314
- // tag first, merge base as the understudy: `releaseTags` asks origin, so a clone that has not
1315
- // fetched the tag yet must still get a baseline instead of losing the fold proof
1316
- const bases: { ref: string; source: "tag" | "merge-base" }[] = [];
1317
- if (newest) bases.push({ ref: cfg.versioning.pattern.replace("{version}", newest), source: "tag" });
1318
- if (mbRef) bases.push({ ref: mbRef, source: "merge-base" });
1319
- for (const b of bases) {
1320
- const base = await sh(`git show ${sq(b.ref)}:${p} 2>/dev/null || true`, wtCwd);
1321
- if (base.out.trim()) {
1322
- changelogBase.pending = pendingEntryLines(base.out);
1323
- changelogBase.source = b.source;
1324
- break;
1325
- }
1326
- }
1327
- }
1328
- const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1329
- // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1330
- if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1331
- // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1332
- const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1333
- if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
1334
- // a stale session build is the operator's decision, never a block: publishing under an older gate is a
1335
- // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1336
- // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
1337
- // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
1338
- const selfBuild = checkoutBuild(root);
1339
- const behind = sessionRunsOlderBuild(loadedVersion(), selfBuild.version);
1340
- // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
1341
- // has every proof the checkout would run, and asking about it would be noise.
1342
- const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
1343
- let staleAsk = "";
1344
- let staleNote = "";
1345
- if (stale) {
1346
- const clPath = path.join(selfBuild.dir, "CHANGELOG.md");
1347
- const missing = existsSync(clPath) && selfBuild.version ? changelogVersionsBetween(readFileSync(clPath, "utf8"), behind, selfBuild.version) : [];
1348
- staleAsk =
1349
- ` This session runs dev-flow ${behind}, ${selfBuild.label} ships ${selfBuild.version ?? "?"} — gate proofs shipped between the two will NOT run. ` +
1350
- (missing.length
1351
- ? `Shipped since ${behind}: ${missing.slice(0, 8).join(", ")}${missing.length > 8 ? ` …(${missing.length} total)` : ""} — see ${clPath}. `
1352
- : `What shipped between them is not readable from the checkout's CHANGELOG.md — read it before deciding. `) +
1353
- `Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
1354
- staleNote = `released under dev-flow ${behind} (${selfBuild.label} ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
1355
- }
1356
- const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1357
- if (!flag("confirmed") && !state!.yolo) {
1358
- if (!ui.hasUI) return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}`, "Release?"), isError: true };
1359
- const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${state!.noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${state!.noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}`);
1360
- if (!ok) return { text: "release declined — keep preparing in pre-release" };
1361
- }
1362
- state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
1363
- state!.approvals["pre-release"] = now();
1364
- state!.stage = "release";
1365
- // a skipped proof is never silent: the gate says which one and why (#97)
1366
- const foldNote = !changelog
1367
- ? ""
1368
- : flag("no-fold-check")
1369
- ? " Warning: the changelog fold proofs were skipped (--no-fold-check) — check that the entry carries what was pending."
1370
- : changelogBase.source === "none"
1371
- ? " Warning: no tag or merge base to compare against, so the changelog fold was not proven — check the entry by hand."
1372
- : "";
1373
- // the version of record is fixed here, from the manifest this gate validated: release-done must not
1374
- // re-read a checkout that may still be behind (#52)
1375
- if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
1376
- if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1377
- writeState(root, state!);
1378
- 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}.` : ""}\n${nextHint(state!, cfg)}` };
1379
- }
1596
+ // single words are verbs (roadmap-style); a note merely starting with one stays a note
1597
+ if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
1598
+ if (words.length === 1 && words[0] === "list") return reflectList(root);
1599
+ if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
1600
+ if (words.length) return reflectNote(root, sess, words, forced);
1601
+ // upstream for the update probe: the manifest's repository field; the dev-flow checkout itself falls back to its origin
1602
+ const self = pluginVersion(import.meta.dirname);
1603
+ const upstream = self.repo || (isSelfRepo(root) ? githubSlug((await sh("git remote get-url origin", root)).out) : "");
1604
+ return { text: reflectProtocol(readReflections(root), isSelfRepo(root), { version: self.version, upstream, closed: closedReflectionCount(readReflectionsText(root)) }).join("\n") };
1605
+ }
1380
1606
 
1381
- case "release-done": {
1382
- const { state, err } = needState(root, sess, slugArg);
1383
- if (err) return err;
1384
- const errs = releaseGate(state!);
1385
- let manifestVer: string | null = state!.releaseVersion ?? null;
1386
- if (cfg.versioning.file && !state!.noVersion && !manifestVer) {
1387
- // a flow approved before releaseVersion existed: the worktree copy is what the release gate
1388
- // validated, the main checkout is the last resort (#52)
1389
- for (const dir of [gateCwd(root, state!), root]) {
1390
- const p = path.join(dir, cfg.versioning.file);
1391
- if (!existsSync(p)) continue;
1392
- manifestVer = parseVersion(cfg.versioning.file, readFileSync(p, "utf8"));
1393
- if (manifestVer) break;
1394
- }
1395
- if (!manifestVer) errs.push(`versioning.file "${cfg.versioning.file}" has no parsable version — fix the playbook`);
1396
- }
1397
- const expectedTag = manifestVer ? cfg.versioning.pattern.replace("{version}", manifestVer) : null;
1398
- const hasOrigin = (await sh("git remote get-url origin", root)).ok;
1399
- // one round-trip answers both questions about the tag: is it there, and did it leave this laptop (#52)
1400
- const tags = expectedTag ? await releaseTags(root) : [];
1401
- if (tags === null) errs.push("cannot list tags on origin (offline?) — retry: local tags must not decide what is already released");
1402
- else if (expectedTag && manifestVer) {
1403
- const verrs = versionTagGate(manifestVer, cfg.versioning.pattern, tags);
1404
- if (verrs.length) {
1405
- // the actionable version of "not on the forge": the tag exists but never got pushed
1406
- const local = hasOrigin ? (await sh(`git tag --list ${sq(expectedTag)}`, root)).out.trim() : "";
1407
- 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)`);
1408
- else errs.push(...verrs);
1409
- }
1410
- // never publish behind what the forge already has — that is how a stale manifest republished
1411
- // the previous version and its artifact probe passed (#52)
1412
- const newest = newestTaggedVersion(cfg.versioning.pattern, tags);
1413
- if (newest && cmpVersions(newest, manifestVer) > 0) errs.push(`${cfg.versioning.pattern.replace("{version}", newest)} is already tagged — refusing to release ${expectedTag} behind it`);
1414
- if (!verrs.length) {
1415
- 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);
1416
- if (!reach.ok) errs.push(`tag ${expectedTag} is not reachable from ${cfg.defaultBranch} — tag what actually shipped on ${cfg.defaultBranch}`);
1417
- }
1418
- }
1419
- let artNote = "";
1420
- if (expectedTag && cfg.release.artifact) {
1421
- if (flag("no-artifact-check")) artNote = "Artifact check skipped (--no-artifact-check).";
1422
- else {
1423
- const cmd = cfg.release.artifact.replaceAll("{version}", manifestVer!).replaceAll("{tag}", expectedTag);
1424
- const art = await sh(cmd, root);
1425
- if (art.ok) artNote = `Artifact verified for ${manifestVer}.`;
1426
- else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
1427
- }
1428
- }
1429
- // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
1430
- // refuses the release record; what dev-flow cannot see stays an advisory — the split the changelog
1431
- // proofs learned (#97): an invisible topology never blocks a legal release.
1432
- let mergeNote = "";
1433
- if (cfg.release.merge && cfg.release.merge !== "any" && state!.branch) {
1434
- const br = state!.branch;
1435
- await sh(`git fetch -q origin ${sq(br)} 2>/dev/null; git fetch -q origin ${sq(cfg.defaultBranch)} 2>/dev/null`, root);
1436
- const refsOk = hasOrigin && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${br}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1437
- // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1438
- // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1439
- const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1440
- const forgeProof = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1441
- const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeProof, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1442
- if (proof.errors.length) errs.push(...proof.errors);
1443
- else mergeNote = proof.note;
1444
- }
1445
- if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1446
- // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
1447
- const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false; let ghNote = "";
1448
- let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1449
- let bodyNote = "";
1450
- const forgeName = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1451
- if (manifestVer && flag("no-release-create")) ghNote = "Forge release skipped (--no-release-create).";
1452
- 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).";
1453
- else if (manifestVer && releasesWanted) {
1454
- // forge release for the verified tag — gh for GitHub, glab for GitLab. A failed create is no
1455
- // longer the end of the story: the proof below asks the forge whether anything is there (#63, #85)
1456
- const tag = expectedTag!;
1457
- const forge = forgeName;
1458
- if (forge === "self") ghNote = "Forge release skipped (forge=self — publication stays manual).";
1459
- else {
1460
- // the body is the changelog entry for this version (#97); the tag annotation only stands in
1461
- // when the changelog has no entry for it — and never the output of a failed command, which
1462
- // is how a shell error became a release body (#51)
1463
- const notesRes = await sh(tagNotesCommand(tag), root);
1464
- const annotation = notesRes.ok ? notesRes.out.trim() : "";
1465
- let changelogText: string | null = null;
1466
- if (cfg.release.changelog) {
1467
- const cl = path.join(gateCwd(root, state!), cfg.release.changelog);
1468
- if (existsSync(cl)) changelogText = readFileSync(cl, "utf8");
1469
- }
1470
- const picked = pickReleaseNotes({ changelog: changelogText, version: manifestVer, annotation });
1471
- const notes = picked.notes;
1472
- if (picked.source === "changelog") bodyOfRecord = notes;
1473
- let notesNote = "";
1474
- if (picked.source === "changelog") notesNote = `notes from ${cfg.release.changelog}. `;
1475
- 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. `;
1476
- else if (!notesRes.ok) notesNote = `no release notes (the tag command failed: ${tail(notesRes.out)}). `;
1477
- else if (annotation && looksLikeShellError(annotation)) notesNote = "no release notes (the tag command returned a shell error, not a body). ";
1478
- 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). `;
1479
- const cmd = forge === "gitlab"
1480
- ? `glab release create ${sq(tag)} --name ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`
1481
- : `gh release create ${sq(tag)} --title ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`;
1482
- const gr = await sh(cmd, root);
1483
- // a failed create is the operator's call to decline, never a choice we make for them — stamp it so finish names it (#63)
1484
- if (gr.ok) delete state!.forgeReleaseSkipped; // a successful retry lifts the stamp
1485
- else state!.forgeReleaseSkipped = tail(gr.out);
1486
- ghNote = gr.ok ? `${forge} release ${tag} created. ${notesNote}`.trim() : `${forge} release skipped: ${tail(gr.out)}`;
1487
- }
1488
- }
1489
- const diskBuild = checkoutBuild(root);
1490
- const behind = sessionRunsOlderBuild(loadedVersion(), diskBuild.version);
1491
- const openRelease = checklistPending(cfg, state!, "release");
1492
- // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
1493
- // name them at the last objective gate — on the way out too, or the refusal hides half the story
1494
- 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.` : "";
1495
- // #85: ask the forge whether the release exists instead of trusting the attempt. #51, #60 and #63
1496
- // were three ways of recording a release nothing published, and the artifact probe saw none of them
1497
- if (releasesWanted && expectedTag && forgeName !== "self") {
1498
- const view = forgeName === "gitlab" ? `glab release view ${sq(expectedTag)}` : `gh release view ${sq(expectedTag)}`;
1499
- if (!(await sh(view, root)).ok) {
1500
- 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 };
1501
- }
1502
- delete state!.forgeReleaseSkipped; // the forge has it, whatever the create call reported
1503
- ghNote += `${ghNote ? " " : ""}Release ${expectedTag} verified on ${forgeName}.`;
1504
- // #97: the changelog entry is the release body — prove the forge kept it. gh normalizes the
1505
- // markdown it stored, so the comparison normalizes too; on another forge say it was skipped
1506
- // rather than guess at a JSON shape nobody pinned.
1507
- if (bodyOfRecord !== null) {
1508
- if (forgeName !== "github") bodyNote = `Release body proof skipped (forge=${forgeName}).`;
1509
- else {
1510
- const got = await sh(`gh release view ${sq(expectedTag)} --json body --jq .body`, root);
1511
- if (!got.ok) bodyNote = `warning: could not read back the ${expectedTag} release body — compare it with ${cfg.release.changelog} by hand.`;
1512
- else if (normalizeReleaseBody(got.out) !== normalizeReleaseBody(bodyOfRecord))
1513
- return {
1514
- 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)}`,
1515
- isError: true,
1516
- };
1517
- else bodyNote = `Release ${expectedTag} body matches ${cfg.release.changelog}.`;
1518
- }
1519
- }
1520
- }
1521
- state!.approvals.release = now();
1522
- const tailNote = [
1523
- // a session that shipped from behind: the code it runs is not the code the checkout just released
1524
- state!.staleBuild
1525
- ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
1526
- : behind
1527
- // #117: the pair (session vs what the disk ships) makes the warning actionable where it prints;
1528
- // a second registered copy is what made the skew confusing on the report — name it too
1529
- ? `warning: this session runs dev-flow ${behind}, ${diskBuild.label} ships ${diskBuild.version ?? "?"} — /reload before trusting what it printed.${copyWarning() ? ` ${copyWarning()}` : ""}`
1530
- : "",
1531
- mergeNote,
1532
- openNote,
1533
- ghNote,
1534
- bodyNote,
1535
- artNote,
1536
- ].filter(Boolean).join(" ");
1537
- writeState(root, state!);
1538
- return { text: `release recorded as complete${state!.noVersion ? " (unversioned — the changelog entry ships under Unreleased; the next versioned release folds it)" : ""}.${tailNote ? ` ${tailNote}` : ""}\n${nextHint(state!, cfg)}` };
1607
+ async function gateRoadmap(o: GateCtx): Promise<RunResult> {
1608
+ const { root, sess, rest } = o;
1609
+ // the backlog is advisory — no state, no gating; direct file edits stay allowed like reflections.md
1610
+ const words = rest.filter((a) => !a.startsWith("--")); // gate flags are not backlog prose (#43 applies here too)
1611
+ const [verb = "list", ...args] = words;
1612
+ const text = readRoadmap(root);
1613
+ const open = roadmapOpenCount(text);
1614
+ const done = roadmapDoneCount(text);
1615
+ const save = (next: string) => writeFileSync(roadmapFile(root), next); // .dev-flow/ existence is runFlow's precondition
1616
+ const idx = Number(args[0]);
1617
+ const validIdx = Number.isInteger(idx) && idx >= 1 && idx <= open;
1618
+ switch (verb) {
1619
+ case "list": {
1620
+ if (!open) return { text: done ? `roadmap: nothing open (${done} done — flow roadmap tidy drops them)` : "roadmap: empty — flow roadmap add \"<future feature>\"" };
1621
+ return { text: [`roadmap — ${open} open (${done} done):`, ...openChecklistItems(text).map((l, i) => ` ${i + 1}. ${l.slice(6)}`)].join("\n") };
1539
1622
  }
1540
-
1541
- case "finish": {
1542
- const { state, err } = needState(root, sess, slugArg);
1543
- if (err) return err;
1544
- if (!state!.approvals.release)
1545
- 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 };
1546
- // after this the flow state is gone: nothing may sit uncommitted or unpushed
1547
- const dirty = await sh("git status --porcelain", root);
1548
- 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 };
1549
- const hasOriginF = (await sh("git remote get-url origin", root)).ok;
1550
- if (hasOriginF) {
1551
- const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1552
- if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
1553
- }
1554
- // close-out also syncs the main checkout: a released flow must never leave local
1555
- // <default> trailing origin — the push check above proved nothing local-only remains, so a
1556
- // differing sha means local trails and the fast-forward is safe. never a merge: a diverged
1557
- // or not-checked-out main prints the operator's exact command instead of touching anything
1558
- let syncNote = "";
1559
- if (hasOriginF) {
1560
- const headSha = await sh("git rev-parse HEAD", root);
1561
- const originSha = await sh(`git rev-parse ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1562
- if (headSha.ok && originSha.ok && headSha.out.trim() !== originSha.out.trim()) {
1563
- const onDefault = (await currentBranch(root)) === cfg.defaultBranch;
1564
- const ff = onDefault ? await sh(`git merge --ff-only ${sq(`origin/${cfg.defaultBranch}`)}`, root) : { ok: false, out: "" };
1565
- syncNote = ff.ok
1566
- ? ` local ${cfg.defaultBranch} fast-forwarded to origin/${cfg.defaultBranch}.`
1567
- : ` local ${cfg.defaultBranch} trails origin/${cfg.defaultBranch} and did not fast-forward cleanly — sync by hand: git -C ${sq(root)} pull --ff-only`;
1568
- }
1569
- }
1570
- // the cleanup part of closing out: drop the worktree and branch the release consumed
1571
- const wt = worktreeAbs(root, state!);
1572
- let closeNote: string;
1573
- let unmergedNote = "";
1574
- if (wt && existsSync(wt)) {
1575
- const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
1576
- 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);
1577
- const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1578
- if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}`, isError: true };
1579
- if (assess.unmerged.length) {
1580
- const policy = cfg.release.merge;
1581
- // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1582
- // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1583
- 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;
1584
- unmergedNote =
1585
- policy && policy !== "merge" && policy !== "any"
1586
- ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1587
- : policy === "merge" && measurable
1588
- ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} although the playbook says merge = merge — that PR did not land as a merge commit`
1589
- : ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1590
- // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1591
- // answer it, only the operator does
1592
- if (policy === "merge" && measurable && !flag("confirmed"))
1593
- return { text: needsOperator(`the playbook says merge = merge, but ${assess.unmerged.length} commit(s) of ${state!.slug} are not on ${cfg.defaultBranch} — the PR landed as a squash or a rebase. Ask the operator how to proceed, then re-run with --confirmed`, "Merge policy violation?"), isError: true };
1594
- }
1595
- }
1596
- // a forge release that failed at release-done is still the operator's call — but they must see it before the state vanishes (#63)
1597
- const forgeSkipNote = state!.forgeReleaseSkipped ? ` WARNING: the forge release was not created (${state!.forgeReleaseSkipped}) — recreate it manually or re-run release-done before finishing.` : "";
1598
- // the one finish question — asked after the safety checks so it can never be a wasted question
1599
- // yolo works uniformly at every gate: at Finish? nothing later remains to pre-confirm, the flag just answers this one
1600
- if (flag("yolo")) {
1601
- if (!state!.yolo && !flag("confirmed")) return { text: "yolo is the operator's word — the operator must have said it in chat, then re-run with --yolo --confirmed", isError: true };
1602
- state!.yolo = true;
1603
- }
1604
- if (!flag("confirmed") && !state!.yolo) {
1605
- if (!ui.hasUI) return { text: needsOperator(`finish needs the operator: ask them Finish? in chat, then re-run with --confirmed (or run /flow finish interactively)${forgeSkipNote}`, "Finish?"), isError: true };
1606
- const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1607
- if (!ok) return { text: "finish declined" };
1608
- }
1609
- if (wt && existsSync(wt)) {
1610
- const rm = await sh(`git worktree remove ${sq(wt)} && git branch -D ${sq(state!.branch)}`, root);
1611
- 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 };
1612
- closeNote = `worktree and branch ${state!.branch} removed`;
1613
- } else {
1614
- await sh("git worktree prune", root);
1615
- closeNote = "worktree already gone";
1616
- if (state!.branch && (await sh(`git rev-parse --verify --quiet refs/heads/${state!.branch}`, root)).ok) {
1617
- const del = await sh(`git branch -d ${sq(state!.branch)}`, root);
1618
- closeNote = del.ok ? `branch ${state!.branch} deleted` : `branch ${state!.branch} kept (not fully merged — git branch -D if sure)`;
1619
- }
1620
- }
1621
- // remote cleanup: origin/<branch> is deleted only on proof it was released — being an ancestor of
1622
- // origin/<default> (merge-commit merges) or a merged PR via gh (squash merges); else it stays.
1623
- let remoteNote = "";
1624
- if (state!.branch && (await sh("git remote get-url origin", root)).ok) {
1625
- const br = state!.branch;
1626
- const onRemote = await sh("git ls-remote --heads origin", root);
1627
- if (onRemote.out.split("\n").some((l) => l.endsWith(`\trefs/heads/${br}`))) {
1628
- await sh(`git fetch -q origin ${sq(br)}`, root);
1629
- let merged = (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok;
1630
- if (!merged) {
1631
- // squash merges leave no ancestry — ask the forge: gh pr list, or the GitLab API via glab; self-hosted stays on ancestry proof
1632
- const originUrl = await sh("git remote get-url origin", root);
1633
- const forge = cfg.forge || detectForge(originUrl.out);
1634
- if (forge === "gitlab") {
1635
- const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${br}&state=merged&per_page=1`)}`, root);
1636
- merged = mr.ok && mr.out.trim() !== "[]";
1637
- } else if (forge === "github") {
1638
- const pr = await sh(`gh pr list --state merged --head ${sq(br)} --json number --jq length`, root);
1639
- merged = pr.ok && pr.out.trim() !== "0";
1640
- }
1641
- }
1642
- if (merged) remoteNote = (await sh(`git push origin --delete ${sq(`refs/heads/${br}`)}`, root)).ok
1643
- ? ` origin/${br} deleted (verified merged)`
1644
- : ` origin/${br} delete failed — git push origin --delete ${br}`;
1645
- else remoteNote = ` origin/${br} kept — merged state not verifiable from here (git push origin --delete ${br} when sure)`;
1646
- }
1647
- }
1648
- rmSync(featDir(root, state!.slug), { recursive: true, force: true });
1649
- if (sess.slug === state!.slug) sess.bind(null);
1650
- // a feature picked from the backlog closes its own item: check off what `roadmap pick` stamped (slug)
1651
- let roadmapNote = "";
1652
- if (existsSync(roadmapFile(root))) {
1653
- const r = roadmapDoneForSlug(readRoadmap(root), state!.slug, new Date().toISOString().slice(0, 10));
1654
- if (r.count) {
1655
- writeFileSync(roadmapFile(root), r.text);
1656
- roadmapNote = ` roadmap: ${r.count} item(s) marked done.`;
1657
- }
1658
- }
1659
- return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${syncNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
1623
+ case "add": {
1624
+ if (!args.length) return { text: 'usage: flow roadmap add "<future feature>"', isError: true };
1625
+ save(appendRoadmapItem(text, args.join(" ")));
1626
+ return { text: `roadmap: added — ${open + 1} open` };
1660
1627
  }
1661
-
1662
- case "use": {
1663
- if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
1664
- const st = readState(root, slugArg);
1665
- if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
1666
- const prior = readClaim(root, slugArg);
1667
- const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
1668
- sess.bind(slugArg);
1669
- sess.rename(slugArg);
1670
- 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}` };
1628
+ case "pick": {
1629
+ const slug = args[1] ?? "";
1630
+ if (!validIdx) return { text: `pick: open item 1–${open} required — flow roadmap lists them`, isError: true };
1631
+ if (!slug || !validSlug(slug)) return { text: `usage: flow roadmap pick <n> <slug> — the slug flow start will use (lowercase, dashes)`, isError: true };
1632
+ save(roadmapPick(text, idx, slug)!);
1633
+ return { text: `roadmap: item ${idx} picked for ${slug} — now: flow start ${slug} (flow finish checks the item off when it ships)` };
1671
1634
  }
1672
-
1673
- case "abort": {
1674
- // Unbinds the session only; state and worktree stay for manual recovery.
1675
- const target = slugArg ?? sess.slug;
1676
- if (!target) return { text: "nothing bound — pass a slug", isError: true };
1677
- const st = readState(root, target);
1678
- // a live claim locks the whole feature, not only its gates: aborting it out from under the session
1679
- // that works it erases the plan that session is still writing (same rule needState applies)
1680
- const claim = readClaim(root, target);
1681
- 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 };
1682
- if (sess.slug === target) sess.bind(null);
1683
- if (st && !st.worktree) {
1684
- // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
1685
- // as a ghost the doctor flags (a plan/ whose state.json is gone)
1686
- rmSync(featDir(root, target), { recursive: true, force: true });
1687
- return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
1688
- }
1689
- return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
1635
+ case "done": {
1636
+ if (!validIdx) return { text: `done: open item 1–${open} required — flow roadmap lists them`, isError: true };
1637
+ // stamped with date + bound slug, so history says what shipped it
1638
+ save(roadmapDone(text, idx, [new Date().toISOString().slice(0, 10), sess.slug].filter(Boolean).join(" "))!);
1639
+ return { text: `roadmap: item ${idx} marked done (${open - 1} open)` };
1640
+ }
1641
+ case "tidy": {
1642
+ if (!done) return { text: `roadmap: nothing to tidy (${open} open, 0 done)` };
1643
+ save(roadmapTidy(text));
1644
+ return { text: `roadmap: dropped ${done} done item(s) — ${open} open` };
1690
1645
  }
1691
-
1692
1646
  default:
1693
- return { text: `unknown subcommand "${sub}" — ${GATE_HELP}`, isError: true };
1647
+ return { text: "usage: flow roadmap [list|add <text>|pick <n> <slug>|done <n>|tidy]", isError: true };
1648
+ }
1649
+ }
1650
+
1651
+ async function gateDoctor(o: GateCtx): Promise<RunResult> {
1652
+ const { root, cfg, rest } = o;
1653
+ // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
1654
+ const df = dfDir(root);
1655
+ const loaded = loadProject(df);
1656
+ const findings = doctorFindings(root, loaded.cfg, loaded.md);
1657
+ findings.push(...(await gitConsistency(root, loaded.cfg)));
1658
+ const refl = readReflections(root);
1659
+ if (refl.length) {
1660
+ 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:`);
1661
+ // labelled from the heading each item sits under — the file is the record, re-guessing from the
1662
+ // note text made doctor's table disagree with where the note was actually filed
1663
+ for (const r of reflectionRoutes(refl, isSelfRepo(root))) findings.push(` [${r.sections.join("+")}] ${r.text}\n → ${r.route}`);
1664
+ }
1665
+ const unfiled = reflectUnfiledCount(readReflectionsText(root));
1666
+ if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## plugin — flow reflect list shows them, flow reflect move <n> --plugin|--playbook files them`);
1667
+ const closedRefl = closedReflectionCount(readReflectionsText(root));
1668
+ if (closedRefl) findings.push(reflectionsTidyHint(closedRefl));
1669
+ 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" };
1670
+ // flow doctor <note>: a fresh observation gets an investigation brief and a fix route
1671
+ return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
1672
+ }
1673
+
1674
+ /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
1675
+ * their own names back, so the bodies needed zero edits. */
1676
+ interface GateCtx {
1677
+ root: string;
1678
+ ui: Ui;
1679
+ sess: Session;
1680
+ cfg: Config;
1681
+ rest: string[];
1682
+ flag: (name: string) => boolean;
1683
+ slugArg?: string;
1684
+ takeYoloWord: (state: FlowState) => string | null;
1685
+ }
1686
+
1687
+ async function gateVersion(o: GateCtx): Promise<RunResult> {
1688
+ const { root, flag } = o;
1689
+ // the plugin's own version — separate from the project's versioning.file version the release gates use
1690
+ const self = checkoutBuild(root);
1691
+ const behind = sessionRunsOlderBuild(loadedVersion(), self.version);
1692
+ 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}`;
1693
+ // in the dev-flow repo head names the checkout, so name where the stale code actually lives
1694
+ const from = SELF_BUILD.dir !== self.dir ? ` (from ${SELF_BUILD.dir})` : "";
1695
+ const dupNote = copyWarning();
1696
+ // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
1697
+ if (flag("check-upstream")) {
1698
+ const pub = await sh("npm view pi-dev-flow version", root);
1699
+ const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1700
+ return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
1701
+ }
1702
+ 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}` : ""}` };
1703
+ }
1704
+
1705
+ async function gateTest(o: GateCtx): Promise<RunResult> {
1706
+ const { root, sess, cfg, slugArg } = o;
1707
+ const { state, err } = needState(root, sess, slugArg);
1708
+ if (err) return err;
1709
+ if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
1710
+ const res = await sh(cfg.commands.test, gateCwd(root, state!));
1711
+ state!.checks.test = { ok: res.ok, at: now() };
1712
+ await stampChecks(root, state!, ["test"]);
1713
+ writeState(root, state!);
1714
+ return { text: `test: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.test})\n${tail(res.out)}` };
1715
+ }
1716
+
1717
+ async function gateCheck(o: GateCtx): Promise<RunResult> {
1718
+ const { root, sess, cfg, slugArg } = o;
1719
+ const { state, err } = needState(root, sess, slugArg);
1720
+ if (err) return err;
1721
+ // a docs flow runs no project command anywhere else — pendingChecks, verifyGate and releaseGate all skip
1722
+ // it — so running tier-1 here only produced a FAIL that read like a broken deploy in a checkout that
1723
+ // never built the binary (#96)
1724
+ // shortcut: --docs is the operator's word, nothing checks the changeset is docs-only, so a mislabelled
1725
+ // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
1726
+ 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)" };
1727
+ if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
1728
+ const ran = await runChecks(root, state!, cfg, cfg.checkList);
1729
+ return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
1730
+ }
1731
+
1732
+ async function gateHealth(o: GateCtx): Promise<RunResult> {
1733
+ const { root, sess, cfg, slugArg } = o;
1734
+ const { state, err } = needState(root, sess, slugArg);
1735
+ if (err) return err;
1736
+ if (!cfg.commands.health) return { text: "no commands.health configured — add `health = <command>` (or a flow-check health block) under ## implement in .dev-flow/project.md", isError: true };
1737
+ const seedFail = await seedStep(root, state!, cfg);
1738
+ if (seedFail) return seedFail;
1739
+ const res = await runHealthProbe(cfg.commands.health, gateCwd(root, state!), cfg.healthWait);
1740
+ state!.checks.health = { ok: res.ok, at: now() };
1741
+ await stampChecks(root, state!, ["health"]);
1742
+ writeState(root, state!);
1743
+ const tried = res.attempts > 1 ? `, ${res.attempts} attempts` : "";
1744
+ return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.health}${tried})\n${tail(res.out)}` };
1745
+ }
1746
+
1747
+ async function gateUse(o: GateCtx): Promise<RunResult> {
1748
+ const { root, sess, slugArg } = o;
1749
+ if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
1750
+ const st = readState(root, slugArg);
1751
+ if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
1752
+ const prior = readClaim(root, slugArg);
1753
+ const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
1754
+ sess.bind(slugArg);
1755
+ sess.rename(slugArg);
1756
+ 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}` };
1757
+ }
1758
+
1759
+ async function gateAbort(o: GateCtx): Promise<RunResult> {
1760
+ const { root, sess, slugArg } = o;
1761
+ // Unbinds the session only; state and worktree stay for manual recovery.
1762
+ const target = slugArg ?? sess.slug;
1763
+ if (!target) return { text: "nothing bound — pass a slug", isError: true };
1764
+ const st = readState(root, target);
1765
+ // a live claim locks the whole feature, not only its gates: aborting it out from under the session
1766
+ // that works it erases the plan that session is still writing (same rule needState applies)
1767
+ const claim = readClaim(root, target);
1768
+ 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 };
1769
+ if (sess.slug === target) sess.bind(null);
1770
+ if (st && !st.worktree) {
1771
+ // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
1772
+ // as a ghost the doctor flags (a plan/ whose state.json is gone)
1773
+ rmSync(featDir(root, target), { recursive: true, force: true });
1774
+ return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
1694
1775
  }
1776
+ return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
1695
1777
  }
1696
1778
 
1779
+
1697
1780
  async function currentBranch(root: string): Promise<string> {
1698
1781
  const r = await sh("git branch --show-current", root);
1699
1782
  return r.ok ? r.out.split("\n")[0] : "";