pi-dev-flow 0.91.1 → 0.92.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +5 -5
- package/docs/development.md +2 -1
- package/docs/gates.md +56 -16
- package/docs/guardrails.md +4 -2
- package/docs/headless.md +9 -5
- package/docs/playbook.md +15 -3
- package/docs/reflections.md +5 -3
- package/extensions/dev-flow.ts +21 -7
- package/package.json +1 -1
- package/skills/dev-flow/references/finish.md +12 -5
- package/skills/dev-flow/references/implement.md +6 -2
- package/skills/dev-flow/references/plan.md +9 -5
- package/skills/dev-flow/references/pre-release.md +8 -5
- package/skills/dev-flow/references/reflect.md +5 -4
- package/skills/dev-flow/references/release.md +53 -40
- package/skills/dev-flow/references/start.md +11 -8
- package/src/core.ts +71 -16
- package/src/projectmd.ts +21 -2
- package/src/runtime/base.ts +1 -1
- package/src/runtime/checks.ts +95 -5
- package/src/runtime/gates.ts +53 -14
- package/src/runtime/grants.ts +38 -4
- package/src/runtime/publish.ts +223 -0
- package/src/runtime/reflect.ts +16 -5
- package/src/runtime/ship.ts +136 -38
package/src/runtime/checks.ts
CHANGED
|
@@ -3,10 +3,10 @@ import { existsSync, readFileSync, statfsSync } from "node:fs";
|
|
|
3
3
|
import { createServer } from "node:net";
|
|
4
4
|
import { freemem } from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import { checkFingerprint, DEFAULTS, freshenChecks, healthProbe, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
|
|
6
|
+
import { AGENT_MARK, checkFingerprint, DEFAULTS, freshenChecks, healthProbe, prepOnlyChange, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
|
|
7
7
|
import { loadProject } from "../projectmd.ts";
|
|
8
8
|
import { agentText, presentGate, type GateView, type StageFacts } from "../present.ts";
|
|
9
|
-
import { atomicWrite, boundFeature, dfDir, featDir, featureEnv, flagValue, gateCwd, initiated, mergeBase, now, originUrl, readState, runHealthProbe, sh, tail, worktreeAbs, writeState } from "./base.ts";
|
|
9
|
+
import { atomicWrite, boundFeature, buildSkew, dfDir, featDir, featureEnv, flagValue, gateCwd, initiated, mergeBase, now, originUrl, readState, runHealthProbe, sh, tail, worktreeAbs, writeState } from "./base.ts";
|
|
10
10
|
import { type GateCtx } from "./gates.ts";
|
|
11
11
|
|
|
12
12
|
/** The port this flow's dev deploy uses: the operator's pick for it, else the playbook default. */
|
|
@@ -28,6 +28,26 @@ export const devPortsFile = (root: string) => path.join(dfDir(root), "dev-ports.
|
|
|
28
28
|
export const slotKey = (port: number | undefined) => (port === undefined ? "default" : String(port));
|
|
29
29
|
|
|
30
30
|
/** Live slots only: a slot whose flow finished (state.json gone) or was aborted holds nothing. */
|
|
31
|
+
/** Close a flow's hold on the dev stack: stop a side-by-side instance (a port the operator picked at verify)
|
|
32
|
+
* and give its dev-port entries back. The default port's stack stays up — it is the machine's shared app,
|
|
33
|
+
* and the next flow redeploys over it. Returns the note for the gate's result ("" when nothing ran). */
|
|
34
|
+
export async function releaseDevSlot(root: string, state: FlowState, cfg: Config): Promise<string> {
|
|
35
|
+
let note = "";
|
|
36
|
+
if (state.devPort !== undefined && state.devPort !== cfg.devPort) {
|
|
37
|
+
if (cfg.commands.devDown) {
|
|
38
|
+
const down = await sh(cfg.commands.devDown, gateCwd(root, state), 5 * 60_000, devEnv(root, state, cfg));
|
|
39
|
+
note = down.ok ? ` dev instance on port ${state.devPort} stopped (${cfg.commands.devDown}).` : ` dev instance on port ${state.devPort} did NOT stop (${cfg.commands.devDown}) — stop it by hand:\n${tail(down.out)}\n`;
|
|
40
|
+
} else note = ` dev instance on port ${state.devPort} is still running — the playbook has no devDown to stop it; stop it by hand.`;
|
|
41
|
+
}
|
|
42
|
+
const reg = readDevPorts(root);
|
|
43
|
+
const mine = Object.keys(reg).filter((k) => reg[k].slug === state.slug);
|
|
44
|
+
if (mine.length) {
|
|
45
|
+
for (const k of mine) delete reg[k];
|
|
46
|
+
writeDevPorts(root, reg);
|
|
47
|
+
}
|
|
48
|
+
return note;
|
|
49
|
+
}
|
|
50
|
+
|
|
31
51
|
export function readDevPorts(root: string): Record<string, DevSlot> {
|
|
32
52
|
let raw: Record<string, DevSlot>;
|
|
33
53
|
try {
|
|
@@ -249,9 +269,45 @@ export async function worktreeFingerprint(cwd: string): Promise<string | null> {
|
|
|
249
269
|
/** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
|
|
250
270
|
* that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
|
|
251
271
|
export async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
|
|
252
|
-
const
|
|
272
|
+
const cwd = gateCwd(root, state);
|
|
273
|
+
const fp = await worktreeFingerprint(cwd);
|
|
253
274
|
if (!fp) return;
|
|
254
|
-
|
|
275
|
+
// a clean tree is exactly its HEAD: only then can a later gate reason about what was committed since
|
|
276
|
+
const st = await sh("git status --porcelain", cwd);
|
|
277
|
+
const head = st.ok && !st.out.trim() ? (await sh("git rev-parse HEAD", cwd)).out.trim() : "";
|
|
278
|
+
for (const n of names)
|
|
279
|
+
if (state.checks[n]) {
|
|
280
|
+
state.checks[n].wt = fp;
|
|
281
|
+
if (head) state.checks[n].head = head;
|
|
282
|
+
else delete state.checks[n].head;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Green records survive a commit that holds nothing but release prep (the bump, the changelog entry): they
|
|
287
|
+
* are restamped onto the current tree instead of going stale, so the suite does not run twice to prove a
|
|
288
|
+
* version string. Only on a clean tree, only for records taken on a clean tree, and never under
|
|
289
|
+
* `recheck = always`. Returns the names it kept. */
|
|
290
|
+
export async function keepThroughPrep(root: string, state: FlowState, cfg: Config, fp: string | null): Promise<string[]> {
|
|
291
|
+
if (!fp || cfg.release.recheck === "always") return [];
|
|
292
|
+
const cwd = gateCwd(root, state);
|
|
293
|
+
const st = await sh("git status --porcelain", cwd);
|
|
294
|
+
if (!st.ok || st.out.trim()) return [];
|
|
295
|
+
const head = (await sh("git rev-parse HEAD", cwd)).out.trim();
|
|
296
|
+
const kept: string[] = [];
|
|
297
|
+
const verdict = new Map<string, boolean>();
|
|
298
|
+
for (const [name, rec] of Object.entries(state.checks)) {
|
|
299
|
+
if (!rec.ok || !rec.wt || rec.wt === fp || !rec.head || !head) continue;
|
|
300
|
+
if (!verdict.has(rec.head)) {
|
|
301
|
+
const d = await sh(`git diff --name-only ${sq(rec.head)} HEAD`, cwd);
|
|
302
|
+
verdict.set(rec.head, d.ok && prepOnlyChange(cfg, d.out.split("\n").map((l) => l.trim()).filter(Boolean)));
|
|
303
|
+
}
|
|
304
|
+
if (!verdict.get(rec.head)) continue;
|
|
305
|
+
rec.wt = fp;
|
|
306
|
+
rec.head = head;
|
|
307
|
+
rec.prep = true;
|
|
308
|
+
kept.push(name);
|
|
309
|
+
}
|
|
310
|
+
return kept;
|
|
255
311
|
}
|
|
256
312
|
|
|
257
313
|
/** Commits the feature branch holds over its merge base with the default branch, plus how many
|
|
@@ -336,7 +392,41 @@ export async function presentRun(args: string[], root: string, key: string, res:
|
|
|
336
392
|
facts = undefined;
|
|
337
393
|
}
|
|
338
394
|
const view = presentGate(sub, res.text, !!res.isError, state, cfg, facts);
|
|
339
|
-
|
|
395
|
+
// gh#218: a session running an older build than the disk ships must hear it on every gate, not only at
|
|
396
|
+
// start and status — a fix already released never reached the session that needed it
|
|
397
|
+
let agent = agentText(res.text, view);
|
|
398
|
+
if (initiated(root) && !SKEW_SAYS_ITSELF.has(sub)) {
|
|
399
|
+
const skew = buildSkew(root);
|
|
400
|
+
if (skew.line && !agent.includes(skew.line)) agent += `\n${AGENT_MARK}warning: ${skew.line}. Gates in this session run the older build — tell the operator at the next safe point.`;
|
|
401
|
+
}
|
|
402
|
+
return { agent, view };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Gates that print the build skew in their own words. */
|
|
406
|
+
const SKEW_SAYS_ITSELF = new Set(["start", "status", "version", "release", "help"]);
|
|
407
|
+
|
|
408
|
+
/** gh#209: say at check time that the branch fell behind the default branch, and which files both sides
|
|
409
|
+
* touched — verify's rebase is the right convenience, but it must not be where a conflict is first seen.
|
|
410
|
+
* "" when up to date or when git cannot say. Read-only: nothing is rebased or merged here. */
|
|
411
|
+
export async function behindNote(root: string, state: FlowState, cfg: Config): Promise<string> {
|
|
412
|
+
const cwd = gateCwd(root, state);
|
|
413
|
+
if (cwd === root) return "";
|
|
414
|
+
const d = cfg.defaultBranch;
|
|
415
|
+
const hasOrigin = !!(await originUrl(root));
|
|
416
|
+
if (hasOrigin) await sh(`git fetch -q origin ${sq(d)}`, cwd, 20_000);
|
|
417
|
+
const base = hasOrigin && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, cwd)).ok ? `origin/${d}` : d;
|
|
418
|
+
const r = await sh(`git rev-list --count HEAD..${sq(base)}`, cwd);
|
|
419
|
+
const behind = Number.parseInt(r.out.trim(), 10);
|
|
420
|
+
if (!r.ok || !Number.isFinite(behind) || behind === 0) return "";
|
|
421
|
+
const mb = (await sh(`git merge-base HEAD ${sq(base)}`, cwd)).out.trim();
|
|
422
|
+
const names = async (range: string) => new Set(mb ? (await sh(`git diff --name-only ${range}`, cwd)).out.split("\n").map((l) => l.trim()).filter(Boolean) : []);
|
|
423
|
+
const mine = await names(`${sq(mb)} HEAD`);
|
|
424
|
+
const both = [...(await names(`${sq(mb)} ${sq(base)}`))].filter((f) => mine.has(f));
|
|
425
|
+
// merge-tree predicts the conflicts without touching the tree (git ≥ 2.38); an older git just lists the overlap
|
|
426
|
+
const mt = await sh(`git merge-tree --write-tree --name-only --no-messages HEAD ${sq(base)}`, cwd);
|
|
427
|
+
const conflicts = !mt.ok ? mt.out.split("\n").slice(1).map((l) => l.trim()).filter((l) => l && !/^(fatal|error|usage)/i.test(l)) : [];
|
|
428
|
+
const list = (xs: string[]) => `${xs.slice(0, 8).join(", ")}${xs.length > 8 ? ` …(${xs.length - 8} more)` : ""}`;
|
|
429
|
+
return `branch is ${behind} commit(s) behind ${base} — flow verify rebases it before the review deploy${conflicts.length ? `; that rebase would conflict in: ${list(conflicts)} — rebase by hand now (git rebase ${base}) and read what ${d} changed there` : both.length ? `; both sides changed: ${list(both)} (no conflict predicted)` : ""}`;
|
|
340
430
|
}
|
|
341
431
|
|
|
342
432
|
export function describeBranchState(b: BranchState, defaultBranch: string): string {
|
package/src/runtime/gates.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { linkedTag } from "../fold.ts";
|
|
|
7
7
|
import { detectProject } from "../detect.ts";
|
|
8
8
|
import { AGENT_MARK } from "../present.ts";
|
|
9
9
|
import { GATE_HELP, SELF_BUILD, type Ui, buildSkew, copyWarning, currentBranch, dfDir, featDir, featureEnv, flagValue, gateCwd, gitConsistency, initiated, loadedVersion, mergeHistoryEvidence, needState, now, originUrl, publishedVersion, readClaim, readReflections, readReflectionsText, readRoadmap, readState, roadmapFile, sh, stateFile, tail, unfinishedStates, writePlaybookMergePolicy, writeState } from "./base.ts";
|
|
10
|
-
import { type RunResult, type Session, ago, pendingChecks, probeHealth, readDevPorts, runChecks, stampChecks, triedNote } from "./checks.ts";
|
|
10
|
+
import { type RunResult, type Session, ago, behindNote, releaseDevSlot, pendingChecks, probeHealth, readDevPorts, runChecks, stampChecks, triedNote } from "./checks.ts";
|
|
11
11
|
import { GIT_TRACK_NOTE, isSelfRepo, renderQuestions, setupQuestions, tagPatternEvidence } from "./setup.ts";
|
|
12
12
|
import { foldRows, foldView, legacyPluginRows, pluginUpstream, reflectDoneNote, reflectList, reflectMoveNote, reflectNote, reflectTidy } from "./reflect.ts";
|
|
13
13
|
import { gateFinish, gateRelease, gateReleaseDone, gateVerify } from "./ship.ts";
|
|
@@ -281,7 +281,7 @@ export const GRANT_AFTER =
|
|
|
281
281
|
|
|
282
282
|
export async function gateStart(o: GateCtx): Promise<RunResult> {
|
|
283
283
|
const { root, sess, cfg, rest, flag, slugArg } = o;
|
|
284
|
-
if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs
|
|
284
|
+
if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs are a proposal the operator grants with their Approve? answer — name the mode when you ask it; --no-ui on an existing plan-stage feature is operator-granted (ask in chat, then add --confirmed); --ui is yours to pass whenever screens change", isError: true };
|
|
285
285
|
// a ghost (plan/ but no state.json — typically a spin-off someone wrote by hand) is adopted, never a dead end:
|
|
286
286
|
// "already exists, flow use it" sent the agent to use, which found no state, and doctor offered to delete it
|
|
287
287
|
// gh#178: any feature dir without state.json is a ghost, not only one with a plan/ — a tmp/ or mockups
|
|
@@ -320,13 +320,11 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
|
|
|
320
320
|
}
|
|
321
321
|
return { text: `feature ${slugArg} already exists — flow use ${slugArg} to resume it${existing?.stage === "plan" ? `; to add the mockup gate at plan, run flow start ${slugArg} --ui from the session bound to it` : ""}`, isError: true };
|
|
322
322
|
}
|
|
323
|
-
// relaxed
|
|
324
|
-
|
|
323
|
+
// A relaxed mode is a proposal, granted by the Approve? answer: nothing it loosens (no written plan, no
|
|
324
|
+
// tier-1 checks) can happen before approve — the plan stage cannot edit code — so a grant asked at start was
|
|
325
|
+
// a second question with the same decision in it. The approve gate names the mode in what it asks.
|
|
326
|
+
if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — propose one", isError: true };
|
|
325
327
|
const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
|
|
326
|
-
// every grant start needs goes into one question: a refusal for one names the others still open, so
|
|
327
|
-
// the operator answers mode, mockups and merge policy in a single message
|
|
328
|
-
const alsoMerge = !cfg.release.merge && flagValue(rest, "merge") === null ? `\n${AGENT_MARK}the playbook also has no merge policy — put it in the same question (squash | merge | rebase | any) and pass --merge=<style> on the same re-run` : "";
|
|
329
|
-
if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — ${GRANT_AFTER}${alsoMerge}`, isError: true };
|
|
330
328
|
// --ui adds the rendered-mockup gate to plan: stricter, never looser, so the agent turns it on itself
|
|
331
329
|
// whenever screens change — no operator grant (only turning it off is theirs)
|
|
332
330
|
if (flag("no-ui")) return { text: "--no-ui applies to an existing plan-stage feature — a new start is ui-off unless you pass --ui", isError: true };
|
|
@@ -389,6 +387,7 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
|
|
|
389
387
|
writeState(root, state);
|
|
390
388
|
sess.bind(slugArg);
|
|
391
389
|
sess.rename(slugArg);
|
|
390
|
+
if (mode) notes.push(`${mode} mode is proposed, not granted yet — the operator's Approve? answer grants it`);
|
|
392
391
|
return { text: `feature ${slugArg} started at stage plan (ui=${state.ui}${state.patch ? ", patch" : state.docs ? ", docs" : ""}${state.flowVersion ? `, dev-flow ${state.flowVersion}` : ""}); session renamed to ${slugArg}.${notes.length ? `\n${notes.join("\n")}` : ""}\n${AGENT_MARK}next: ${nextHint(state, cfg)}` };
|
|
393
392
|
}
|
|
394
393
|
|
|
@@ -410,7 +409,13 @@ export async function gateApprove(o: GateCtx): Promise<RunResult> {
|
|
|
410
409
|
if (askPending) {
|
|
411
410
|
markPendingAsk(root, state!, "Approve?");
|
|
412
411
|
if (!ui.hasUI) {
|
|
413
|
-
|
|
412
|
+
// a relaxed mode is granted here: the question says what the operator is agreeing to do without
|
|
413
|
+
const what = state!.patch
|
|
414
|
+
? "this is proposed as a patch flow — no written plan, the one-line description is the plan; your answer grants that"
|
|
415
|
+
: state!.docs
|
|
416
|
+
? "this is proposed as a docs flow — no written plan and no build checks; your answer grants that"
|
|
417
|
+
: "the plan is waiting for your approval";
|
|
418
|
+
return { text: needsOperator(what, "Approve?", `${state!.patch || state!.docs ? "say the mode and the one-line change when you ask; " : ""}re-run with --confirmed once the operator answered in chat`), isError: true };
|
|
414
419
|
}
|
|
415
420
|
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." : ""}`);
|
|
416
421
|
if (!ok) {
|
|
@@ -478,7 +483,7 @@ export async function gateStatus(o: GateCtx): Promise<RunResult> {
|
|
|
478
483
|
const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
|
|
479
484
|
return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
|
|
480
485
|
}
|
|
481
|
-
if (!slugs.length) return { text: ["no features in flight — describe what you want built to start one", `${AGENT_MARK}start one: flow start <slug> [--ui] [--patch|--docs
|
|
486
|
+
if (!slugs.length) return { text: ["no features in flight — describe what you want built to start one", `${AGENT_MARK}start one: flow start <slug> [--ui] [--patch|--docs]`, ...warn, ...rmapLine].join("\n") };
|
|
482
487
|
// one readable row per feature for the operator; the identifiers an agent needs stay on agent-only lines
|
|
483
488
|
const lines = slugs.flatMap((s) => {
|
|
484
489
|
const st = readState(root, s);
|
|
@@ -685,7 +690,8 @@ export async function gateCheck(o: GateCtx): Promise<RunResult> {
|
|
|
685
690
|
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)" };
|
|
686
691
|
if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
|
|
687
692
|
const ran = await runChecks(root, state!, cfg, cfg.checkList);
|
|
688
|
-
|
|
693
|
+
const behind = await behindNote(root, state!, cfg);
|
|
694
|
+
return { text: `tier-1 checks:\n${ran.lines.join("\n")}${behind ? `\n${behind}` : ""}`, isError: ran.failed };
|
|
689
695
|
}
|
|
690
696
|
|
|
691
697
|
export async function gateHealth(o: GateCtx): Promise<RunResult> {
|
|
@@ -727,8 +733,8 @@ export async function gateUse(o: GateCtx): Promise<RunResult> {
|
|
|
727
733
|
}
|
|
728
734
|
|
|
729
735
|
export async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
730
|
-
const { root, ui, sess, flag, slugArg } = o;
|
|
731
|
-
// Unbinds the session only; state and worktree stay for manual recovery.
|
|
736
|
+
const { root, ui, sess, cfg, flag, slugArg } = o;
|
|
737
|
+
// Unbinds the session only; state and worktree stay for manual recovery — unless the operator purges it.
|
|
732
738
|
const target = slugArg ?? sess.slug;
|
|
733
739
|
if (!target) return { text: "nothing bound — pass a slug", isError: true };
|
|
734
740
|
const st = readState(root, target);
|
|
@@ -755,9 +761,42 @@ export async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
|
755
761
|
rmSync(featDir(root, target), { recursive: true, force: true });
|
|
756
762
|
return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
|
|
757
763
|
}
|
|
764
|
+
// --purge: an abandoned feature leaves nothing to clean by hand. The agent may not delete a feature folder or
|
|
765
|
+
// force-remove a worktree itself, so the gate does it — on the operator's word, after saying what is lost.
|
|
766
|
+
if (flag("purge") && st?.worktree) {
|
|
767
|
+
if (st.approvals.release) return { text: `${target} is released — flow finish closes it; abort --purge is for a feature that is being dropped`, isError: true };
|
|
768
|
+
const wt = path.resolve(root, st.worktree);
|
|
769
|
+
const ahead = st.branch ? (await sh(`git rev-list --count ${sq(cfg.defaultBranch)}..${sq(st.branch)}`, root)).out.trim() : "";
|
|
770
|
+
const dirtyOut = existsSync(wt) ? (await sh("git status --porcelain", wt)).out : "";
|
|
771
|
+
const dirty = dirtyOut.split("\n").filter((l) => l.trim()).length;
|
|
772
|
+
const onOrigin = !!st.branch && !!(await originUrl(root)) && (await sh(`git ls-remote --heads origin ${sq(st.branch)}`, root, 30_000)).out.includes(`refs/heads/${st.branch}`);
|
|
773
|
+
const lost = [
|
|
774
|
+
/^\d+$/.test(ahead) ? `${ahead} commit(s) on ${st.branch} that are not on ${cfg.defaultBranch}` : `branch ${st.branch || "-"}`,
|
|
775
|
+
dirty ? `${dirty} uncommitted path(s) in the worktree` : "",
|
|
776
|
+
`the plan and state in .dev-flow/${target}/`,
|
|
777
|
+
].filter(Boolean).join(", ");
|
|
778
|
+
const publishedNote = st.stage === "release" ? " Its release was approved: a PR, a merge or a tag may already be on the forge — purge removes none of that." : "";
|
|
779
|
+
const remoteNote = onOrigin ? ` origin/${st.branch} is left alone (remove it with: git push origin --delete ${st.branch}).` : "";
|
|
780
|
+
if (!flag("confirmed")) {
|
|
781
|
+
const ok = ui.hasUI && (await ui.confirm("Purge feature?", `Purge ${target}? This removes for good: ${lost}.${publishedNote}${remoteNote}`));
|
|
782
|
+
if (!ok) return { text: needsOperator(`purging ${target} removes for good: ${lost}.${publishedNote}${remoteNote}`, "Purge?", "ask the operator, then re-run flow abort --purge --confirmed"), isError: true };
|
|
783
|
+
}
|
|
784
|
+
const devNote = await releaseDevSlot(root, st, cfg);
|
|
785
|
+
if (existsSync(wt)) {
|
|
786
|
+
const rm = await sh(`git worktree remove --force ${sq(wt)}`, root);
|
|
787
|
+
if (!rm.ok) return { text: `purge stopped — worktree removal failed, nothing else was removed:\n${tail(rm.out)}\nif files are owned by another user (e.g. root-owned docker build output), remove ${st.worktree} by hand and re-run`, isError: true };
|
|
788
|
+
} else await sh("git worktree prune", root);
|
|
789
|
+
const brNote = st.branch && (await sh(`git rev-parse --verify --quiet ${sq(`refs/heads/${st.branch}`)}`, root)).ok
|
|
790
|
+
? (await sh(`git branch -D ${sq(st.branch)}`, root)).ok ? `, branch ${st.branch} deleted` : `, branch ${st.branch} could not be deleted (git branch -D ${st.branch})`
|
|
791
|
+
: "";
|
|
792
|
+
if (sess.slug === target) sess.bind(null);
|
|
793
|
+
rmSync(featureTmpDir(dfDir(root), target), { recursive: true, force: true });
|
|
794
|
+
rmSync(featDir(root, target), { recursive: true, force: true });
|
|
795
|
+
return { text: `purged ${target} — worktree removed${brNote}; .dev-flow/${target}/ removed.${devNote}${remoteNote}${publishedNote}` };
|
|
796
|
+
}
|
|
758
797
|
if (sess.slug === target) sess.bind(null);
|
|
759
798
|
// the scratch dir is the bound session's working junk — it does not outlive the binding
|
|
760
799
|
rmSync(featureTmpDir(dfDir(root), target), { recursive: true, force: true });
|
|
761
800
|
if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
|
|
762
|
-
return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and
|
|
801
|
+
return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree, branch and feature folder: ask the operator, then flow abort ${target} --purge --confirmed on their word` : "") };
|
|
763
802
|
}
|
package/src/runtime/grants.ts
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
*
|
|
6
6
|
* A. a gate asked for the operator's word (NEEDS-OPERATOR, or an "operator-granted" refusal) and the same
|
|
7
7
|
* gate is re-run with --confirmed before any operator message arrived;
|
|
8
|
-
* B. a feature started in this session
|
|
9
|
-
*
|
|
8
|
+
* B. a feature started in this session has its mockup gate dropped (--no-ui) with --confirmed before any
|
|
9
|
+
* operator message arrived after the start. (--patch/--docs need no grant at start: the Approve? answer
|
|
10
|
+
* grants them, and rule A binds that.)
|
|
10
11
|
*
|
|
11
12
|
* --confirmed is not the only answer a gate takes: `Dev port?` is answered with --replace or --port=<n>
|
|
12
13
|
* (gh#203), and those bind the same way — a re-run of the gate that asked, carrying any of them, needs
|
|
@@ -38,8 +39,9 @@ export interface GrantLedger {
|
|
|
38
39
|
export const newGrantLedger = (): GrantLedger => ({ asked: new Map(), started: new Map() });
|
|
39
40
|
|
|
40
41
|
const ASKS_FOR_WORD = /operator-granted|operator's (?:explicit )?word|the operator must grant/;
|
|
41
|
-
/** Mode flags that loosen a gate
|
|
42
|
-
|
|
42
|
+
/** Mode flags that loosen a gate and need a grant of their own. --ui only tightens one; --patch and --docs
|
|
43
|
+
* are granted by the Approve? answer, which rule A already binds; --no-ui (dropping the mockup gate) is the one left. */
|
|
44
|
+
const MODE_FLAGS = ["--no-ui"];
|
|
43
45
|
/** Flags that carry the operator's answer to the question a gate asked — `--confirmed`, and the
|
|
44
46
|
* `Dev port?` answers (gh#203). */
|
|
45
47
|
export function answerFlags(args: readonly string[]): string[] {
|
|
@@ -74,3 +76,35 @@ export function grantRecord(args: readonly string[], key: string, users: number
|
|
|
74
76
|
if (!res.isError && ledger.asked.get(key)?.sub === sub) ledger.asked.delete(key);
|
|
75
77
|
if (!res.isError && sub === "start" && /\bstarted at stage\b/.test(res.text)) ledger.started.set(`${key}\u0000${slugOf(args)}`, users);
|
|
76
78
|
}
|
|
79
|
+
|
|
80
|
+
/** A refusal that is the work failing, not the process: a red test, a broken build, a deploy that did not come up. */
|
|
81
|
+
const WORK_FAILURE = /check run at the gate failed|\bbuild FAILED\b|dev deploy FAILED|probe FAILED|served-build check FAILED|after-merge check "[^"]*" failed|has not passed|publish stopped — PR #\d+ checks failed/;
|
|
82
|
+
/** The release gate still waiting on CI: re-running it is the instruction, never a sign the agent is stuck. */
|
|
83
|
+
const WAITING = /(?:^|\n)publish waiting —/;
|
|
84
|
+
/** `flow check|test|health` reporting a red run — the answer those tools exist to give. A refusal from them that
|
|
85
|
+
* is not a run (nothing configured, no feature bound) stays friction. */
|
|
86
|
+
const RED_RUN = /^(?:tier-1 checks:|test: FAIL|health: FAIL)/;
|
|
87
|
+
const CHECK_SUBS = new Set(["check", "test", "health"]);
|
|
88
|
+
|
|
89
|
+
/** Refusals in a row per session and gate — the second one in a row is what makes a work failure friction. */
|
|
90
|
+
export type RefusalStreak = Map<string, { sub: string; n: number }>;
|
|
91
|
+
|
|
92
|
+
/** Is this flow result friction the closing reflection should look at? A question for the operator is not, and
|
|
93
|
+
* neither is a failing check: finding red tests is what `flow check` is for, and counting it made nearly every
|
|
94
|
+
* flow "have friction", so the reflection worker ran on flows that had none. Friction is a self-granted
|
|
95
|
+
* answer, a process refusal (wrong stage, missing plan, a proof that does not hold), or the same gate
|
|
96
|
+
* refusing twice in a row whatever the cause — the agent is stuck on it. */
|
|
97
|
+
export function isFriction(args: readonly string[], key: string, res: { text: string; isError?: boolean }, selfGrant: boolean, streak: RefusalStreak): boolean {
|
|
98
|
+
const sub = args[0] ?? "";
|
|
99
|
+
if (selfGrant) return true;
|
|
100
|
+
if (!res.isError) {
|
|
101
|
+
if (streak.get(key)?.sub === sub) streak.delete(key);
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
if (res.text.startsWith(NEEDS_OPERATOR) || WAITING.test(res.text)) return false;
|
|
105
|
+
if (CHECK_SUBS.has(sub) && RED_RUN.test(res.text)) return false;
|
|
106
|
+
const prev = streak.get(key);
|
|
107
|
+
const n = prev?.sub === sub ? prev.n + 1 : 1;
|
|
108
|
+
streak.set(key, { sub, n });
|
|
109
|
+
return n >= 2 || !WORK_FAILURE.test(res.text);
|
|
110
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/** dev-flow runtime — the release stage, run by the gate. After Release? is answered the agent used to push,
|
|
2
|
+
* open the PR, watch CI, merge in the playbook's style, tag and push the tag by hand; most of release.md was a
|
|
3
|
+
* list of past mistakes in those steps. `flow release` now runs them itself on GitHub. Every step first asks
|
|
4
|
+
* the forge whether it is already done, so a re-run resumes and a step done by hand is accepted. */
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { pickReleaseNotes, prepOnlyChange, sq } from "../core.ts";
|
|
8
|
+
import type { Config, FlowState } from "../core.ts";
|
|
9
|
+
import { gateCwd, mergeBase, releaseTags, sh, tail, writeState } from "./base.ts";
|
|
10
|
+
|
|
11
|
+
/** How long the gate waits on a PR's CI; a seam so tests run in milliseconds (same shape as artifactWait). */
|
|
12
|
+
export const publishWait = {
|
|
13
|
+
budgetMs: 30 * 60_000,
|
|
14
|
+
pollMs: 20_000,
|
|
15
|
+
/** a PR opened seconds ago may have no check yet: look this long before deciding the repo has none */
|
|
16
|
+
appearMs: 60_000,
|
|
17
|
+
sleep: (ms: number) => new Promise<void>((r) => setTimeout(r, ms)),
|
|
18
|
+
clock: () => Date.now(),
|
|
19
|
+
checks: (pr: number, cwd: string): Promise<PrCheck[] | null> => prChecks(pr, cwd),
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export interface PrCheck { name: string; bucket: string; link: string }
|
|
23
|
+
interface Pr { number: number; state: string; url: string; headRefOid: string; mergeCommit: { oid: string } | null }
|
|
24
|
+
|
|
25
|
+
/** The first JSON array in a CLI's output — sh() folds stderr in, and gh exits non-zero on pending checks. */
|
|
26
|
+
function jsonArray<T>(out: string): T[] | null {
|
|
27
|
+
const at = out.indexOf("[");
|
|
28
|
+
if (at < 0) return null;
|
|
29
|
+
for (let end = out.lastIndexOf("]"); end > at; end = out.lastIndexOf("]", end - 1)) {
|
|
30
|
+
try {
|
|
31
|
+
const v = JSON.parse(out.slice(at, end + 1)) as unknown;
|
|
32
|
+
if (Array.isArray(v)) return v as T[];
|
|
33
|
+
} catch {
|
|
34
|
+
/* a shorter slice may parse */
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One entry of GitHub's status rollup: a check run (Actions, apps) or a commit status (older CI). */
|
|
41
|
+
interface RollupItem { __typename?: string; name?: string; context?: string; status?: string; conclusion?: string; state?: string; detailsUrl?: string; targetUrl?: string }
|
|
42
|
+
|
|
43
|
+
/** A rollup entry as pass | fail | cancel | skipping | pending. */
|
|
44
|
+
export function checkBucket(c: RollupItem): string {
|
|
45
|
+
if (c.__typename === "StatusContext" || (c.state && !c.status)) {
|
|
46
|
+
const st = (c.state ?? "").toUpperCase();
|
|
47
|
+
return st === "SUCCESS" ? "pass" : st === "FAILURE" || st === "ERROR" ? "fail" : "pending";
|
|
48
|
+
}
|
|
49
|
+
if ((c.status ?? "").toUpperCase() !== "COMPLETED") return "pending";
|
|
50
|
+
const k = (c.conclusion ?? "").toUpperCase();
|
|
51
|
+
if (k === "SUCCESS") return "pass";
|
|
52
|
+
if (k === "SKIPPED" || k === "NEUTRAL") return "skipping";
|
|
53
|
+
if (k === "CANCELLED") return "cancel";
|
|
54
|
+
return "fail"; // FAILURE, TIMED_OUT, ACTION_REQUIRED, STARTUP_FAILURE, STALE
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The PR's checks; [] when the forge reports none, null when gh cannot say. `gh pr view --json
|
|
58
|
+
* statusCheckRollup` and not `gh pr checks --json`: older gh builds have no --json on pr checks. */
|
|
59
|
+
async function prChecks(pr: number, cwd: string): Promise<PrCheck[] | null> {
|
|
60
|
+
const r = await sh(`gh pr view ${pr} --json statusCheckRollup`, cwd, 60_000);
|
|
61
|
+
if (!r.ok) return null;
|
|
62
|
+
try {
|
|
63
|
+
const rows = (JSON.parse(r.out.slice(r.out.indexOf("{"), r.out.lastIndexOf("}") + 1)) as { statusCheckRollup?: RollupItem[] | null }).statusCheckRollup;
|
|
64
|
+
return (rows ?? []).map((c) => ({ name: c.name ?? c.context ?? "check", bucket: checkBucket(c), link: c.detailsUrl ?? c.targetUrl ?? "" }));
|
|
65
|
+
} catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type CiVerdict = { state: "green" | "none"; note: string } | { state: "red" | "running" | "unknown"; why: string };
|
|
71
|
+
|
|
72
|
+
/** Wait (bounded) for the PR's checks to settle. */
|
|
73
|
+
export async function awaitPrChecks(pr: number, cwd: string): Promise<CiVerdict> {
|
|
74
|
+
const start = publishWait.clock();
|
|
75
|
+
const mins = () => `${Math.max(1, Math.round((publishWait.clock() - start) / 60_000))} min`;
|
|
76
|
+
for (;;) {
|
|
77
|
+
const rows = await publishWait.checks(pr, cwd);
|
|
78
|
+
const elapsed = publishWait.clock() - start;
|
|
79
|
+
if (rows === null) return { state: "unknown", why: `cannot read the checks of PR #${pr} (gh pr view ${pr} --json statusCheckRollup)` };
|
|
80
|
+
if (!rows.length) {
|
|
81
|
+
if (elapsed >= publishWait.appearMs) return { state: "none", note: "no CI checks on the PR" };
|
|
82
|
+
} else {
|
|
83
|
+
const failed = rows.filter((c) => c.bucket === "fail" || c.bucket === "cancel");
|
|
84
|
+
if (failed.length) return { state: "red", why: `PR #${pr} checks failed — ${failed.map((c) => `${c.name}: ${c.bucket}${c.link ? ` (${c.link})` : ""}`).join(", ")}` };
|
|
85
|
+
const pending = rows.filter((c) => c.bucket !== "pass" && c.bucket !== "skipping");
|
|
86
|
+
if (!pending.length) return { state: "green", note: `CI green (${rows.length} check${rows.length === 1 ? "" : "s"}${elapsed >= 60_000 ? `, waited ${mins()}` : ""})` };
|
|
87
|
+
if (elapsed >= publishWait.budgetMs) return { state: "running", why: `PR #${pr} checks still running after ${mins()} (${pending.map((c) => c.name).join(", ")})` };
|
|
88
|
+
}
|
|
89
|
+
await publishWait.sleep(publishWait.pollMs);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Does the gate publish this flow itself? Only on GitHub with a working gh, and unless the playbook says manual. */
|
|
94
|
+
export async function gatePublishes(cfg: Config, forgeName: string, root: string): Promise<boolean> {
|
|
95
|
+
if (cfg.release.publish === "manual" || forgeName !== "github") return false;
|
|
96
|
+
return (await sh("gh --version", root, 15_000)).ok;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function prsFor(branch: string, cwd: string): Promise<Pr[] | null> {
|
|
100
|
+
const r = await sh(`gh pr list --head ${sq(branch)} --state all --limit 20 --json number,state,url,headRefOid,mergeCommit`, cwd, 60_000);
|
|
101
|
+
return r.ok ? jsonArray<Pr>(r.out) ?? (r.out.trim() ? null : []) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Title for the PR: the newest commit on the branch that is more than release prep. */
|
|
105
|
+
async function prTitle(cwd: string, cfg: Config, slug: string): Promise<string> {
|
|
106
|
+
const base = await mergeBase(cwd, cfg.defaultBranch);
|
|
107
|
+
const log = await sh(`git log -n 30 --format=%H%x09%s ${base ? `${sq(base)}..HEAD` : "HEAD"}`, cwd);
|
|
108
|
+
const rows = log.ok ? log.out.split("\n").filter(Boolean).map((l) => l.split("\t")) : [];
|
|
109
|
+
for (const [sha, subject] of rows) {
|
|
110
|
+
const files = (await sh(`git diff-tree --no-commit-id --name-only -r ${sq(sha)}`, cwd)).out.split("\n").filter(Boolean);
|
|
111
|
+
if (!prepOnlyChange(cfg, files)) return subject;
|
|
112
|
+
}
|
|
113
|
+
return rows[0]?.[1] ?? slug;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Body for the PR: the changelog entry of the version being released, else the branch's commit subjects. */
|
|
117
|
+
async function prBody(cwd: string, cfg: Config, state: FlowState): Promise<string> {
|
|
118
|
+
const file = cfg.release.changelog ? path.join(cwd, cfg.release.changelog) : "";
|
|
119
|
+
const entry = pickReleaseNotes({ changelog: file && existsSync(file) ? readFileSync(file, "utf8") : null, version: state.releaseVersion ?? null, annotation: "" }).notes;
|
|
120
|
+
if (entry) return entry;
|
|
121
|
+
const base = await mergeBase(cwd, cfg.defaultBranch);
|
|
122
|
+
const log = await sh(`git log -n 30 --format='- %s' ${base ? `${sq(base)}..HEAD` : "HEAD"}`, cwd);
|
|
123
|
+
return log.ok ? log.out.trim() : "";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type PublishResult = { ok: true; log: string } | { ok: false; text: string };
|
|
127
|
+
|
|
128
|
+
/** Push, PR, CI, merge, tag — each step skipped when the forge already shows it done. On success the caller
|
|
129
|
+
* records the release (release-done's proofs). A refusal starts with `publish stopped —` (something to fix)
|
|
130
|
+
* or `publish waiting —` (CI still running: re-run to keep waiting). */
|
|
131
|
+
export async function publishRelease(root: string, state: FlowState, cfg: Config): Promise<PublishResult> {
|
|
132
|
+
const wt = gateCwd(root, state);
|
|
133
|
+
const br = state.branch;
|
|
134
|
+
const steps: string[] = [];
|
|
135
|
+
const stop = (why: string, next: string): PublishResult => ({ ok: false, text: `publish stopped — ${why}${steps.length ? `\ndone so far: ${steps.join(" · ")}` : ""}\n↪ next: ${next}; then re-run flow release — it resumes where it stopped` });
|
|
136
|
+
if (!br) return stop("the feature has no branch on record", "check flow status");
|
|
137
|
+
const head = (await sh("git rev-parse HEAD", wt)).out.trim();
|
|
138
|
+
const find = async (): Promise<{ merged?: Pr; open?: Pr } | null> => {
|
|
139
|
+
const prs = await prsFor(br, wt);
|
|
140
|
+
if (!prs) return null;
|
|
141
|
+
// a slug used before has an old merged PR under the same branch name: only a PR of this head counts
|
|
142
|
+
return { merged: prs.find((p) => p.state === "MERGED" && p.headRefOid === head), open: prs.find((p) => p.state === "OPEN") };
|
|
143
|
+
};
|
|
144
|
+
let found = await find();
|
|
145
|
+
if (!found) return stop(`cannot list the pull requests of ${br} (gh pr list)`, "check gh auth status");
|
|
146
|
+
let merged = found.merged;
|
|
147
|
+
if (merged) steps.push(`PR #${merged.number} already merged`);
|
|
148
|
+
else {
|
|
149
|
+
const remote = await sh(`git ls-remote origin ${sq(`refs/heads/${br}`)}`, wt, 60_000);
|
|
150
|
+
if (!remote.ok) return stop(`cannot reach origin:\n${tail(remote.out, 5)}`, "check the network and git credentials");
|
|
151
|
+
if (remote.out.split(/\s/)[0] === head) steps.push("branch already on origin");
|
|
152
|
+
else {
|
|
153
|
+
const push = await sh(`git push -u origin ${sq(br)}`, wt);
|
|
154
|
+
if (!push.ok) return stop(`pushing ${br} failed:\n${tail(push.out, 8)}`, `push the branch yourself (a branch rebased after an earlier push needs git push --force-with-lease origin ${br})`);
|
|
155
|
+
steps.push("branch pushed");
|
|
156
|
+
}
|
|
157
|
+
let pr = found.open;
|
|
158
|
+
if (pr) steps.push(`PR #${pr.number} already open`);
|
|
159
|
+
else {
|
|
160
|
+
const body = await prBody(wt, cfg, state);
|
|
161
|
+
const create = await sh(`gh pr create --head ${sq(br)} --base ${sq(cfg.defaultBranch)} --title ${sq(await prTitle(wt, cfg, state.slug))} --body ${sq(body || state.slug)}`, wt);
|
|
162
|
+
if (!create.ok) return stop(`opening the PR failed:\n${tail(create.out, 8)}`, "open the PR yourself");
|
|
163
|
+
found = await find();
|
|
164
|
+
pr = found?.open;
|
|
165
|
+
if (!pr) return stop("the PR was created but gh pr list does not show it yet", "wait a moment");
|
|
166
|
+
steps.push(`PR #${pr.number} opened`);
|
|
167
|
+
}
|
|
168
|
+
state.publish = { ...state.publish, pr: pr.number };
|
|
169
|
+
writeState(root, state);
|
|
170
|
+
const ci = await awaitPrChecks(pr.number, wt);
|
|
171
|
+
if (!("why" in ci)) steps.push(ci.note);
|
|
172
|
+
else if (ci.state === "running") return { ok: false, text: `publish waiting — ${ci.why}${steps.length ? `\ndone so far: ${steps.join(" · ")}` : ""}\n↪ next: re-run flow release to keep waiting — do not end the turn on a promise to watch` };
|
|
173
|
+
else if (ci.state === "red") return stop(ci.why, "fix it on the branch (commit, flow release pushes it) or re-run the failed job");
|
|
174
|
+
else return stop(ci.why, "check gh auth status, or merge the PR yourself once CI is green");
|
|
175
|
+
const policy = cfg.release.merge && cfg.release.merge !== "any" ? [cfg.release.merge] : (["merge", "squash", "rebase"] as const);
|
|
176
|
+
let mergeOut = "";
|
|
177
|
+
let style = "";
|
|
178
|
+
for (const s of policy) {
|
|
179
|
+
const m = await sh(`gh pr merge ${pr.number} --${s}`, wt);
|
|
180
|
+
if (m.ok) {
|
|
181
|
+
style = s;
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
mergeOut = m.out;
|
|
185
|
+
}
|
|
186
|
+
if (!style) return stop(`merging PR #${pr.number} failed${policy.length === 1 ? ` (--${policy[0]})` : ""}:\n${tail(mergeOut, 8)}`, `get the PR merged (a required review or a merge queue is the forge's rule, not the gate's)`);
|
|
187
|
+
// the forge may take a moment to report the merge commit
|
|
188
|
+
for (let i = 0; i < 6 && !merged; i++) {
|
|
189
|
+
merged = (await find())?.merged;
|
|
190
|
+
if (!merged?.mergeCommit?.oid) {
|
|
191
|
+
merged = undefined;
|
|
192
|
+
await publishWait.sleep(2_000);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (!merged) return stop(`PR #${pr.number} was merged but the forge does not show its merge commit yet`, "wait a moment");
|
|
196
|
+
steps.push(`merged (${style})`);
|
|
197
|
+
}
|
|
198
|
+
const oid = merged.mergeCommit?.oid ?? "";
|
|
199
|
+
state.publish = { ...state.publish, pr: merged.number, merged: oid };
|
|
200
|
+
writeState(root, state);
|
|
201
|
+
await sh(`git fetch -q origin ${sq(cfg.defaultBranch)}`, root, 5 * 60_000);
|
|
202
|
+
if (state.releaseVersion && !state.noVersion) {
|
|
203
|
+
const tag = cfg.versioning.pattern.replace("{version}", state.releaseVersion);
|
|
204
|
+
const tags = await releaseTags(root);
|
|
205
|
+
if (tags === null) return stop("cannot list tags on origin", "check the network and git credentials");
|
|
206
|
+
if (tags.includes(tag)) steps.push(`tag ${tag} already on origin`);
|
|
207
|
+
else {
|
|
208
|
+
if (!oid) return stop(`PR #${merged.number} shows no merge commit to tag`, `tag what shipped yourself (git tag -a ${tag}) and push it`);
|
|
209
|
+
if (!(await sh(`git cat-file -e ${sq(`${oid}^{commit}`)}`, root)).ok) return stop(`the merge commit ${oid.slice(0, 9)} of PR #${merged.number} is not in this clone after a fetch`, `git fetch origin ${cfg.defaultBranch}`);
|
|
210
|
+
if (!(await sh(`git rev-parse -q --verify ${sq(`refs/tags/${tag}`)}`, root)).ok) {
|
|
211
|
+
// the merge commit by sha, not origin/<default>: a parallel flow that landed after it stays out of the tag
|
|
212
|
+
const mk = await sh(`git tag -a ${sq(tag)} -m ${sq(tag)} ${sq(oid)}`, root);
|
|
213
|
+
if (!mk.ok) return stop(`creating tag ${tag} failed:\n${tail(mk.out, 5)}`, "fix what git reports");
|
|
214
|
+
}
|
|
215
|
+
const pushTag = await sh(`git push origin ${sq(`refs/tags/${tag}`)}`, root);
|
|
216
|
+
if (!pushTag.ok) return stop(`pushing tag ${tag} failed:\n${tail(pushTag.out, 5)}`, `git push origin ${tag}`);
|
|
217
|
+
steps.push(`tag ${tag} pushed`);
|
|
218
|
+
}
|
|
219
|
+
state.publish = { ...state.publish, tag };
|
|
220
|
+
writeState(root, state);
|
|
221
|
+
}
|
|
222
|
+
return { ok: true, log: `published: ${steps.join(" · ")}` };
|
|
223
|
+
}
|
package/src/runtime/reflect.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResu
|
|
|
6
6
|
import { dfDir, now, originUrl, readReflections, readReflectionsText, sh } from "./base.ts";
|
|
7
7
|
import { type RunResult, type Session } from "./checks.ts";
|
|
8
8
|
import { isSelfRepo } from "./setup.ts";
|
|
9
|
+
import { AGENT_MARK } from "../present.ts";
|
|
9
10
|
|
|
10
11
|
/** The dev-flow repo plugin notes are filed against: the manifest's repository field; the dev-flow
|
|
11
12
|
* checkout itself falls back to its origin. */
|
|
@@ -93,6 +94,8 @@ export async function reflectList(root: string): Promise<RunResult> {
|
|
|
93
94
|
const link = fold.state === "ok" ? fold.result.linked.find((l) => l.item === i) : undefined;
|
|
94
95
|
return ` ${it.n}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}${link ? linkedTag(link.issue) : ""}`;
|
|
95
96
|
}),
|
|
97
|
+
// gh#220: the command that closes a row has to be in front of the session that is about to hand-edit the file
|
|
98
|
+
`${AGENT_MARK}close fixed rows with flow reflect done <n>[,<n>…] "<what fixed it>" — never by editing reflections.md`,
|
|
96
99
|
]
|
|
97
100
|
: fold.state === "absent" || fold.state === "skipped"
|
|
98
101
|
? ["reflections: nothing open"]
|
|
@@ -148,15 +151,23 @@ function noOpenRow(text: string, n: number, items: readonly ReflectItem[]): stri
|
|
|
148
151
|
export function reflectDoneNote(root: string, sess: Session, args: string[]): RunResult {
|
|
149
152
|
const text = readReflectionsText(root);
|
|
150
153
|
const items = reflectItems(text);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
+
// gh#220: a fold closes several rows with one fix — `done 3,4,7 "<what>"` checks them off together. Checking a
|
|
155
|
+
// row off leaves the other numbers as they are, so the batch is all or nothing: one bad number closes none.
|
|
156
|
+
const nums = [...new Set(String(args[0] ?? "").split(",").map((p) => p.trim()).filter(Boolean).map(Number))];
|
|
157
|
+
if (!nums.length) return { text: 'usage: flow reflect done <n>[,<n>…] "<what fixed it>"', isError: true };
|
|
158
|
+
const picked = nums.map((n) => ({ n, it: items.find((x) => x.n === n) }));
|
|
159
|
+
const bad = picked.filter((p) => !p.it);
|
|
160
|
+
if (bad.length) return { text: `done: ${bad.map((p) => noOpenRow(text, p.n, items)).join("; ")}${nums.length > 1 ? " — nothing was checked off" : ""}`, isError: true };
|
|
154
161
|
const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
|
|
155
162
|
const what = args.slice(1).join(" ").trim();
|
|
156
|
-
|
|
163
|
+
let next = text;
|
|
164
|
+
for (const n of nums) next = reflectDone(next, n, what ? `${stamp} — ${what}` : stamp)!;
|
|
157
165
|
writeFileSync(path.join(dfDir(root), "reflections.md"), next);
|
|
158
166
|
const { tidy } = reflectionNudges(next, now().slice(0, 10));
|
|
159
|
-
|
|
167
|
+
const head = nums.length === 1
|
|
168
|
+
? `reflect: item ${nums[0]} checked off — ${picked[0].it!.body}${what ? ` — fixed: ${what}` : ""}`
|
|
169
|
+
: `reflect: ${nums.length} items checked off${what ? ` — fixed: ${what}` : ""}\n${picked.map((p) => ` ${p.n}. ${p.it!.body}`).join("\n")}`;
|
|
170
|
+
return { text: head + (tidy ? `\n${tidy}` : "") };
|
|
160
171
|
}
|
|
161
172
|
|
|
162
173
|
/** `flow reflect tidy` — drop the closed (`- [x]`) items; the `— fixed:` note already recorded the outcome. */
|