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