pi-dev-flow 0.94.3 → 0.95.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/docs/gates.md +8 -4
- package/docs/playbook.md +1 -0
- package/docs/reflections.md +9 -4
- package/extensions/dev-flow.ts +35 -10
- package/package.json +1 -1
- package/skills/dev-flow/references/implement.md +4 -2
- package/skills/dev-flow/references/reflect.md +22 -10
- package/skills/dev-flow/references/release.md +3 -2
- package/src/core.ts +272 -25
- package/src/projectmd.ts +5 -0
- package/src/runtime/base.ts +41 -7
- package/src/runtime/checks.ts +2 -2
- package/src/runtime/gates.ts +54 -12
- package/src/runtime/publish.ts +61 -7
- package/src/runtime/reflect.ts +141 -26
- package/src/runtime/setup.ts +1 -1
- package/src/runtime/ship.ts +14 -5
package/src/runtime/gates.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/** dev-flow runtime — The gate runner and the gates that do not ship anything. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
2
|
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { approveGate, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapOpenRows, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState } from "../core.ts";
|
|
4
|
+
import { skipsChecks, approveGate, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapOpenRows, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState, parseRowIds, DF_GITIGNORE } from "../core.ts";
|
|
5
5
|
import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, ghostInfo, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
|
|
6
6
|
import { linkedTag } from "../fold.ts";
|
|
7
7
|
import { detectProject } from "../detect.ts";
|
|
8
8
|
import { AGENT_MARK } from "../present.ts";
|
|
9
|
-
import { GATE_HELP, SELF_BUILD, type Ui, buildSkew, copyWarning, currentBranch, dfDir, featDir, featureEnv, flagValue, gateCwd, gitConsistency, initiated, loadedVersion, mergeHistoryEvidence, needState, now, originUrl, publishedVersion, readClaim, readReflections, readReflectionsText, readRoadmap, readState, roadmapFile, sh, stateFile, tail, unfinishedStates, writePlaybookMergePolicy, writeState } from "./base.ts";
|
|
9
|
+
import { GATE_HELP, SELF_BUILD, refreshDocsCode, 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
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
|
-
import { foldRows, foldView, legacyPluginRows, pluginUpstream, reflectDoneNote, reflectList, reflectMoveNote, reflectNote, reflectTidy } from "./reflect.ts";
|
|
12
|
+
import { foldRows, foldView, legacyPluginRows, pluginUpstream, reflectDeferNote, reflectDoneNote, reflectList, reflectMoveNote, reflectNote, reflectPlanNote, reflectReopenNote, reflectSameNote, reflectTidy } from "./reflect.ts";
|
|
13
13
|
import { gateFinish, gateRelease, gateReleaseDone, gateVerify } from "./ship.ts";
|
|
14
14
|
|
|
15
15
|
/** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
|
|
@@ -17,6 +17,19 @@ export interface FlowHooks {
|
|
|
17
17
|
reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean }>;
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
/** Write `.dev-flow/.gitignore` when it is missing; true when it did. Best effort — never fails a gate. */
|
|
21
|
+
export function healDfIgnore(root: string): boolean {
|
|
22
|
+
const gi = path.join(dfDir(root), ".gitignore");
|
|
23
|
+
if (existsSync(gi)) return false;
|
|
24
|
+
try {
|
|
25
|
+
writeFileSync(gi, DF_GITIGNORE);
|
|
26
|
+
return true;
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const HEALED_NOTE = `restored .dev-flow/.gitignore — it was missing (a fresh clone does not carry an untracked one), so every feature dir under .dev-flow/ showed as uncommitted work\n${AGENT_MARK}track it so the next clone keeps it — tell the operator, and on their word: git add -f .dev-flow/.gitignore, then (a separate call — the file ignores itself, so it shows as a playbook chore only once staged) DEV_FLOW_ALLOW_MAIN=1 git commit -m "track .dev-flow/.gitignore" -- .dev-flow/.gitignore`;
|
|
32
|
+
|
|
20
33
|
/** Single runner for both the /flow command and the flow tool. */
|
|
21
34
|
export async function runFlow(args: string[], root: string, ui: Ui, sess: Session, hooks: FlowHooks = {}): Promise<RunResult> {
|
|
22
35
|
const [sub = "status", ...rest] = args;
|
|
@@ -24,6 +37,13 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
|
|
|
24
37
|
if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, loadedVersion()) : `usage: flow <sub> — ${GATE_HELP}` };
|
|
25
38
|
// an uninitiated folder is dormant: every gate verb but init and version needs the operator playbook (project.md)
|
|
26
39
|
if (!initiated(root) && sub !== "init" && sub !== "version") return { text: "dev-flow is not initiated here — no .dev-flow/project.md — run flow init first", isError: true };
|
|
40
|
+
// the folder's ignore file is dev-flow's, and its content never varies: a clone that lost it is healed here,
|
|
41
|
+
// before any gate reads git status (finish's clean-checkout proof, doctor's tracking probe)
|
|
42
|
+
const healed = sub !== "init" && sub !== "version" ? healDfIgnore(root) : false;
|
|
43
|
+
if (healed) {
|
|
44
|
+
const res = await runFlow(args, root, ui, sess, hooks);
|
|
45
|
+
return { ...res, text: `${res.text}\n${HEALED_NOTE}` };
|
|
46
|
+
}
|
|
27
47
|
const cfg = loadProject(dfDir(root)).cfg;
|
|
28
48
|
const flag = (name: string) => rest.includes(`--${name}`);
|
|
29
49
|
// the yolo word at Verified?/Release?/Finish?: the operator said it in chat, then re-run with --confirmed; checks and guardrails stay enforced
|
|
@@ -127,7 +147,7 @@ export async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
127
147
|
mkdirSync(dfDir(root), { recursive: true });
|
|
128
148
|
const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
|
|
129
149
|
// self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
|
|
130
|
-
writeFileSync(path.join(dfDir(root), ".gitignore"),
|
|
150
|
+
writeFileSync(path.join(dfDir(root), ".gitignore"), DF_GITIGNORE);
|
|
131
151
|
const mdFile = path.join(dfDir(root), "project.md");
|
|
132
152
|
const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
|
|
133
153
|
const curBr = await currentBranch(root);
|
|
@@ -175,8 +195,9 @@ export async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
175
195
|
notes.push(GIT_TRACK_NOTE, AGENT_MARK + "(or re-run the same call with --track on the operator's word)");
|
|
176
196
|
return;
|
|
177
197
|
}
|
|
178
|
-
|
|
179
|
-
|
|
198
|
+
// the folder's ignore file rides along: untracked, a fresh clone lost it and every feature dir became "uncommitted"
|
|
199
|
+
const c = await sh(`git add -f .dev-flow/project.md .dev-flow/.gitignore && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(before ? "chore: update dev-flow playbook" : "chore: add dev-flow playbook")} -- .dev-flow/project.md .dev-flow/.gitignore`, root, 60_000);
|
|
200
|
+
notes.push(c.ok ? "project.md and .dev-flow/.gitignore committed (git add -f + playbook chore)" : `commit failed — ${c.out.split("\n").find(Boolean) ?? "?"}; ${GIT_TRACK_NOTE}`);
|
|
180
201
|
};
|
|
181
202
|
const answerToks = [...flagValues(rest, "answers"), ...(flag("answers-file") ? (() => { const f = flagValues(rest, "answers-file")[0]; return f && existsSync(path.resolve(root, f)) ? readFileSync(path.resolve(root, f), "utf8").split("\n") : [`<missing answers file ${f ?? ""}>`]; })() : [])];
|
|
182
203
|
if (flag("answers") || flag("answers-file")) {
|
|
@@ -372,9 +393,25 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
|
|
|
372
393
|
cfg.release.merge = style;
|
|
373
394
|
notes.push(written.note);
|
|
374
395
|
}
|
|
396
|
+
// the reflection rows this flow sets out to fix, proven open before anything is created: a linked row is
|
|
397
|
+
// closed by finish as fixed by this flow — the fix and the ledger can no longer drift apart
|
|
398
|
+
const linkArg = flagValue(rest, "reflections");
|
|
399
|
+
let linked: { id: number; body: string }[] = [];
|
|
400
|
+
if (linkArg !== null) {
|
|
401
|
+
const ids = parseRowIds(linkArg);
|
|
402
|
+
const open = readReflections(root);
|
|
403
|
+
const bad = ids.filter((id) => !open.some((i) => i.n === id));
|
|
404
|
+
if (!ids.length || bad.length) return { text: `start: --reflections names ${bad.length ? `no open row ${bad.map((b) => (Number.isNaN(b) ? "?" : `r${b}`)).join(", ")}` : "nothing"} — open: ${open.map((i) => `r${i.n}`).join(", ") || "none"} (flow reflect list prints them; flow reflect plan groups them)`, isError: true };
|
|
405
|
+
linked = ids.map((id) => ({ id, body: open.find((i) => i.n === id)!.body }));
|
|
406
|
+
}
|
|
375
407
|
// stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling.
|
|
376
408
|
// the stamp is what ran, not what the disk claims (that mismatch is the warning above).
|
|
377
409
|
const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), loadedVersion() ?? undefined);
|
|
410
|
+
if (linked.length) {
|
|
411
|
+
state.reflections = linked;
|
|
412
|
+
const rows = readReflections(root).filter((i) => linked.some((l) => l.id === i.n));
|
|
413
|
+
notes.push(`linked reflections (finish closes each as fixed by this flow; one it does not fix: flow reflect defer <id> "<why>"):\n${rows.map((i) => ` r${i.n}. ${i.line.replace(/^- \[ \] /, "").replace(/^\[r\d+\]\s*/, "")}`).join("\n")}`);
|
|
414
|
+
}
|
|
378
415
|
const planDir = path.join(featDir(root, slugArg), "plan");
|
|
379
416
|
if (ghost) notes.push(gi!.plan ? `adopted ghost .dev-flow/${slugArg}/ — its plan/ (${listFiles(planDir).join(", ") || "empty"}) is this feature's draft` : `adopted ghost .dev-flow/${slugArg}/ — kept ${gi!.entries.join(", ") || "nothing (it was empty)"}`);
|
|
380
417
|
mkdirSync(planDir, { recursive: true });
|
|
@@ -529,9 +566,13 @@ export async function gateReflect(o: GateCtx): Promise<RunResult> {
|
|
|
529
566
|
// single words are verbs (roadmap-style); a note merely starting with one stays a note
|
|
530
567
|
if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
|
|
531
568
|
if (words.length === 1 && words[0] === "list") return await reflectList(root);
|
|
569
|
+
if (words.length === 1 && words[0] === "plan") return reflectPlanNote(root);
|
|
570
|
+
if (flag("same")) return reflectSameNote(root, sess, words);
|
|
532
571
|
if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
|
|
533
572
|
if (words[0] === "done") return reflectDoneNote(root, sess, words.slice(1));
|
|
534
|
-
if (words
|
|
573
|
+
if (words[0] === "reopen") return reflectReopenNote(root, sess, words.slice(1));
|
|
574
|
+
if (words[0] === "defer") return reflectDeferNote(root, sess, words.slice(1));
|
|
575
|
+
if (words.length) return await reflectNote(root, sess, words, forced, flagValue(rest, "evidence") ?? "");
|
|
535
576
|
const self = pluginVersion(import.meta.dirname);
|
|
536
577
|
const upstream = await pluginUpstream(root);
|
|
537
578
|
const refl = readReflections(root);
|
|
@@ -644,7 +685,7 @@ export async function gateDoctor(o: GateCtx): Promise<RunResult> {
|
|
|
644
685
|
// note text made doctor's table disagree with where the note was actually filed
|
|
645
686
|
reflectionRoutes(refl, isSelfRepo(root)).forEach((r, i) => {
|
|
646
687
|
const link = fold.state === "ok" ? fold.result.linked.find((l) => l.item === i) : undefined;
|
|
647
|
-
findings.push(` [${r.sections.join("+")}] ${r.text}${link ? linkedTag(link.issue) : ""}\n → ${r.route}${link ? ` — already upstream (gh#${link.issue}); check off with — filed: gh#${link.issue} once it lands` : ""}`);
|
|
688
|
+
findings.push(` r${refl[i].n} [${r.sections.join("+")}] ${r.text}${link ? linkedTag(link.issue) : ""}\n → ${r.route}${link ? ` — already upstream (gh#${link.issue}); check off with — filed: gh#${link.issue} once it lands` : ""}`);
|
|
648
689
|
});
|
|
649
690
|
}
|
|
650
691
|
findings.push(...foldRows(fold, isSelfRepo(root), refl));
|
|
@@ -708,13 +749,14 @@ export async function gateCheck(o: GateCtx): Promise<RunResult> {
|
|
|
708
749
|
// a docs flow runs no project command anywhere else — pendingChecks, verifyGate and releaseGate all skip
|
|
709
750
|
// it — so running tier-1 here only produced a FAIL that read like a broken deploy in a checkout that
|
|
710
751
|
// never built the binary (#96)
|
|
711
|
-
//
|
|
712
|
-
|
|
713
|
-
if (state
|
|
752
|
+
// --docs is the operator's word for the change's kind, but the diff decides: one that reaches code runs the checks
|
|
753
|
+
await refreshDocsCode(root, state!, cfg);
|
|
754
|
+
if (skipsChecks(state!)) 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)" };
|
|
755
|
+
const docsNote = state!.docs ? `docs flow, but its diff reaches code (${state!.docsCode!.slice(0, 6).join(", ")}${state!.docsCode!.length > 6 ? ` +${state!.docsCode!.length - 6}` : ""}) — the tier-1 checks run as on any flow\n` : "";
|
|
714
756
|
if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
|
|
715
757
|
const ran = await runChecks(root, state!, cfg, cfg.checkList);
|
|
716
758
|
const behind = await behindNote(root, state!, cfg);
|
|
717
|
-
return { text:
|
|
759
|
+
return { text: `${docsNote}tier-1 checks:\n${ran.lines.join("\n")}${behind ? `\n${behind}` : ""}`, isError: ran.failed };
|
|
718
760
|
}
|
|
719
761
|
|
|
720
762
|
export async function gateHealth(o: GateCtx): Promise<RunResult> {
|
package/src/runtime/publish.ts
CHANGED
|
@@ -17,8 +17,19 @@ export const publishWait = {
|
|
|
17
17
|
sleep: (ms: number) => new Promise<void>((r) => setTimeout(r, ms)),
|
|
18
18
|
clock: () => Date.now(),
|
|
19
19
|
checks: (pr: number, cwd: string): Promise<PrCheck[] | null> => prChecks(pr, cwd),
|
|
20
|
+
/** the CI runs a commit started — the merge commit, before it is tagged (gh#271) */
|
|
21
|
+
commitChecks: (sha: string, cwd: string): Promise<PrCheck[] | null> => commitRuns(sha, cwd),
|
|
20
22
|
};
|
|
21
23
|
|
|
24
|
+
/** Workflow runs of one commit as checks; [] when none started, null when gh cannot say. */
|
|
25
|
+
async function commitRuns(sha: string, cwd: string): Promise<PrCheck[] | null> {
|
|
26
|
+
const r = await sh(`gh run list --commit ${sha} --limit 50 --json status,conclusion,name,url`, cwd, 60_000);
|
|
27
|
+
if (!r.ok) return null;
|
|
28
|
+
const rows = jsonArray<{ status?: string; conclusion?: string; name?: string; url?: string }>(r.out);
|
|
29
|
+
if (rows === null) return r.out.trim() ? null : [];
|
|
30
|
+
return rows.map((x) => ({ name: x.name ?? "run", bucket: checkBucket({ status: (x.status ?? "").toUpperCase(), conclusion: (x.conclusion ?? "").toUpperCase() }), link: x.url ?? "" }));
|
|
31
|
+
}
|
|
32
|
+
|
|
22
33
|
export interface PrCheck { name: string; bucket: string; link: string }
|
|
23
34
|
interface Pr { number: number; state: string; url: string; headRefOid: string; mergeCommit: { oid: string } | null }
|
|
24
35
|
|
|
@@ -70,21 +81,28 @@ async function prChecks(pr: number, cwd: string): Promise<PrCheck[] | null> {
|
|
|
70
81
|
export type CiVerdict = { state: "green" | "none"; note: string } | { state: "red" | "running" | "unknown"; why: string };
|
|
71
82
|
|
|
72
83
|
/** Wait (bounded) for the PR's checks to settle. */
|
|
73
|
-
export
|
|
84
|
+
export const awaitPrChecks = (pr: number, cwd: string): Promise<CiVerdict> =>
|
|
85
|
+
awaitChecks(() => publishWait.checks(pr, cwd), { who: `PR #${pr}`, read: `gh pr view ${pr} --json statusCheckRollup`, none: "no CI checks on the PR", green: "CI green" });
|
|
86
|
+
|
|
87
|
+
/** gh#271: wait (bounded) for the CI the merge commit started — a tag publishes from it, so it is cut on green only. */
|
|
88
|
+
export const awaitCommitChecks = (sha: string, cwd: string): Promise<CiVerdict> =>
|
|
89
|
+
awaitChecks(() => publishWait.commitChecks(sha, cwd), { who: `merge commit ${sha.slice(0, 9)}`, read: `gh run list --commit ${sha}`, none: "no CI ran on the merge commit", green: "merge-commit CI green" });
|
|
90
|
+
|
|
91
|
+
async function awaitChecks(read: () => Promise<PrCheck[] | null>, l: { who: string; read: string; none: string; green: string }): Promise<CiVerdict> {
|
|
74
92
|
const start = publishWait.clock();
|
|
75
93
|
const mins = () => `${Math.max(1, Math.round((publishWait.clock() - start) / 60_000))} min`;
|
|
76
94
|
for (;;) {
|
|
77
|
-
const rows = await
|
|
95
|
+
const rows = await read();
|
|
78
96
|
const elapsed = publishWait.clock() - start;
|
|
79
|
-
if (rows === null) return { state: "unknown", why: `cannot read the checks of
|
|
97
|
+
if (rows === null) return { state: "unknown", why: `cannot read the checks of ${l.who} (${l.read})` };
|
|
80
98
|
if (!rows.length) {
|
|
81
|
-
if (elapsed >= publishWait.appearMs) return { state: "none", note:
|
|
99
|
+
if (elapsed >= publishWait.appearMs) return { state: "none", note: l.none };
|
|
82
100
|
} else {
|
|
83
101
|
const failed = rows.filter((c) => c.bucket === "fail" || c.bucket === "cancel");
|
|
84
|
-
if (failed.length) return { state: "red", why:
|
|
102
|
+
if (failed.length) return { state: "red", why: `${l.who} checks failed — ${failed.map((c) => `${c.name}: ${c.bucket}${c.link ? ` (${c.link})` : ""}`).join(", ")}` };
|
|
85
103
|
const pending = rows.filter((c) => c.bucket !== "pass" && c.bucket !== "skipping");
|
|
86
|
-
if (!pending.length) return { state: "green", note:
|
|
87
|
-
if (elapsed >= publishWait.budgetMs) return { state: "running", why:
|
|
104
|
+
if (!pending.length) return { state: "green", note: `${l.green} (${rows.length} check${rows.length === 1 ? "" : "s"}${elapsed >= 60_000 ? `, waited ${mins()}` : ""})` };
|
|
105
|
+
if (elapsed >= publishWait.budgetMs) return { state: "running", why: `${l.who} checks still running after ${mins()} (${pending.map((c) => c.name).join(", ")})` };
|
|
88
106
|
}
|
|
89
107
|
await publishWait.sleep(publishWait.pollMs);
|
|
90
108
|
}
|
|
@@ -147,6 +165,25 @@ async function prBody(root: string, cwd: string, cfg: Config, state: FlowState):
|
|
|
147
165
|
|
|
148
166
|
export type PublishResult = { ok: true; log: string } | { ok: false; text: string };
|
|
149
167
|
|
|
168
|
+
/** gh#259: the files a merge of `HEAD` into `origin/<default>` would conflict in, from a fresh fetch — [] when it
|
|
169
|
+
* merges clean, null when this git cannot say (merge-tree --write-tree needs git 2.38) or origin is unreachable.
|
|
170
|
+
* A conflict was found by gh pr merge after the whole CI wait, though it was true before the push. */
|
|
171
|
+
export async function mergeConflicts(wt: string, defaultBranch: string): Promise<string[] | null> {
|
|
172
|
+
if (!(await sh(`git fetch -q origin ${sq(defaultBranch)}`, wt, 5 * 60_000)).ok) return null;
|
|
173
|
+
const r = await sh(`git merge-tree --write-tree --name-only --no-messages ${sq(`origin/${defaultBranch}`)} HEAD`, wt);
|
|
174
|
+
if (r.ok) return [];
|
|
175
|
+
// exit 1 with a tree id on the first line is "conflicts"; anything else (an old git, a bad ref) is not an answer
|
|
176
|
+
const lines = r.out.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
177
|
+
if (!/^[0-9a-f]{40,64}$/.test(lines[0] ?? "")) return null;
|
|
178
|
+
return [...new Set(lines.slice(1))];
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** GitHub's own verdict on an open PR: CONFLICTING is the one that stops; UNKNOWN (still computing) does not. */
|
|
182
|
+
async function prConflicting(pr: number, cwd: string): Promise<boolean> {
|
|
183
|
+
const r = await sh(`gh pr view ${pr} --json mergeable`, cwd, 60_000);
|
|
184
|
+
return r.ok && /"mergeable"\s*:\s*"CONFLICTING"/.test(r.out);
|
|
185
|
+
}
|
|
186
|
+
|
|
150
187
|
/** Push, PR, CI, merge, tag — each step skipped when the forge already shows it done. On success the caller
|
|
151
188
|
* records the release (release-done's proofs). A refusal starts with `publish stopped —` (something to fix)
|
|
152
189
|
* or `publish waiting —` (CI still running: re-run to keep waiting). */
|
|
@@ -168,6 +205,11 @@ export async function publishRelease(root: string, state: FlowState, cfg: Config
|
|
|
168
205
|
let merged = found.merged;
|
|
169
206
|
if (merged) steps.push(`PR #${merged.number} already merged`);
|
|
170
207
|
else {
|
|
208
|
+
// gh#259: a conflict with the default branch is known before the push — never spend the CI wait to learn it
|
|
209
|
+
const d = cfg.defaultBranch;
|
|
210
|
+
const resolve = `merge origin/${d} into ${br} in the worktree (git merge origin/${d}), resolve the conflicts — keep both sides' changelog lines; a version file takes the bump past the newest release — and commit`;
|
|
211
|
+
const conflicts = await mergeConflicts(wt, d);
|
|
212
|
+
if (conflicts?.length) return stop(`${br} conflicts with origin/${d} in ${conflicts.join(", ")} — the merge would be refused after the CI wait, so nothing was pushed`, resolve);
|
|
171
213
|
const remote = await sh(`git ls-remote origin ${sq(`refs/heads/${br}`)}`, wt, 60_000);
|
|
172
214
|
if (!remote.ok) return stop(`cannot reach origin:\n${tail(remote.out, 5)}`, "check the network and git credentials");
|
|
173
215
|
if (remote.out.split(/\s/)[0] === head) steps.push("branch already on origin");
|
|
@@ -192,6 +234,8 @@ export async function publishRelease(root: string, state: FlowState, cfg: Config
|
|
|
192
234
|
}
|
|
193
235
|
state.publish = { ...state.publish, pr: pr.number };
|
|
194
236
|
writeState(root, state);
|
|
237
|
+
// the forge's view too: the default branch can move between the local check and the PR
|
|
238
|
+
if (await prConflicting(pr.number, wt)) return stop(`PR #${pr.number} has merge conflicts with ${d} — the merge would be refused after the CI wait`, resolve);
|
|
195
239
|
const ci = await awaitPrChecks(pr.number, wt);
|
|
196
240
|
if (!("why" in ci)) steps.push(ci.note);
|
|
197
241
|
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` };
|
|
@@ -230,6 +274,16 @@ export async function publishRelease(root: string, state: FlowState, cfg: Config
|
|
|
230
274
|
if (tags === null) return stop("cannot list tags on origin", "check the network and git credentials");
|
|
231
275
|
if (tags.includes(tag)) steps.push(`tag ${tag} already on origin`);
|
|
232
276
|
else {
|
|
277
|
+
// gh#271: the tag publishes from the merge commit — wait for that commit's own CI before cutting it, so a
|
|
278
|
+
// playbook rule "test green on the merge commit before the tag" is something this gate can honour
|
|
279
|
+
if (oid && cfg.release.tagWait !== "none") {
|
|
280
|
+
const ci = await awaitCommitChecks(oid, root);
|
|
281
|
+
if (!("why" in ci)) steps.push(ci.note);
|
|
282
|
+
else if (ci.state === "running") return { ok: false, text: `publish waiting — ${ci.why}; the tag waits for it${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` };
|
|
283
|
+
else if (ci.state === "red")
|
|
284
|
+
return stop(`${ci.why} — merged, but the tag was not cut: it would publish a red build`, `tell the operator. A flaky job: re-run it (gh run rerun --failed <run>), then re-run flow release, which tags on green. A real failure is fixed forward in a new flow, and the tag goes on the fix by the operator's word (or tagWait = none under ## release for a project whose tag publishes nothing)`);
|
|
285
|
+
else return stop(ci.why, "check gh auth status, or tag the merge commit yourself once its CI is green");
|
|
286
|
+
}
|
|
233
287
|
if (!oid) return stop(`PR #${merged.number} shows no merge commit to tag`, `tag what shipped yourself (git tag -a ${tag}) and push it`);
|
|
234
288
|
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}`);
|
|
235
289
|
if (!(await sh(`git rev-parse -q --verify ${sq(`refs/tags/${tag}`)}`, root)).ok) {
|
package/src/runtime/reflect.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/** dev-flow runtime — Reflections and the upstream issue fold. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
2
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { appendReflection, doneItemCount, githubSlug, pluginVersion, guessReflectSections, reflectItems, reflectMove, reflectDone, reflectRow, reflectLegacyPluginCount, reflectionNudges, pluginIssueRecipe, reflectionLine, reflectionsTidy, openChecklistItems, type ReflectTarget, type ReflectItem, type ReflectSection } from "../core.ts";
|
|
4
|
+
import { ensureReflectIds as ensureReflectIdsFor, appendReflection, doneItemCount, githubSlug, pluginVersion, guessReflectSections, reflectItems, reflectMove, reflectDone, reflectRow, reflectLegacyPluginCount, reflectionNudges, pluginIssueRecipe, reflectionLine, reflectionsTidy, openChecklistItems, parseRowIds, reflectSame, reflectReopen, closedRowsBySection, archiveAppend, archiveTake, reflectFixPlan, rowId, type ReflectTarget, type ReflectItem, type ReflectSection, type FlowState } from "../core.ts";
|
|
5
5
|
import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../fold.ts";
|
|
6
|
-
import { dfDir, now, originUrl, readReflections, readReflectionsText, sh } from "./base.ts";
|
|
6
|
+
import { dfDir, now, originUrl, readState, writeState, readReflectArchive, readReflections, readReflectionsText, reflectArchiveFile, sh } from "./base.ts";
|
|
7
7
|
import { type RunResult, type Session } from "./checks.ts";
|
|
8
8
|
import { isSelfRepo } from "./setup.ts";
|
|
9
9
|
import { AGENT_MARK } from "../present.ts";
|
|
@@ -18,9 +18,9 @@ export async function pluginUpstream(root: string): Promise<string> {
|
|
|
18
18
|
* section (the agent knows what its own note is about); `--plugin` is dev-flow feedback, which never
|
|
19
19
|
* lands in a project's file — it prints the upstream issue recipe instead (in the dev-flow repo itself
|
|
20
20
|
* plugin IS code, so it files under `## code`). With no flag the wording guesses and the echo prints why. */
|
|
21
|
-
export async function reflectNote(root: string, sess: Session, note: string[], forced: ReflectTarget | null): Promise<RunResult> {
|
|
21
|
+
export async function reflectNote(root: string, sess: Session, note: string[], forced: ReflectTarget | null, evidence = ""): Promise<RunResult> {
|
|
22
22
|
const file = path.join(dfDir(root), "reflections.md");
|
|
23
|
-
const text =
|
|
23
|
+
const text = readReflectionsText(root);
|
|
24
24
|
const guess = guessReflectSections(note.join(" "));
|
|
25
25
|
const self = isSelfRepo(root);
|
|
26
26
|
const target = forced ?? guess.target;
|
|
@@ -28,13 +28,122 @@ export async function reflectNote(root: string, sess: Session, note: string[], f
|
|
|
28
28
|
const date = now().slice(0, 10);
|
|
29
29
|
if (target === "plugin" && !self) return { text: [...pluginIssueRecipe(note.join(" "), await pluginUpstream(root), sess.slug, date), ...(forced ? [] : [`(filed as plugin: ${why} — a project note: flow reflect --playbook|--code "<note>")`])].join("\n") };
|
|
30
30
|
const section: ReflectSection = target === "plugin" ? "code" : target;
|
|
31
|
-
const line = reflectionLine(note.join(" "), sess.slug, date);
|
|
32
|
-
const
|
|
33
|
-
if (
|
|
31
|
+
const line = reflectionLine(note.join(" "), sess.slug, date, evidence);
|
|
32
|
+
const appended = appendReflection(text, [section], line);
|
|
33
|
+
if (appended === text) {
|
|
34
|
+
const body = reflectItems(line)[0]?.body;
|
|
35
|
+
const same = reflectItems(text).find((it) => it.body === body);
|
|
36
|
+
return { text: `already reflected (duplicate)${same ? ` as r${same.n} — a recurrence is flow reflect --same r${same.n} "<evidence>"` : ""}: ${line}` };
|
|
37
|
+
}
|
|
38
|
+
const next = ensureIds(root, appended);
|
|
34
39
|
writeFileSync(file, next);
|
|
40
|
+
const id = reflectItems(next).find((it) => it.line.endsWith(line.slice(6)))?.n;
|
|
35
41
|
// queueing is exactly when the operator hears about the checked-off pile — nudge only once it is worth a tidy
|
|
36
42
|
const { tidy } = reflectionNudges(next, date);
|
|
37
|
-
return { text: `reflected (${section} — ${target === "plugin" ? "dev-flow repo: plugin feedback is this project's code" : why}): ${line}` + (tidy ? `\n${tidy}` : "") };
|
|
43
|
+
return { text: `reflected${id ? ` as r${id}` : ""} (${section} — ${target === "plugin" ? "dev-flow repo: plugin feedback is this project's code" : why}): ${line}` + (tidy ? `\n${tidy}` : "") };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const ensureIds = (root: string, text: string) => ensureReflectIdsFor(text, readReflectArchive(root));
|
|
47
|
+
|
|
48
|
+
/** `flow reflect --same <id> [evidence]` (gh#263 follow-up): the reflect worker reports a finding as `dup: r<id>` —
|
|
49
|
+
* the recurrence lands on that row as `· seen again <date> <slug>[: evidence]`, and the count ranks it, instead
|
|
50
|
+
* of a fourth copy of the same defect in its own row. */
|
|
51
|
+
export function reflectSameNote(root: string, sess: Session, args: string[]): RunResult {
|
|
52
|
+
const [id] = parseRowIds(args[0] ?? "");
|
|
53
|
+
if (!Number.isInteger(id)) return { text: 'usage: flow reflect --same <id> ["<evidence>"] — the id is the r<n> flow reflect list prints', isError: true };
|
|
54
|
+
const text = readReflectionsText(root);
|
|
55
|
+
const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
|
|
56
|
+
const next = reflectSame(text, id, stamp, args.slice(1).join(" "));
|
|
57
|
+
if (next === null) return { text: `same: ${noOpenRow(text, id, reflectItems(text))}`, isError: true };
|
|
58
|
+
writeFileSync(path.join(dfDir(root), "reflections.md"), next);
|
|
59
|
+
const it = reflectItems(next).find((x) => x.n === id)!;
|
|
60
|
+
return { text: `reflect: r${id} seen again — now hit ${it.hits}× — ${it.body}` };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `flow reflect reopen <id> [why]`: a row closed by mistake comes back open, its history on the row. A row already
|
|
64
|
+
* tidied into the archive is taken back from there, under its section. */
|
|
65
|
+
export function reflectReopenNote(root: string, sess: Session, args: string[]): RunResult {
|
|
66
|
+
const [id] = parseRowIds(args[0] ?? "");
|
|
67
|
+
if (!Number.isInteger(id)) return { text: 'usage: flow reflect reopen <id> ["<why>"]', isError: true };
|
|
68
|
+
const file = path.join(dfDir(root), "reflections.md");
|
|
69
|
+
let text = readReflectionsText(root);
|
|
70
|
+
const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
|
|
71
|
+
const why = args.slice(1).join(" ");
|
|
72
|
+
let from = "";
|
|
73
|
+
if (!reflectRow(text, id)) {
|
|
74
|
+
const taken = archiveTake(readReflectArchive(root), id);
|
|
75
|
+
if (!taken) return { text: `reopen: no row r${id} in reflections.md or its archive`, isError: true };
|
|
76
|
+
writeFileSync(reflectArchiveFile(root), taken.archive);
|
|
77
|
+
const section = taken.row.section === "playbook" || taken.row.section === "code" ? (taken.row.section as ReflectSection) : "playbook";
|
|
78
|
+
text = appendReflection(text || "", [section], taken.row.line);
|
|
79
|
+
from = " (taken back from the archive)";
|
|
80
|
+
}
|
|
81
|
+
const next = reflectReopen(text, id, stamp, why);
|
|
82
|
+
if (next === null) return { text: `reopen: r${id} is open already`, isError: true };
|
|
83
|
+
writeFileSync(file, next);
|
|
84
|
+
return { text: `reflect: r${id} reopened${from} — ${reflectItems(next).find((x) => x.n === id)?.body ?? ""}` };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `flow reflect defer <id> "<why>"`: a row linked to the bound flow that this flow does not fix after all — it stays
|
|
88
|
+
* open with the reason on it, and finish leaves it alone. Every linked row is either fixed (closed at finish) or
|
|
89
|
+
* deferred with a reason: the ledger never again reads "30 open" after the flow that fixed them shipped. */
|
|
90
|
+
export function reflectDeferNote(root: string, sess: Session, args: string[]): RunResult {
|
|
91
|
+
const [id] = parseRowIds(args[0] ?? "");
|
|
92
|
+
const why = args.slice(1).join(" ").trim();
|
|
93
|
+
if (!Number.isInteger(id) || !why) return { text: 'usage: flow reflect defer <id> "<why this flow does not fix it>"', isError: true };
|
|
94
|
+
if (!sess.slug) return { text: "defer: no flow bound — a row is deferred by the flow it was linked to (flow start --reflections)", isError: true };
|
|
95
|
+
const state = readState(root, sess.slug);
|
|
96
|
+
const link = state?.reflections?.find((r) => r.id === id);
|
|
97
|
+
if (!state || !link) return { text: `defer: r${id} is not linked to ${sess.slug} — linked: ${(state?.reflections ?? []).map((r) => `r${r.id}`).join(", ") || "none"}`, isError: true };
|
|
98
|
+
link.deferred = why;
|
|
99
|
+
writeState(root, state);
|
|
100
|
+
const text = readReflectionsText(root);
|
|
101
|
+
const row = reflectRow(text, id);
|
|
102
|
+
if (row?.open) {
|
|
103
|
+
const lines = text.split("\n");
|
|
104
|
+
lines[row.index] = `${lines[row.index].trimEnd()} · deferred by ${sess.slug} ${now().slice(0, 10)}: ${why}`;
|
|
105
|
+
writeFileSync(path.join(dfDir(root), "reflections.md"), lines.join("\n"));
|
|
106
|
+
}
|
|
107
|
+
return { text: `reflect: r${id} deferred by ${sess.slug} — it stays open (${why}); finish closes the rest of the linked rows as fixed` };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Close the rows a flow was linked to and did not defer — finish's half of the link. Returns the ids closed. */
|
|
111
|
+
export function closeLinkedReflections(root: string, state: FlowState, prNote: string): number[] {
|
|
112
|
+
const linked = (state.reflections ?? []).filter((r) => !r.deferred);
|
|
113
|
+
if (!linked.length) return [];
|
|
114
|
+
let text = readReflectionsText(root);
|
|
115
|
+
const closed: number[] = [];
|
|
116
|
+
for (const r of linked) {
|
|
117
|
+
const next = reflectDone(text, r.id, `${now().slice(0, 10)} ${state.slug} — fixed by this flow${prNote}`);
|
|
118
|
+
if (next !== null) { text = next; closed.push(r.id); }
|
|
119
|
+
}
|
|
120
|
+
if (closed.length) writeFileSync(path.join(dfDir(root), "reflections.md"), text);
|
|
121
|
+
return closed;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** `flow reflect plan`: the open rows grouped into flows — shared files and code names make a group, the playbook
|
|
125
|
+
* rows one docs flow — ranked by how often their rows were hit, each with the start command that links its rows. */
|
|
126
|
+
export function reflectPlanNote(root: string): RunResult {
|
|
127
|
+
const items = readReflections(root).filter((i) => i.section !== "plugin");
|
|
128
|
+
if (!items.length) return { text: "reflections: nothing open to plan" };
|
|
129
|
+
const { groups, singles } = reflectFixPlan(items);
|
|
130
|
+
const ids = (g: { ids: number[] }) => g.ids.map((n) => `r${n}`).join(",");
|
|
131
|
+
const clip = (s: string) => (s.length > 90 ? `${s.slice(0, 89)}…` : s);
|
|
132
|
+
const out = [`fix plan — ${items.length} open, ${groups.length + singles.length} flow(s), most-hit first:`];
|
|
133
|
+
groups.forEach((g, i) => {
|
|
134
|
+
const docs = g.section === "playbook";
|
|
135
|
+
out.push(` ${i + 1}. ${docs ? "playbook — one docs flow" : `code · ${g.topic}`} (${g.ids.length} row(s), hit ${g.hits}×): ${ids(g)}`);
|
|
136
|
+
for (const b of g.bodies.slice(0, 4)) out.push(` · ${clip(b)}`);
|
|
137
|
+
if (g.bodies.length > 4) out.push(` · … ${g.bodies.length - 4} more`);
|
|
138
|
+
out.push(`${AGENT_MARK}start: flow start ${docs ? "fold-playbook" : `fix-${g.topic}`} ${docs ? "--docs" : "--patch"} --reflections=${ids(g)}`);
|
|
139
|
+
});
|
|
140
|
+
if (singles.length) {
|
|
141
|
+
out.push(`single code rows (no shared file with another row) — ${singles.length}:`);
|
|
142
|
+
for (const g of singles) out.push(` r${g.ids[0]} (hit ${g.hits}×) ${clip(g.bodies[0])}`);
|
|
143
|
+
out.push(`${AGENT_MARK}a single row is its own patch flow (flow start fix-<topic> --patch --reflections=r<id>), or rides with a group above when it touches the same code`);
|
|
144
|
+
}
|
|
145
|
+
out.push(`${AGENT_MARK}--reflections links the rows to the flow: finish closes them as fixed by it; one the flow does not fix is flow reflect defer <id> "<why>"`);
|
|
146
|
+
return { text: out.join("\n") };
|
|
38
147
|
}
|
|
39
148
|
|
|
40
149
|
/** In-process TTL cache per repo slug — repeat doctor runs in one session must not re-hit the API. */
|
|
@@ -89,13 +198,13 @@ export async function reflectList(root: string): Promise<RunResult> {
|
|
|
89
198
|
const fold = await foldView(root, items);
|
|
90
199
|
const local = items.length
|
|
91
200
|
? [
|
|
92
|
-
`reflections — ${items.length} open (
|
|
201
|
+
`reflections — ${items.length} open (r<n> is a row's id: it never changes, whatever is closed, tidied or moved):`,
|
|
93
202
|
...items.map((it, i) => {
|
|
94
203
|
const link = fold.state === "ok" ? fold.result.linked.find((l) => l.item === i) : undefined;
|
|
95
|
-
return ` ${it.n}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}${link ? linkedTag(link.issue) : ""}`;
|
|
204
|
+
return ` r${it.n}. [${it.section}]${(it.hits ?? 1) > 1 ? ` hit ${it.hits}×` : ""} ${it.line.replace(/^- \[ \] /, "").replace(/^\[r\d+\]\s*/, "")}${link ? linkedTag(link.issue) : ""}`;
|
|
96
205
|
}),
|
|
97
206
|
// 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 <
|
|
207
|
+
`${AGENT_MARK}close fixed rows with flow reflect done <id>[,<id>…] "<what fixed it>" — never by editing reflections.md; a recurrence is flow reflect --same <id> "<evidence>"; flow reflect plan groups the open rows into flows`,
|
|
99
208
|
]
|
|
100
209
|
: fold.state === "absent" || fold.state === "skipped"
|
|
101
210
|
? ["reflections: nothing open"]
|
|
@@ -121,29 +230,27 @@ export function reflectMoveNote(root: string, args: string[], forced: ReflectTar
|
|
|
121
230
|
if (forced === "plugin") return { text: "move: plugin notes are not kept in reflections.md — file the item upstream (flow reflect --plugin \"<note>\" prints the recipe), then check the row off '— filed: gh#NNN' (in the dev-flow repo itself: move <n> --code)", isError: true };
|
|
122
231
|
if (!forced) return { text: "usage: flow reflect move <n> --playbook | --code", isError: true };
|
|
123
232
|
const section = forced;
|
|
124
|
-
const n =
|
|
233
|
+
const [n] = parseRowIds(args[0] ?? "");
|
|
125
234
|
const text = readReflectionsText(root);
|
|
126
235
|
const items = reflectItems(text);
|
|
127
236
|
const it = items.find((x) => x.n === n);
|
|
128
237
|
if (!it) return { text: `move: ${noOpenRow(text, n, items)}`, isError: true };
|
|
129
|
-
if (it.section === section) return { text: `reflect:
|
|
238
|
+
if (it.section === section) return { text: `reflect: r${n} is already under ## ${section}` };
|
|
130
239
|
// the same note open under both headings (an old --both filing): the move merges it, it does not copy it
|
|
131
240
|
const twin = items.some((x) => x !== it && x.section === section && x.body === it.body);
|
|
132
241
|
const next = reflectMove(text, n, section);
|
|
133
242
|
if (next === null) return { text: `move: ${noOpenRow(text, n, items)}`, isError: true };
|
|
134
243
|
writeFileSync(path.join(dfDir(root), "reflections.md"), next);
|
|
135
244
|
const note = it.line.replace(/^- \[ \] /, "");
|
|
136
|
-
return { text:
|
|
245
|
+
return { text: twin ? `reflect: r${n} was already recorded under ## ${section} — the duplicate is gone (${note})` : `reflect: r${n} re-filed under ## ${section} — ${note}` };
|
|
137
246
|
}
|
|
138
247
|
|
|
139
|
-
const RENUMBERED = "the row numbers changed — run flow reflect list before the next done or move";
|
|
140
|
-
|
|
141
248
|
/** Why `<n>` names no open row (gh#197): a row already checked off says which note it holds, so a batch that
|
|
142
249
|
* drifted shows the mismatch instead of closing the wrong line. */
|
|
143
250
|
function noOpenRow(text: string, n: number, items: readonly ReflectItem[]): string {
|
|
144
251
|
const row = Number.isInteger(n) && n > 0 ? reflectRow(text, n) : null;
|
|
145
|
-
if (row && !row.open) return `
|
|
146
|
-
return items.length ? `no open
|
|
252
|
+
if (row && !row.open) return `r${n} is already checked off (${row.line.replace(/^-\s*\[[xX]\]\s*/, "")}) — flow reflect list shows the open ones; flow reflect reopen r${n} "<why>" if it was closed by mistake`;
|
|
253
|
+
return items.length ? `no open row r${Number.isNaN(n) ? "?" : n} — open: ${items.map((i) => `r${i.n}`).join(", ")} (flow reflect list prints them)` : "nothing open in reflections.md";
|
|
147
254
|
}
|
|
148
255
|
|
|
149
256
|
/** `flow reflect done <n> [what fixed it]` — check a folded/fixed item off, so doctor stops re-reporting it (#165).
|
|
@@ -153,31 +260,39 @@ export function reflectDoneNote(root: string, sess: Session, args: string[]): Ru
|
|
|
153
260
|
const items = reflectItems(text);
|
|
154
261
|
// gh#220: a fold closes several rows with one fix — `done 3,4,7 "<what>"` checks them off together. Checking a
|
|
155
262
|
// row off leaves the other numbers as they are, so the batch is all or nothing: one bad number closes none.
|
|
156
|
-
const nums =
|
|
157
|
-
if (!nums.length) return { text: 'usage: flow reflect done <
|
|
263
|
+
const nums = parseRowIds(args[0] ?? "");
|
|
264
|
+
if (!nums.length) return { text: 'usage: flow reflect done <id>[,<id>…] "<what fixed it>"', isError: true };
|
|
158
265
|
const picked = nums.map((n) => ({ n, it: items.find((x) => x.n === n) }));
|
|
159
266
|
const bad = picked.filter((p) => !p.it);
|
|
160
267
|
if (bad.length) return { text: `done: ${bad.map((p) => noOpenRow(text, p.n, items)).join("; ")}${nums.length > 1 ? " — nothing was checked off" : ""}`, isError: true };
|
|
161
268
|
const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
|
|
162
269
|
const what = args.slice(1).join(" ").trim();
|
|
163
270
|
let next = text;
|
|
164
|
-
for (const n of nums)
|
|
271
|
+
for (const n of nums) {
|
|
272
|
+
const closed = reflectDone(next, n, what ? `${stamp} — ${what}` : stamp);
|
|
273
|
+
// every id was proven open above and a close moves no other row — a miss here is a bug, never a silent skip
|
|
274
|
+
if (closed === null) return { text: `done: r${n} could not be checked off — nothing was changed`, isError: true };
|
|
275
|
+
next = closed;
|
|
276
|
+
}
|
|
165
277
|
writeFileSync(path.join(dfDir(root), "reflections.md"), next);
|
|
166
278
|
const { tidy } = reflectionNudges(next, now().slice(0, 10));
|
|
167
279
|
const head = nums.length === 1
|
|
168
|
-
? `reflect:
|
|
169
|
-
: `reflect: ${nums.length} items checked off${what ? ` — fixed: ${what}` : ""}\n${picked.map((p) => ` ${p.n}. ${p.it!.body}`).join("\n")}`;
|
|
280
|
+
? `reflect: r${nums[0]} checked off — ${picked[0].it!.body}${what ? ` — fixed: ${what}` : ""}`
|
|
281
|
+
: `reflect: ${nums.length} items checked off${what ? ` — fixed: ${what}` : ""}\n${picked.map((p) => ` r${p.n}. ${p.it!.body}`).join("\n")}`;
|
|
170
282
|
return { text: head + (tidy ? `\n${tidy}` : "") };
|
|
171
283
|
}
|
|
172
284
|
|
|
173
|
-
/** `flow reflect tidy` —
|
|
285
|
+
/** `flow reflect tidy` — move the closed (`- [x]`) items to reflections-archive.md. Deleting them lost the
|
|
286
|
+
* `— fixed:` note and, after a mistaken close, the row itself (gh#263); archived, a row can be reopened and its
|
|
287
|
+
* id is never handed out again. */
|
|
174
288
|
export function reflectTidy(root: string): RunResult {
|
|
175
289
|
const file = path.join(dfDir(root), "reflections.md");
|
|
176
290
|
if (!existsSync(file)) return { text: "reflections: nothing to tidy (no queue yet)" };
|
|
177
|
-
const text =
|
|
291
|
+
const text = readReflectionsText(root);
|
|
178
292
|
const closed = doneItemCount(text);
|
|
179
293
|
const open = openChecklistItems(text).length;
|
|
180
294
|
if (!closed) return { text: `reflections: nothing to tidy (${open} open, 0 closed)` };
|
|
295
|
+
writeFileSync(reflectArchiveFile(root), archiveAppend(readReflectArchive(root), closedRowsBySection(text), now().slice(0, 10)));
|
|
181
296
|
writeFileSync(file, reflectionsTidy(text));
|
|
182
|
-
return { text: `reflections:
|
|
297
|
+
return { text: `reflections: moved ${closed} closed item(s) to .dev-flow/reflections-archive.md — ${open} open; ids are unchanged (flow reflect reopen <id> brings one back)` };
|
|
183
298
|
}
|
package/src/runtime/setup.ts
CHANGED
|
@@ -82,4 +82,4 @@ export function renderQuestions(qs: SetupQuestion[]): string[] {
|
|
|
82
82
|
return out;
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
export const GIT_TRACK_NOTE = AGENT_MARK + 'the playbook belongs in git: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force-add: a root .gitignore may exclude .dev-flow/ entirely — tracked once, the ignore stops mattering; the env prefix is for the pre-commit hook, dev-flow itself lets a main commit whose only change is the playbook)';
|
|
85
|
+
export const GIT_TRACK_NOTE = AGENT_MARK + 'the playbook belongs in git, with the folder\'s ignore file (untracked, a fresh clone loses it and every feature dir reads as uncommitted work): git add -f .dev-flow/project.md .dev-flow/.gitignore && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force-add: a root .gitignore may exclude .dev-flow/ entirely — tracked once, the ignore stops mattering; the env prefix is for the pre-commit hook, dev-flow itself lets a main commit whose only change is the playbook)';
|
package/src/runtime/ship.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/** dev-flow runtime — The gates that ship: verify, release, release-done, finish. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
2
|
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { applicableItems, changelogVersionsBetween, normalizeReleaseBody, pendingEntryLines, pickReleaseNotes, checklistHash, checklistPending, cmpVersions, freshenChecks, healthProbe, mergeShapeProof, preReleaseGate, reflectionNudges, conflictMarkerLines, isReleaseOnly, looksLikeShellError, needsOperator, newestTaggedVersion, nextHint, releaseGate, parseVersion, roadmapDoneForSlug, sq, tagNotesCommand, verifyGate, versionTagGate, servedBuildMatches, prepFiles, versionArg, playbookVersionChoice, describeVersionChoice, majorBump, bumpVersion, isBumpKind, resolvedDevEnv, reviewOwed, localDefaultAhead, failTail } from "../core.ts";
|
|
4
|
+
import { skipsChecks, applicableItems, changelogVersionsBetween, normalizeReleaseBody, pendingEntryLines, pickReleaseNotes, checklistHash, checklistPending, cmpVersions, freshenChecks, healthProbe, mergeShapeProof, preReleaseGate, reflectionNudges, conflictMarkerLines, isReleaseOnly, looksLikeShellError, needsOperator, newestTaggedVersion, nextHint, releaseGate, parseVersion, roadmapDoneForSlug, sq, tagNotesCommand, verifyGate, versionTagGate, servedBuildMatches, prepFiles, versionArg, playbookVersionChoice, describeVersionChoice, majorBump, bumpVersion, isBumpKind, resolvedDevEnv, reviewOwed, localDefaultAhead, failTail, operatorDirt } from "../core.ts";
|
|
5
5
|
import type { Config, FlowState } from "../core.ts";
|
|
6
6
|
import { AGENT_MARK } from "../present.ts";
|
|
7
|
-
import { buildSkew, copyWarning, currentBranch, featDir, flagValue, forgeMergeStyle, forgeOf, gateCwd, mergeBase, needState, now, originUrl, readReflectionsText, readRoadmap, readState, releaseTags, roadmapFile, sh, tail, worktreeAbs, writeState } from "./base.ts";
|
|
7
|
+
import { refreshDocsCode, buildSkew, copyWarning, currentBranch, featDir, flagValue, forgeMergeStyle, forgeOf, gateCwd, mergeBase, needState, now, originUrl, readReflectionsText, readRoadmap, readState, releaseTags, roadmapFile, sh, tail, worktreeAbs, writeState } from "./base.ts";
|
|
8
8
|
import { type RunResult, ago, releaseDevSlot, keepThroughPrep, branchState, catchUp, describeBranchState, devEnv, devPortOf, devSlotCheck, healthRerunsAfterDeploy, pendingChecks, probeHealth, readDevPorts, runChecks, slotKey, triedNote, unreleasedOnMain, worktreeFingerprint, writeDevPorts } from "./checks.ts";
|
|
9
9
|
import { type GateCtx, markPendingAsk } from "./gates.ts";
|
|
10
|
+
import { closeLinkedReflections } from "./reflect.ts";
|
|
10
11
|
import { gatePublishes, prBodyOwed, publishRelease } from "./publish.ts";
|
|
11
12
|
|
|
12
13
|
/** gh#198: the version question asked with Verified? — null when it is not the operator's to answer here
|
|
@@ -42,6 +43,7 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
42
43
|
const fpAtGate = await worktreeFingerprint(gateCwd(root, state!));
|
|
43
44
|
const staleAtGate = freshenChecks(state!, fpAtGate, (n) => n === "health" && healthRerunsAfterDeploy(cfg));
|
|
44
45
|
if (staleAtGate.length) writeState(root, state!);
|
|
46
|
+
await refreshDocsCode(root, state!, cfg); // a docs flow whose diff reaches code owes the checks like any flow
|
|
45
47
|
const pending = pendingChecks(state!, cfg);
|
|
46
48
|
const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
|
|
47
49
|
if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
|
|
@@ -354,7 +356,8 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
354
356
|
// tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
|
|
355
357
|
// The checks this gate needs green are run by the gate, as verify does (#84) — after the cheap proofs, so a
|
|
356
358
|
// wrong version or a missing changelog entry is refused before minutes are spent on a suite.
|
|
357
|
-
|
|
359
|
+
await refreshDocsCode(root, state!, cfg);
|
|
360
|
+
const owed = skipsChecks(state!) ? [] : cfg.checkList.filter((c) => !state!.checks[c.name]?.ok);
|
|
358
361
|
const assumed = { ...state!.checks, ...Object.fromEntries(owed.map((c) => [c.name, { ok: true, at: now() }])) };
|
|
359
362
|
const gateState = (checks: FlowState["checks"]) => ({ ...state!, checks, noVersion, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } });
|
|
360
363
|
const cheap = preReleaseGate(gateState(assumed), cfg, prep);
|
|
@@ -772,7 +775,9 @@ export async function gateFinishCore(o: GateCtx): Promise<RunResult> {
|
|
|
772
775
|
return { text: `finish closes a released feature — stage is "${state!.stage}" and no release is recorded; publish it first — flow release (to abandon an unfinished feature, run flow abort)`, isError: true };
|
|
773
776
|
// after this the flow state is gone: nothing may sit uncommitted or unpushed
|
|
774
777
|
const dirty = await sh("git status --porcelain", root);
|
|
775
|
-
|
|
778
|
+
// dev-flow's own folder is never the operator's uncommitted work — another flow's state least of all
|
|
779
|
+
const work = dirty.ok ? operatorDirt(dirty.out) : "";
|
|
780
|
+
if (work.trim()) return { text: `main checkout has uncommitted changes — commit them first (finish deletes .dev-flow/${state!.slug}/):\n${tail(work)}`, isError: true };
|
|
776
781
|
const origin = await originUrl(root);
|
|
777
782
|
const hasOriginF = origin !== null;
|
|
778
783
|
// gh#234/gh#228: judge the local default branch, not whatever HEAD the main checkout happens to be on, and
|
|
@@ -960,8 +965,12 @@ export async function gateFinishCore(o: GateCtx): Promise<RunResult> {
|
|
|
960
965
|
roadmapNote = ` roadmap: ${r.count} item(s) marked done.`;
|
|
961
966
|
}
|
|
962
967
|
}
|
|
968
|
+
// the reflection rows this flow was linked to close with it — the fix and the ledger agree the moment it ships
|
|
969
|
+
const closedRefl = closeLinkedReflections(root, state!, state!.publish?.pr ? ` (PR #${state!.publish.pr})` : "");
|
|
970
|
+
const deferred = (state!.reflections ?? []).filter((r) => r.deferred);
|
|
971
|
+
const reflNote = closedRefl.length || deferred.length ? ` reflections: ${closedRefl.length ? `closed ${closedRefl.map((n) => `r${n}`).join(", ")} as fixed by this flow` : ""}${closedRefl.length && deferred.length ? "; " : ""}${deferred.length ? `left open ${deferred.map((r) => `r${r.id} (${r.deferred})`).join(", ")}` : ""}.` : "";
|
|
963
972
|
// finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
|
|
964
973
|
const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
|
|
965
974
|
const nudgeNote = [nudge.fix, nudge.tidy].filter(Boolean).map((n) => ` ${n} — offer it to the operator.`).join("");
|
|
966
|
-
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${devDownNote}${roadmapNote}${forgeSkipNote}${reflectSkipNote}${quietNote}${releaseChecksNote}${autoNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
975
|
+
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${devDownNote}${roadmapNote}${reflNote}${forgeSkipNote}${reflectSkipNote}${quietNote}${releaseChecksNote}${autoNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
967
976
|
}
|