pi-dev-flow 0.85.0 → 0.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,2653 +16,31 @@
16
16
  * per session (pi only advertises a skill; it never loads it unasked) and the
17
17
  * one playbook reference file the current stage needs.
18
18
  *
19
- * The stage logic lives in src/core.ts (unit-tested); this file is pi wiring.
19
+ * The stage logic lives in src/core.ts (unit-tested), the runtime in src/runtime/; this file is pi wiring.
20
20
  * Inactive (fully pass-through) in repos without a .dev-flow/ directory.
21
21
  */
22
- import { exec } from "node:child_process";
23
- import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statfsSync, writeFileSync } from "node:fs";
24
- import { createServer } from "node:net";
25
- import { freemem } from "node:os";
22
+ import { existsSync, mkdirSync, rmSync } from "node:fs";
26
23
  import path from "node:path";
27
- import { promisify } from "node:util";
28
- import { Type } from "@earendil-works/pi-ai";
29
- import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
30
- import type { ExtensionAPI, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent";
31
- import {
32
- ALLOW_REWRITE,
33
- approveGate,
34
- applicableItems,
35
- appendReflection,
36
- appendRoadmapItem,
37
- bashFlowGuard,
38
- checkFingerprint,
39
- changelogVersionsBetween,
40
- normalizeReleaseBody,
41
- pendingEntryLines,
42
- pickReleaseNotes,
43
- checklistHash,
44
- checklistPending,
45
- checkoutInvocation,
46
- claimBlocks,
47
- classifyMergeHistory,
48
- cmpVersions,
49
- doneItemCount,
50
- detectForge,
51
- extractSkillCore,
52
- featureBranchPrefix,
53
- FLOW_SHELL_HINT,
54
- flowShellInvocation,
55
- forcePushInvocation,
56
- freshenChecks,
57
- gateHelpJson,
58
- gitInvocation,
59
- githubSlug,
60
- guardBash,
61
- guardPath,
62
- healthProbe,
63
- healthRetry,
64
- mergeShapeProof,
65
- mergeStyleInvocation,
66
- parseMergeStyle,
67
- investigationBrief,
68
- parseLsRemoteTags,
69
- parsePushRefs,
70
- playbookTamper,
71
- playbookOnlyChange,
72
- pluginVersion,
73
- preReleaseGate,
74
- guessReflectSections,
75
- reflectItems,
76
- reflectMove,
77
- reflectDone,
78
- reflectProtocol,
79
- reflectUnfiledCount,
80
- reflectLegacyPluginCount,
81
- reflectionNudges,
82
- pluginIssueRecipe,
83
- type ReflectTarget,
84
- buildReflectBrief,
85
- parseReflectReport,
86
- renderReflectFindings,
87
- childSessionFiles,
88
- conflictMarkerLines,
89
- isReleaseOnly,
90
- digestTranscript,
91
- workerSteer,
92
- WORKER_STEER_AT,
93
- WORKER_SALVAGE,
94
- WORKER_SALVAGE_MS,
95
- WORKER_NUDGE_READONLY,
96
- type SessionHeaderInfo,
97
- reflectionLine,
98
- reflectionRoutes,
99
- reflectionsTidy,
100
- type ReflectItem,
101
- type ReflectSection,
102
- stageReference,
103
- sessionRunsOlderBuild,
24
+ import { Type } from "typebox";
25
+ import { compact, defineTool, isToolCallEventType, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
26
+ import { type ExtensionAPI, type ToolCallEvent, type ToolCallEventResult, type TurnEndEvent, type TurnEndEventResult } from "@earendil-works/pi-coding-agent";
27
+ import { ALLOW_REWRITE, applicableItems, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, WORKER_STEER_AT, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
28
+ import { loadProject } from "../src/projectmd.ts";
29
+ import { bashTimeout, requireTimeout, timeoutClass } from "../src/timeouts.ts";
30
+ import { AGENT_MARK, operatorCommandAsks, operatorCommandCorrection, viewHeader, askLine, type GateView } from "../src/present.ts";
31
+ import { Text } from "@earendil-works/pi-tui";
32
+ import { CONTEXT_EMITTED, COPIES, GATE_HELP, SELF_BUILD, SKILL_DIR, type Ui, WEB_CHIP_KEYS, baseSeams, bindings, boundFeature, claimBlocker, claimFile, compacting, compactionTakeover, coreInjected, coreStale, currentBranch, dfDir, featDir, featureRefs, flowCompactInstructions, flowRoot, guardsAreMine, initiated, lastContext, loadedVersion, maybeCompactNow, noteFriction, now, readClaim, readReflections, readReflectionsText, readRoadmap, readState, registerCopy, releaseSession, sessionKey, sh, skillCore, unfinishedStates, worktreeAbs, writeClaim, writeState } from "../src/runtime/base.ts";
33
+ import { type Session, presentRun } from "../src/runtime/checks.ts";
34
+ import { isSelfRepo } from "../src/runtime/setup.ts";
35
+ import { foldView, pluginUpstream } from "../src/runtime/reflect.ts";
36
+ import { type FlowHooks, runFlow } from "../src/runtime/gates.ts";
37
+ import { PIWEB_SUBAGENT, WORKER_TOOLS, piwebLiveClaim, piwebStamp, piwebWorkerMeta, reflectSeams, sessionHeaders, stageWorkerSpawn, workerName, workerSessions, workerTiming, writeTranscriptDigests } from "../src/runtime/workers.ts";
38
+ export { compactionTakeover } from "../src/runtime/base.ts";
39
+ export { reflectSeams, stageWorkerSpawn, workerTiming } from "../src/runtime/workers.ts";
104
40
 
105
- listFiles,
106
- looksLikeShellError,
107
- needsOperator,
108
- newestTaggedVersion,
109
- newState,
110
- nextHint,
111
- openChecklistItems,
112
- releaseGate,
113
- parseVersion,
114
- roadmapDone,
115
- roadmapDoneForSlug,
116
- roadmapOpenCount,
117
- roadmapBriefFor,
118
- roadmapPick,
119
- roadmapTidy,
120
- shouldSelfCompact,
121
- shouldTakeOverCompaction,
122
- stageGuidance,
123
- stateTamper,
124
- statusFor,
125
- statusJson,
126
- subst,
127
- sq,
128
- featureTmpDir,
129
- featureTmpEnv,
130
- compactionStateBlock,
131
- foreignWorktreeLinks,
132
- withTmpDir,
133
- tagNotesCommand,
134
- validSlug,
135
- verifyGate,
136
- versionTagGate,
137
- widgetLines,
138
- chipLabel,
139
- writeGuard,
140
- mainCheckoutRoot,
141
- buildWorkerBrief,
142
- clampBudgetMin,
143
- parseWorkerReport,
144
- workerTurnError,
145
- workerOpError,
146
- WORKER_NUDGE,
147
- WORKER_NUDGES,
148
- type WorkerOp,
149
- releaseOrderInvocation,
150
- type BranchState,
151
- type Config,
152
- type DevSlot,
153
- formatSize,
154
- servedBuildMatches,
155
- sideBySide,
156
- type FeatureRef,
157
- type FlowState,
158
- type StageCheck,
159
- type PushRef,
160
- type SessionClaim,
161
- } from "../src/core.ts";
162
- import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
163
- import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
164
- import { bashTimeout, requireTimeout } from "../src/timeouts.ts";
165
- import { detectProject, type Detection } from "../src/detect.ts";
166
-
167
- const execAsync = promisify(exec);
168
-
169
- /** This build's own identity, read once at load: it is what this session's code IS — an update that
170
- * rewrites the package on disk later does not change the code already running. */
171
- const SELF_BUILD = pluginVersion(import.meta.dirname);
172
-
173
- /** The dev-flow build this session actually loaded — see sessionRunsOlderBuild. The load-time
174
- * manifest, never a fresh read: re-reading the package after an in-place update reported the NEW
175
- * version as loaded and the stale one as shipped (lettuce rail-ui-fixes, 0.79.0 → 0.80.0).
176
- * DEV_FLOW_LOADED_VERSION (read at call time) can stand in for it (the smoke suite runs gates
177
- * in-process and needs to pretend it is an old session): the override can only ever make a gate more
178
- * cautious — it never lifts a proof, it turns a release into a warn-and-ask. */
179
- function loadedVersion(): string | null {
180
- return process.env.DEV_FLOW_LOADED_VERSION?.trim() || SELF_BUILD.version;
181
- }
182
-
183
- /** The dev-flow build this session *should* be running, as the disk describes it, and how to call it.
184
- * In the dev-flow repo that is the checkout's own manifest: main moves ahead of the installed copy at
185
- * every release, while `loadedVersion()` and the plugin's own package.json are the same file — so a
186
- * session running 0.54.0 in a checkout already at 0.58.1 compared equal and nothing anywhere said so.
187
- * In a normal project the only manifest is the installed package's, which a mid-session update moves. */
188
- function checkoutBuild(root: string): { version: string | null; dir: string; repo: string; label: string } {
189
- return isSelfRepo(root)
190
- ? { ...pluginVersion(root), label: "this checkout" }
191
- : { ...pluginVersion(import.meta.dirname), label: "the dev-flow install" }; // fresh: what the disk ships NOW
192
- }
193
-
194
- /** The build this session runs vs the one the disk ships: `behind` is the loaded version when they differ
195
- * ("" when current or unknown), `line` the one warning every surface prints for it. */
196
- function buildSkew(root: string): { disk: ReturnType<typeof checkoutBuild>; behind: string; line: string } {
197
- const disk = checkoutBuild(root);
198
- const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
199
- return { disk, behind, line: behind ? `this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version ?? "?"} — /reload rebinds session state; only restarting the host swaps the code it runs` : "" };
200
- }
201
-
202
- /** Cross-copy registry: one process can register dev-flow more than once (the documented
203
- * two-sources-at-once hazard: a project dogfood pointer plus an installed copy), and EVERY copy
204
- * evaluates every guard hook. The flow-tool binding belongs to whichever copy served the call,
205
- * so the other copy judges from a missing binding — claims on disk (see boundFeature) keep its
206
- * verdict honest, and these entries let `flow version`, `status` and `start` name the duplicate
207
- * instead of leaving a misattribution a mystery. Same-process only: it is a globalThis list. */
208
- interface CopyEntry {
209
- dir: string;
210
- version: string | null;
211
- pid: number;
212
- at: string;
213
- }
214
- const COPIES: CopyEntry[] = ((globalThis as { __piDevFlowCopies?: CopyEntry[] }).__piDevFlowCopies ??= []);
215
- function registerCopy(): void {
216
- const mine = COPIES.find((r) => r.dir === SELF_BUILD.dir && r.pid === process.pid);
217
- if (mine) Object.assign(mine, { version: loadedVersion(), at: new Date().toISOString() });
218
- else COPIES.push({ dir: SELF_BUILD.dir, version: loadedVersion(), pid: process.pid, at: new Date().toISOString() });
219
- }
220
- function otherCopies(): CopyEntry[] {
221
- return COPIES.filter((r) => r.pid === process.pid && r.dir !== SELF_BUILD.dir);
222
- }
223
- /** Election: when one process runs several dev-flow copies (the documented two-sources hazard, or a
224
- * copy whose loaded code predates an update), only the highest-version copy may judge — stale code
225
- * must not veto tool calls with a build nobody reviewed. Node cannot unload a loaded module and pi
226
- * cannot unregister its hooks, so silence is the most removal can be from inside the package; only
227
- * a host restart truly drops stale code. Equal versions both judge (same code, same verdicts); a
228
- * copy whose version cannot be read is never outranked. Gate tool/command handlers stay live on
229
- * every copy: the host dispatches a session's flow calls to whichever copy loaded that session,
230
- * and staleness there is what the /reload warnings address. */
231
- function guardsAreMine(): boolean {
232
- const mine = SELF_BUILD.version;
233
- if (!mine) return true; // an unreadable version is never outranked
234
- return !otherCopies().some((r) => r.version && cmpVersions(r.version, mine) > 0);
235
- }
236
- function copyWarning(): string | null {
237
- const dup = otherCopies();
238
- if (!dup.length) return null;
239
- const verdict = guardsAreMine() ? "this copy is the newest and judges the guards" : "this copy is older and stays silent \u2014 the newest copy judges";
240
- return `warning: ${dup.length} other dev-flow cop${dup.length === 1 ? "y" : "ies"} registered in this process: ${dup.map((d) => `${d.dir} (${d.version ?? "?"})`).join(", ")} \u2014 this call served by ${SELF_BUILD.dir} (${SELF_BUILD.version ?? "?"}); ${verdict}. Keep only one source you intend; a host restart drops stale code (README: two sources at once)`;
241
- }
242
41
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
243
42
  * entries and asserts the warnings the real duplicate would print. */
244
- export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined }, piweb: { meta: piwebWorkerMeta, stamp: piwebStamp, liveClaim: piwebLiveClaim, workerName } };
245
-
246
- interface Ui {
247
- hasUI: boolean;
248
- confirm: (title: string, message: string) => Promise<boolean>;
249
- }
250
-
251
- const now = () => new Date().toISOString();
252
-
253
- const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
254
-
255
- async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000, env?: Record<string, string>): Promise<{ ok: boolean; out: string }> {
256
- try {
257
- const { stdout, stderr } = await execAsync(command, { cwd, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) });
258
- return { ok: true, out: `${stdout}\n${stderr}`.trim() };
259
- } catch (e) {
260
- const err = e as { stdout?: string; stderr?: string; message?: string };
261
- return { ok: false, out: `${err.stdout ?? ""}\n${err.stderr ?? ""}`.trim() || String(err.message) };
262
- }
263
- }
264
-
265
- /** origin's URL, or null when the repo has no origin. */
266
- async function originUrl(root: string): Promise<string | null> {
267
- const r = await sh("git remote get-url origin", root, 10_000);
268
- return r.ok && r.out.trim() ? r.out.trim() : null;
269
- }
270
-
271
- /** The forge the release machinery targets: the playbook's `forge`, else detected from origin ("self" without one). */
272
- const forgeOf = (cfg: Config, origin: string | null): string => cfg.forge || detectForge(origin ?? "");
273
-
274
- /** The branch's merge base with the default branch (origin's when fetched), or "" when git cannot say. */
275
- async function mergeBase(cwd: string, defaultBranch: string): Promise<string> {
276
- const mb = await sh(`git merge-base origin/${sq(defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(defaultBranch)} HEAD 2>/dev/null || true`, cwd);
277
- return mb.ok ? mb.out.trim() : "";
278
- }
279
-
280
- /** The published pi-dev-flow version (`--check-upstream`), or "" when the registry cannot be asked. */
281
- async function publishedVersion(root: string): Promise<string> {
282
- const pub = await sh("npm view pi-dev-flow version", root);
283
- return pub.ok ? (pub.out.trim().split("\n").pop() ?? "") : "";
284
- }
285
-
286
- const dfDir = (root: string) => path.join(root, ".dev-flow");
287
- /** dev-flow is initiated once the operator playbook exists: before flow init writes project.md the
288
- * extension is silent in that folder — no injections, no guards (not even the no-playbook bash-timeout
289
- * default), no footer. The flow tool itself stays registered so flow init remains callable. */
290
- const initiated = (root: string): boolean => existsSync(path.join(dfDir(root), "project.md"));
291
-
292
- /** A `--merge=squash` style flag, or null when absent. Returned as the raw string: the caller validates it
293
- * with parseMergeStyle so a typo is reported instead of ignored. */
294
- function flagValue(rest: string[], name: string): string | null {
295
- for (const a of rest) {
296
- const m = a.match(new RegExp(`^--${name}=([\\s\\S]+)$`)); // a --brief= value spans lines
297
- if (m) return m[1];
298
- }
299
- return null;
300
- }
301
-
302
- /** One cheap first-parent log tells the operator what their repo actually does when a PR merges: merge
303
- * commits or one squashed commit per PR. `flow init` and `flow start` ask with this evidence instead of
304
- * asking blind; null when there is no default-branch log to read. */
305
- async function mergeHistoryEvidence(root: string, defaultBranch: string): Promise<{ note: string; recent: "squash" | "merge" | "rebase" | null } | null> {
306
- const log = await sh(`git log --first-parent -n 40 --format=%p|%s ${sq(`origin/${defaultBranch}`)} 2>/dev/null || git log --first-parent -n 40 --format=%p|%s ${sq(defaultBranch)} 2>/dev/null`, root);
307
- if (!log.ok || !log.out.trim()) return null;
308
- const c = classifyMergeHistory(log.out.split("\n"));
309
- return { note: c.note, recent: c.recent };
310
- }
311
-
312
- /** How the forge says the PR landed, when it can be asked — the only way to tell a squash from a rebase,
313
- * because both erase the branch's ancestry. null = unaskable (self-hosted, no CLI, no merged PR found). */
314
- async function forgeMergeStyle(root: string, forge: string, branch: string): Promise<"squash" | "merge" | "rebase" | null> {
315
- if (!branch) return null;
316
- // sh() folds stderr into stdout, so a CLI error can arrive where the JSON was expected: parse defensively
317
- const json = (out: string): unknown | null => {
318
- try {
319
- return JSON.parse(out);
320
- } catch {
321
- return null;
322
- }
323
- };
324
- if (forge === "github") {
325
- const pr = await sh(`gh pr list --state merged --head ${sq(branch)} --json number,squashCommit,rebaseCommit,mergeCommit --jq '.[0]'`, root);
326
- if (!pr.ok || !pr.out.trim() || pr.out.trim() === "null") return null;
327
- const parsed = json(pr.out.trim()) as { squashCommit?: string | null; rebaseCommit?: string | null; mergeCommit?: string | null } | null;
328
- return parsed?.squashCommit ? "squash" : parsed?.rebaseCommit ? "rebase" : parsed?.mergeCommit ? "merge" : null;
329
- }
330
- if (forge === "gitlab") {
331
- const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${branch}&state=merged&per_page=1`)}`, root);
332
- if (!mr.ok || !mr.out.trim() || mr.out.trim() === "[]") return null;
333
- const list = json(mr.out.trim()) as { squash_commit_sha?: string | null; merge_commit_sha?: string | null }[] | null;
334
- const parsed = Array.isArray(list) ? list[0] : null;
335
- return parsed?.squash_commit_sha ? "squash" : parsed?.merge_commit_sha ? "merge" : null;
336
- }
337
- return null;
338
- }
339
-
340
- /**
341
- * Write the merge policy into the playbook with a single-line insert — never a draft regeneration, which
342
- * cannot reproduce hand-written prose and checklist items and would drop them. Validated before it is
343
- * written and kept as `.bak`, exactly like `flow init --write`. The commit is the playbook chore the guard
344
- * already blesses, and only when the playbook is the only dirty path: a gate never sweeps someone else's
345
- * work into a chore commit.
346
- */
347
- async function writePlaybookMergePolicy(root: string, style: string): Promise<{ note: string } | { err: string }> {
348
- const mdFile = path.join(dfDir(root), "project.md");
349
- if (!existsSync(mdFile)) return { err: "no .dev-flow/project.md to write the policy into — run flow init first" };
350
- const ins = setPlaybookKey(readFileSync(mdFile, "utf8"), "release", "merge", style);
351
- if ("error" in ins) return { err: ins.error };
352
- const parsed = parseProjectMd(ins.text);
353
- if (parsed.hard.length) return { err: `refusing to write project.md — the result would not parse:\n- ${parsed.hard.join("\n- ")}` };
354
- copyFileSync(mdFile, `${mdFile}.bak`);
355
- writeFileSync(mdFile, ins.text);
356
- const dirty = await sh("git status --porcelain", root);
357
- const onlyPlaybook = dirty.ok && dirty.out.trim().split("\n").every((l) => l.trim().endsWith(" .dev-flow/project.md"));
358
- const tracked = (await sh("git ls-files --error-unmatch .dev-flow/project.md", root)).ok;
359
- let note = `merge = ${style} written to .dev-flow/project.md (${ins.where}; previous copy kept as project.md.bak)`;
360
- if (tracked && onlyPlaybook) {
361
- const commit = await sh(`git add .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(`playbook: merge policy = ${style}`)}`, root);
362
- note += commit.ok ? " — committed as a playbook chore" : ` — commit failed (${tail(commit.out)}); commit it yourself`;
363
- } else note += `. ${GIT_TRACK_NOTE}`;
364
- return { note };
365
- }
366
-
367
- /**
368
- * Run the health probe with the playbook's wait budget (#42). A service whose readiness lags its
369
- * container start can never pass a single shot, and hand-writing a poll loop into every playbook was
370
- * the workaround; the gate waits and says how long it tried. Attempts/schedule: core.healthRetry.
371
- */
372
- async function runHealthProbe(cmd: string, cwd: string, waitSec: number, env?: Record<string, string>): Promise<{ ok: boolean; out: string; attempts: number }> {
373
- const { attempts, delayMs } = healthRetry(waitSec);
374
- const deadline = Date.now() + waitSec * 1000; // the budget is wall time: a slow probe must not multiply it by its own duration
375
- let res = { ok: false, out: "" };
376
- for (let i = 1; ; i++) {
377
- res = await sh(cmd, cwd, undefined, env);
378
- if (res.ok || i >= attempts || Date.now() >= deadline) return { ...res, attempts: i };
379
- await sleep(delayMs);
380
- }
381
- }
382
-
383
- /** Tags to judge a release against: what origin holds — a clone that has not fetched must not get to
384
- * decide what is already tagged (#52). Local tags only when there is no remote to ask; null when an
385
- * origin exists but could not be asked (offline, no ssh agent) — then local tags must not stand in. */
386
- async function releaseTags(root: string): Promise<string[] | null> {
387
- if (!(await originUrl(root))) return (await sh("git tag --sort=-creatordate", root)).out.split("\n").filter(Boolean);
388
- const remote = await sh("git ls-remote --tags origin", root);
389
- if (!remote.ok) return null;
390
- return parseLsRemoteTags(remote.out);
391
- }
392
-
393
- const GATE_HELP =
394
- "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
395
- const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
396
- const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
397
- const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
398
-
399
- function readState(root: string, slug: string): FlowState | null {
400
- try {
401
- return JSON.parse(readFileSync(stateFile(root, slug), "utf8")) as FlowState;
402
- } catch {
403
- return null;
404
- }
405
- }
406
-
407
- function writeState(root: string, state: FlowState): void {
408
- atomicWrite(stateFile(root, state.slug), `${JSON.stringify(state, null, "\t")}\n`);
409
- }
410
-
411
- /** Replace a file in one move. Gates write state after every check, and a kill in the middle left a
412
- * truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
413
- * and every recorded check, with the folder gitignored so nothing else could restore it. */
414
- function atomicWrite(file: string, text: string): void {
415
- const tmp = `${file}.tmp`;
416
- writeFileSync(tmp, text);
417
- renameSync(tmp, file);
418
- }
419
-
420
- /** Session bindings: one flow per pi session; persisted per session branch via appendEntry.
421
- * Module-level means shared by every session in the process — pi runs many sessions inside one Node
422
- * process (pi-web's agent lives in the server) — so every key here is a session identity and every
423
- * entry is released when that session ends (see releaseSession). */
424
- const bindings = new Map<string, string | null>();
425
- // Two identities are possible: pi's session id, or — when the host hands out none — the working
426
- // directory. Both are prefixed, because a claim written under the directory identity is not a session:
427
- // two pi sessions sharing one directory share that key, and `cwd:` in a claim file says so out loud
428
- // instead of reading like a session that went missing.
429
- const sessionKey = (ctx: { cwd: string; sessionManager?: { getSessionId(): string } }): string =>
430
- ctx.sessionManager?.getSessionId() ? `sid:${ctx.sessionManager.getSessionId()}` : `cwd:${ctx.cwd}`;
431
- /** Sessions with a dev-flow-initiated compaction in flight (prevents stacked compactions). */
432
- const compacting = new Set<string>();
433
- /** Sessions that already received the skill's always-on core this session. The `dev-flow-skill`
434
- * entry records the injection in the session branch, so /reload, resume and fork restore the fact
435
- * instead of paying ~1k tokens a second time. */
436
- const coreInjected = new Set<string>();
437
- /** Sessions whose last compaction dropped the core out of context — the next run pays it once more. */
438
- const coreStale = new Set<string>();
439
- /** The skill dir of THIS loaded copy: the copy a session runs and a development checkout can be
440
- * different installs, so playbook paths resolve from the code actually loaded — never from cwd. */
441
- const SKILL_DIR = path.join(import.meta.dirname, "..", "skills", "dev-flow");
442
- let skillCoreCache: string | null | undefined;
443
- /** The core block between SKILL.md's markers, read once per process (/reload reloads the module
444
- * and picks up edits). Null — no file, no markers, empty core — leaves every message exactly as it
445
- * was: a copy shipped without its skill must not take the guards, or the run, down. */
446
- function skillCore(): string | null {
447
- // Seam first: a test cannot ship a copy of the package with its skills/ directory deleted.
448
- if (testSeams.skillCore.value !== undefined) return testSeams.skillCore.value;
449
- if (skillCoreCache === undefined) {
450
- try {
451
- skillCoreCache = extractSkillCore(readFileSync(path.join(SKILL_DIR, "SKILL.md"), "utf8"));
452
- } catch {
453
- skillCoreCache = null;
454
- }
455
- }
456
- return skillCoreCache;
457
- }
458
-
459
- /** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
460
- export const compactionTakeover: { run: typeof compact } = { run: compact };
461
-
462
- /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
463
- const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
464
-
465
- /** Every feature with a state file — finish deletes the state, so whatever is on disk is unfinished. */
466
- function unfinishedStates(root: string): FlowState[] {
467
- if (!existsSync(dfDir(root))) return [];
468
- return readdirSync(dfDir(root), { withFileTypes: true })
469
- .filter((d) => d.isDirectory())
470
- .map((d) => readState(root, d.name))
471
- .filter((s): s is FlowState => !!s);
472
- }
473
-
474
- /** Open items of the agent's suggestion queue (.dev-flow/reflections.md), each with its section. */
475
- const readReflections = (root: string): ReflectItem[] => {
476
- const f = path.join(dfDir(root), "reflections.md");
477
- return existsSync(f) ? reflectItems(readFileSync(f, "utf8")) : [];
478
- };
479
-
480
- /** Raw reflections.md content — the closed-item count needs the checked lines the open-only reader drops. */
481
- const readReflectionsText = (root: string): string => {
482
- const f = path.join(dfDir(root), "reflections.md");
483
- return existsSync(f) ? readFileSync(f, "utf8") : "";
484
- };
485
-
486
- const roadmapFile = (root: string) => path.join(dfDir(root), "roadmap.md");
487
- const readRoadmap = (root: string): string => {
488
- const f = roadmapFile(root);
489
- return existsSync(f) ? readFileSync(f, "utf8") : "";
490
- };
491
-
492
- /** The session's feature — explicit bindings only: flow start/flow use bind, resume restores from session
493
- * history. Never binds on its own: an unbound session stays unbound however few features are unfinished,
494
- * and reading it must never claim anything. The claim on disk IS the persisted binding — bind() stamps the
495
- * session key into claim.json — so trust the disk after the in-memory map: a second registered dev-flow
496
- * copy (both copies evaluate the guard hooks) or a re-instantiated module then attributes the session's
497
- * own feature from disk instead of misjudging with stage null. */
498
- function boundFeature(root: string, key: string): FlowState | null {
499
- const bound = bindings.get(key);
500
- if (bound) {
501
- const s = readState(root, bound);
502
- if (s) return s;
503
- }
504
- return unfinishedStates(root).find((s) => readClaim(root, s.slug)?.key === key) ?? null;
505
- }
506
-
507
- function readClaim(root: string, slug: string): SessionClaim | null {
508
- try {
509
- return JSON.parse(readFileSync(claimFile(root, slug), "utf8")) as SessionClaim;
510
- } catch {
511
- return null;
512
- }
513
- }
514
-
515
- const writeClaim = (root: string, slug: string, key: string) =>
516
- atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
517
-
518
- /** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
519
- * never dies, so a claim left behind by a finished session keeps refusing every later session with
520
- * "claimed by another live session" — the lock has to end with the session that wrote it. Idempotent:
521
- * shutdown, reload and process exit can converge on this path. */
522
- function releaseSession(root: string, key: string): void {
523
- bindings.delete(key);
524
- compacting.delete(key);
525
- coreInjected.delete(key);
526
- coreStale.delete(key);
527
- if (!existsSync(dfDir(root))) return;
528
- for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
529
- if (!d.isDirectory()) continue;
530
- if (readClaim(root, d.name)?.key === key) rmSync(claimFile(root, d.name), { force: true });
531
- }
532
- }
533
-
534
- /** A lone unfinished feature another live session holds — lets the unbound-context message name it and offer the explicit takeover. */
535
- function claimBlocker(root: string, key: string): { state: FlowState; claim: SessionClaim } | null {
536
- const un = unfinishedStates(root);
537
- if (un.length !== 1) return null;
538
- const claim = readClaim(root, un[0].slug);
539
- return claim && claimBlocks(claim, key) ? { state: un[0], claim } : null;
540
- }
541
-
542
- /** Flow-aware focus for any compaction dev-flow initiates — state lives on disk, the summary must not invent it. */
543
- const flowCompactInstructions = (st: FlowState) =>
544
- `dev-flow feature "${st.slug}", stage "${st.stage}" — flow state is persisted on disk (state.json, plan/). Preserve verbatim: operator answers not yet recorded by a gate, reasons for uncommitted changes, and the exact next action from the last exchange.`;
545
-
546
- /**
547
- * Flow-aware self-compaction at safe points: called after a successful gate (state just hit disk),
548
- * at every turn_end and when a run settles. Only fires within COMPACT_MARGIN of pi's own threshold
549
- * (computed with the *effective* reserveTokens — settings + model overrides, like pi does) and
550
- * never while chat-only state is pending (open dialog, undigested plan) — see shouldSelfCompact.
551
- */
552
- function maybeCompactNow(ctx: ExtensionContext, root: string): void {
553
- if (!initiated(root)) return;
554
- const u = ctx.getContextUsage?.(); // minimal/fake contexts may lack usage info — treat as unknown
555
- if (!u || u.tokens === null) return;
556
- const key = sessionKey(ctx);
557
- const st = boundFeature(root, key);
558
- if (!st) return;
559
- let reserve: number;
560
- try {
561
- const settings = SettingsManager.create(ctx.cwd); // throws on a malformed compaction setting — pi surfaces that itself; we just stay out
562
- if (!settings.getCompactionEnabled()) return; // operator turned auto-compaction off — don't do it behind their back
563
- reserve = settings.getCompactionReserveTokens(ctx.model);
564
- } catch {
565
- return;
566
- }
567
- const cfg = loadProject(dfDir(root)).cfg;
568
- const decision = {
569
- tokens: u.tokens,
570
- contextWindow: u.contextWindow,
571
- stage: st.stage,
572
- planFiles: listFiles(path.join(featDir(root, st.slug), "plan")).length,
573
- checklistPending: checklistPending(cfg, st, st.stage),
574
- compacting: compacting.has(key),
575
- };
576
- if (!shouldSelfCompact(decision, reserve)) return;
577
- compacting.add(key);
578
- const done = () => compacting.delete(key);
579
- try {
580
- ctx.compact({ customInstructions: flowCompactInstructions(st), onComplete: done, onError: done });
581
- } catch {
582
- done(); // a throw before the run started must not leave the flag set: that switched off self-compaction and the takeover for the rest of the session
583
- }
584
- }
585
-
586
- function featureRefs(root: string): FeatureRef[] {
587
- return unfinishedStates(root).map((s) => ({ state: s, worktreeAbs: s.worktree ? path.resolve(root, s.worktree) : null }));
588
- }
589
-
590
- function worktreeAbs(root: string, state: FlowState): string | null {
591
- return state.worktree ? path.resolve(root, state.worktree) : null;
592
- }
593
-
594
- /** Git-level consistency probes for the doctor: orphan worktrees/branches, features missing their worktree. */
595
- async function gitConsistency(root: string, cfg: Config): Promise<string[]> {
596
- const feats = unfinishedStates(root);
597
- const out: string[] = [];
598
- const wtRoot = path.resolve(root, cfg.worktreeDir.split("{")[0]);
599
- const owned = new Set(feats.map((f) => (f.worktree ? path.resolve(root, f.worktree) : "")));
600
- const wtRaw = await sh("git worktree list --porcelain", root);
601
- if (wtRaw.ok)
602
- for (const line of wtRaw.out.split("\n")) {
603
- if (!line.startsWith("worktree ")) continue;
604
- const abs = path.resolve(line.slice(9).trim());
605
- if (abs !== path.resolve(root) && abs.startsWith(wtRoot) && !owned.has(abs)) out.push(`orphan worktree ${path.relative(root, abs)} — no feature owns it (git worktree remove)`);
606
- }
607
- const ownedBr = new Set(feats.map((f) => f.branch));
608
- const brRaw = await sh(`git branch --list ${sq(`${featureBranchPrefix(cfg)}*`)}`, root);
609
- if (brRaw.ok)
610
- // git marks the current branch with "* " and a worktree-checked-out one with "+ " — strip both, or an active feature's own branch never matches ownedBr
611
- for (const b of brRaw.out.split("\n").map((x) => x.replace(/^[*+]?\s+/, "").trim()).filter(Boolean)) {
612
- if (!ownedBr.has(b)) out.push(`orphan branch ${b} — no unfinished feature owns it (git branch -D ${b})`);
613
- }
614
- // an aborted feature is a designed state, not drift: the abort echo tells the operator to remove
615
- // the worktree by hand, and the stamp keeps that cleanup from being re-reported forever (gh#138)
616
- for (const f of feats) if (f.worktree && !f.aborted && !existsSync(path.resolve(root, f.worktree))) out.push(`feature ${f.slug} (${f.stage}) has no worktree at ${f.worktree}`);
617
- // the playbook belongs in git — an untracked project.md is invisible to teammates and lost on machine changes
618
- if (existsSync(path.join(root, ".dev-flow", "project.md")) && !(await sh("git ls-files --error-unmatch -- .dev-flow/project.md", root)).ok)
619
- out.push('.dev-flow/project.md is not tracked in git — track it: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force: a root .gitignore may exclude .dev-flow/ wholesale; the env prefix is for the installed hook — dev-flow allows a main commit whose only change is the playbook)');
620
- return out;
621
- }
622
-
623
- /** Where feature commands run: the feature worktree once it exists (that is where the
624
- * code under test lives), else the main checkout. Keeps gates off the main branch. */
625
- function gateCwd(root: string, state: FlowState): string {
626
- const wt = worktreeAbs(root, state);
627
- return wt && existsSync(wt) ? wt : root;
628
- }
629
-
630
- /** TMPDIR for the project commands a gate runs: the feature's own scratch dir, removed at finish —
631
- * a test suite's mkdtemp fixtures no longer pile up in the OS temp dir. */
632
- function featureEnv(root: string, state: FlowState): Record<string, string> {
633
- const dir = featureTmpDir(dfDir(root), state.slug);
634
- mkdirSync(dir, { recursive: true });
635
- return featureTmpEnv(dir);
636
- }
637
-
638
- /** The port this flow's dev deploy uses: the operator's pick for it, else the playbook default. */
639
- const devPortOf = (state: FlowState, cfg: Config): number | undefined => state.devPort ?? cfg.devPort;
640
-
641
- /** featureEnv plus where this flow's dev instance lives: $DEV_FLOW_PORT, $DEV_FLOW_INSTANCE (the slug) and
642
- * $DEV_FLOW_SUFFIX — "" on the default port, "-<slug>" on another — for a compose project name or container
643
- * prefix that must not collide with the instance already running. */
644
- function devEnv(root: string, state: FlowState, cfg: Config): Record<string, string> {
645
- const port = devPortOf(state, cfg);
646
- const side = state.devPort !== undefined && state.devPort !== cfg.devPort;
647
- return { ...featureEnv(root, state), ...(port !== undefined ? { DEV_FLOW_PORT: String(port) } : {}), DEV_FLOW_INSTANCE: state.slug, DEV_FLOW_SUFFIX: side ? `-${state.slug}` : "" };
648
- }
649
-
650
- // ---------------------------------------------------------------- dev stack registry
651
- // One machine, one dev port, several flows: who deployed last is what decides whether a verify may
652
- // redeploy there or must ask first. Keyed by port ("default" when the playbook names none).
653
- const devPortsFile = (root: string) => path.join(dfDir(root), "dev-ports.json");
654
- const slotKey = (port: number | undefined) => (port === undefined ? "default" : String(port));
655
-
656
- /** Live slots only: a slot whose flow finished (state.json gone) or was aborted holds nothing. */
657
- function readDevPorts(root: string): Record<string, DevSlot> {
658
- let raw: Record<string, DevSlot>;
659
- try {
660
- raw = JSON.parse(readFileSync(devPortsFile(root), "utf8")) as Record<string, DevSlot>;
661
- } catch {
662
- return {};
663
- }
664
- return Object.fromEntries(
665
- Object.entries(raw).filter(([, v]) => {
666
- const st = v?.slug ? readState(root, v.slug) : null;
667
- return !!st && !st.aborted;
668
- }),
669
- );
670
- }
671
-
672
- function writeDevPorts(root: string, reg: Record<string, DevSlot>): void {
673
- atomicWrite(devPortsFile(root), `${JSON.stringify(reg, null, "\t")}\n`);
674
- }
675
-
676
- function portFree(port: number): Promise<boolean> {
677
- return new Promise((resolve) => {
678
- const srv = createServer();
679
- srv.once("error", () => resolve(false));
680
- srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
681
- });
682
- }
683
-
684
- async function nextFreePort(from: number, taken: Set<number>): Promise<number | null> {
685
- for (let p = from + 1; p < Math.min(from + 50, 65536); p++) if (!taken.has(p) && (await portFree(p))) return p;
686
- return null;
687
- }
688
-
689
- /** MemAvailable (what a new process can really get) where Linux reports it, else the OS free figure. */
690
- function memAvailable(): number | null {
691
- try {
692
- const m = readFileSync("/proc/meminfo", "utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);
693
- if (m) return Number(m[1]) * 1024;
694
- } catch {
695
- /* not Linux */
696
- }
697
- const f = freemem();
698
- return Number.isFinite(f) ? f : null;
699
- }
700
-
701
- function diskFreeAt(dir: string): number | null {
702
- try {
703
- const st = statfsSync(dir);
704
- return Number(st.bavail) * Number(st.bsize);
705
- } catch {
706
- return null;
707
- }
708
- }
709
-
710
- function ago(iso: string): string {
711
- const min = Math.round((Date.now() - Date.parse(iso)) / 60_000);
712
- if (!Number.isFinite(min)) return "at an unknown time";
713
- return min < 1 ? "just now" : min < 90 ? `${min} min ago` : `${Math.round(min / 60)} h ago`;
714
- }
715
-
716
- const portLabel = (port: number | undefined) => (port === undefined ? "the dev stack" : `port ${port}`);
717
-
718
- /** Before a verify deploys: is the stack it would replace held by another live flow? Applies the
719
- * operator's `--port=<n>` / `--replace` answer, or asks — with the measured resources — which to do. */
720
- async function devSlotCheck(o: GateCtx, state: FlowState): Promise<RunResult | { note: string }> {
721
- const { root, cfg, flag, rest } = o;
722
- const portArg = flagValue(rest, "port");
723
- if (portArg !== null) {
724
- const n = Number(portArg);
725
- if (!Number.isInteger(n) || n < 1 || n > 65535) return { text: `--port=${portArg} is not a port`, isError: true };
726
- if (cfg.devPort === undefined) return { text: "--port needs a default `port` in the playbook's ## implement flow block — dev-flow exports the chosen one to dev/health as $DEV_FLOW_PORT", isError: true };
727
- if (n === cfg.devPort) delete state.devPort;
728
- else state.devPort = n;
729
- writeState(root, state);
730
- }
731
- const port = devPortOf(state, cfg);
732
- const reg = readDevPorts(root);
733
- const slot = reg[slotKey(port)];
734
- if (!slot || slot.slug === state.slug) return { note: "" };
735
- if (flag("replace")) return { note: `dev: replaced ${slot.slug}'s deploy on ${portLabel(port)} (operator's answer)` };
736
- const other = readState(root, slot.slug);
737
- const taken = new Set(Object.keys(reg).map(Number).filter(Number.isFinite));
738
- const nextPort = port !== undefined ? await nextFreePort(port, taken) : null;
739
- const mem = memAvailable();
740
- const disk = diskFreeAt(root);
741
- const side = sideBySide({ cfg, nextPort, memAvail: mem, diskFree: disk });
742
- const res = [
743
- `RAM available ${mem !== null ? formatSize(mem) : "unknown"}${cfg.instanceMem !== undefined ? ` (one instance needs ${formatSize(cfg.instanceMem)})` : ""}`,
744
- `disk free ${disk !== null ? formatSize(disk) : "unknown"}${cfg.instanceDisk !== undefined ? ` (one instance needs ${formatSize(cfg.instanceDisk)})` : ""}`,
745
- ].join(", ");
746
- const caveat = side.ok
747
- ? cfg.parallelDev === undefined
748
- ? " The playbook does not say whether two instances can share this machine (parallelDev = yes|no) — tell the operator that when you ask."
749
- : ""
750
- : ` Running alongside is not offered: ${side.why.join("; ")}.`;
751
- const opts = [
752
- ...(side.ok ? [`run alongside on port ${nextPort}: flow verify --port=${nextPort}`] : []),
753
- `replace ${slot.slug}'s deploy: flow verify --replace`,
754
- `wait until ${slot.slug} is done with it`,
755
- ];
756
- const held = `${portLabel(port)} is serving ${slot.slug} (stage ${other?.stage ?? "?"}${other?.pendingAsk ? `, waiting on ${other.pendingAsk}` : ""}, ${slot.head.slice(0, 7)}, deployed ${ago(slot.at)})`;
757
- return { text: needsOperator(`${held} — this verify would replace it. Resources: ${res}.${caveat} Ask the operator which: ${opts.join(" | ")} — nothing was built or deployed yet.`, "Dev port?"), isError: true };
758
- }
759
-
760
- /** Before a review deploy: bring the branch up to date with the default branch, so the operator reviews
761
- * the tree that will ship. Rebases a clean branch that is behind; refuses on a conflict (aborted, branch
762
- * untouched) or on uncommitted work. With the operator's answer in hand (--confirmed) it never rewrites
763
- * history: a default branch that moved since the review deploy sends the flow back to `flow verify`. */
764
- async function catchUp(root: string, state: FlowState, cfg: Config, confirmed: boolean): Promise<RunResult | { note: string }> {
765
- const cwd = gateCwd(root, state);
766
- if (cwd === root) return { note: "" };
767
- const d = cfg.defaultBranch;
768
- const hasOrigin = !!(await originUrl(root));
769
- let fetchNote = "";
770
- if (hasOrigin && !(await sh(`git fetch -q origin ${sq(d)}`, cwd, 60_000)).ok) fetchNote = ` (fetch of origin/${d} failed — compared with the last fetched state)`;
771
- const base = hasOrigin && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, cwd)).ok ? `origin/${d}` : d;
772
- const r = await sh(`git rev-list --count HEAD..${sq(base)}`, cwd);
773
- const behind = Number.parseInt(r.out.trim(), 10);
774
- if (!r.ok || !Number.isFinite(behind)) return { note: `behind ${base}: unknown${fetchNote}` };
775
- if (behind === 0) return { note: fetchNote ? `up to date with ${base}${fetchNote}` : "" };
776
- if (confirmed)
777
- return { text: `verify gate FAILED:\n- ${base} moved ${behind} commit(s) past this branch — the operator's answer would cover a tree that is not the one that ships. Run flow verify (it rebases and redeploys for review), then ask Verified? again`, isError: true };
778
- // untracked build output (a deploy's artifacts) does not stop a rebase; uncommitted tracked edits do
779
- const dirty = await sh("git status --porcelain --untracked-files=no", cwd);
780
- if (dirty.ok && dirty.out.trim()) return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and has uncommitted changes — commit them, then re-run flow verify (it rebases before the review deploy)`, isError: true };
781
- const rb = await sh(`git rebase ${sq(base)}`, cwd, 120_000);
782
- if (!rb.ok) {
783
- const conflicts = (await sh("git diff --name-only --diff-filter=U", cwd)).out.split("\n").filter(Boolean);
784
- await sh("git rebase --abort", cwd);
785
- return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and the rebase stopped on conflicts${conflicts.length ? ` (${conflicts.join(", ")})` : ""} — aborted, the branch is as it was. Rebase by hand in ${state.worktree} (git rebase ${base}), resolve, then re-run flow verify\n${tail(rb.out)}`, isError: true };
786
- }
787
- const pushed = hasOrigin && state.branch && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${state.branch}`)}`, cwd)).ok;
788
- return { note: `rebased onto ${base} (was ${behind} commit(s) behind)${fetchNote}${pushed ? ` — origin/${state.branch} now differs: the next push needs --force-with-lease (dev-flow asks the operator)` : ""}` };
789
- }
790
-
791
- /** Tier-1 checks the gate still has to see green. Entering a stage — and every edit of the worktree —
792
- * clears the records, so "run flow check first" cost three round trips to say what one could (#84).
793
- * `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
794
- function pendingChecks(state: FlowState, cfg: Config): StageCheck[] {
795
- if (state.docs) return [];
796
- return cfg.checkList.filter((c) => !state.checks[c.name]?.ok && !(c.name === "health" && healthRerunsAfterDeploy(cfg)));
797
- }
798
-
799
- /** Run tier-1 checks in the feature cwd and record each result (health seeds first, as `flow health` does). */
800
- async function runChecks(root: string, state: FlowState, cfg: Config, checks: StageCheck[]): Promise<{ lines: string[]; failed: boolean }> {
801
- const lines: string[] = [];
802
- let failed = false;
803
- const ran: string[] = [];
804
- for (const c of checks) {
805
- // health is the same probe `flow health` runs: seeded first, retried within healthWait
806
- const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state), undefined, featureEnv(root, state));
807
- if ("seedFail" in res) {
808
- lines.push(res.seedFail.text);
809
- failed = true;
810
- break;
811
- }
812
- state.checks[c.name] = { ok: res.ok, at: now() };
813
- ran.push(c.name);
814
- const tried = triedNote((res as { attempts?: number }).attempts ?? 1);
815
- lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd}${tried})${res.ok ? "" : `\n${tail(res.out)}`}`);
816
- if (!res.ok) failed = true;
817
- }
818
- await stampChecks(root, state, ran);
819
- writeState(root, state);
820
- return { lines, failed };
821
- }
822
-
823
- /** Which health record a verify may leave stale on purpose: the post-deploy probe re-runs it, so
824
- * the pre-deploy record must survive the gate that schedules the deploy. */
825
- const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthProbe(cfg);
826
-
827
- /** Seed pre-existing data before a health probe, recording the step (`flow health` and the verify
828
- * deploy probe both do this). Returns an error result on failure, null when seeded or not configured. */
829
- async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{ text: string; isError: true } | null> {
830
- if (!cfg.commands.seedData) return null;
831
- const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, devEnv(root, state, cfg));
832
- state.checks.seedData = { ok: seed.ok, at: now() };
833
- writeState(root, state);
834
- return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
835
- }
836
-
837
- type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: RunResult };
838
-
839
- /** Seed (when configured), then run the health probe within the playbook's wait budget. */
840
- async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
841
- const seedFail = await seedStep(root, state, cfg);
842
- return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, devEnv(root, state, cfg));
843
- }
844
-
845
- /** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
846
- async function probeHealth(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
847
- const res = await seededProbe(root, state, cfg, probe);
848
- if ("seedFail" in res) return res;
849
- state.checks.health = { ok: res.ok, at: now() };
850
- await stampChecks(root, state, ["health"]);
851
- writeState(root, state);
852
- return res;
853
- }
854
-
855
- /** A probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42). */
856
- const triedNote = (attempts: number) => (attempts > 1 ? `, ${attempts} attempts` : "");
857
-
858
- /** Fingerprint of the working-tree state the checks ran against: paths (`status --porcelain`),
859
- * tracked content (a hash of the uncommitted diff) and HEAD. Null when git cannot answer — a
860
- * measurement failure must never mark a green record stale (see freshenChecks). */
861
- async function worktreeFingerprint(cwd: string): Promise<string | null> {
862
- const st = await sh("git status --porcelain", cwd);
863
- if (!st.ok) return null;
864
- const diff = await sh("git diff HEAD --no-color | git hash-object --stdin", cwd);
865
- const head = await sh("git rev-parse HEAD", cwd);
866
- if (!diff.ok || !head.ok) return null;
867
- return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
868
- }
869
-
870
- /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
871
- * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
872
- async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
873
- const fp = await worktreeFingerprint(gateCwd(root, state));
874
- if (!fp) return;
875
- for (const n of names) if (state.checks[n]) state.checks[n].wt = fp;
876
- }
877
-
878
- /** Commits the feature branch holds over its merge base with the default branch, plus how many
879
- * paths sit uncommitted: verify's proof that there is a committed state behind the operator's
880
- * question. Local refs only — same offline-safe stance as the changelog proof — and an
881
- * unanswerable merge base reports null instead of refusing on a measurement failure. */
882
- async function branchState(cwd: string, defaultBranch: string): Promise<BranchState> {
883
- const base = await mergeBase(cwd, defaultBranch);
884
- if (!base) return { commitsAhead: null, uncommitted: 0 };
885
- const ahead = await sh(`git rev-list --count ${sq(base)}..HEAD`, cwd);
886
- const n = Number.parseInt(ahead.out.trim(), 10);
887
- const dirty = await sh("git status --porcelain", cwd);
888
- return {
889
- commitsAhead: Number.isFinite(n) ? n : null,
890
- uncommitted: dirty.ok ? dirty.out.split("\n").filter((l) => l.trim()).length : 0,
891
- };
892
- }
893
-
894
- /** Commits HEAD carries since the newest local version tag (all of them before the first release) —
895
- * local refs only, so the probe stays offline-safe. HEAD is the default branch's tip on an empty branch. */
896
- async function unreleasedOnMain(cwd: string, pattern: string): Promise<{ count: number | null; since: string | null }> {
897
- const tags = await sh("git tag --list", cwd);
898
- const newest = tags.ok ? newestTaggedVersion(pattern, tags.out.split("\n").map((t) => t.trim()).filter(Boolean)) : null;
899
- const since = newest ? pattern.replace("{version}", newest) : null;
900
- const r = await sh(since ? `git rev-list --count ${sq(since)}..HEAD` : "git rev-list --count HEAD", cwd);
901
- const n = Number.parseInt(r.out.trim(), 10);
902
- return { count: r.ok && Number.isFinite(n) ? n : null, since };
903
- }
904
-
905
- function describeBranchState(b: BranchState, defaultBranch: string): string {
906
- if (b.commitsAhead === null) return `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`;
907
- const line = `commits: ${b.commitsAhead} ahead of ${defaultBranch}, ${b.uncommitted} uncommitted path(s)`;
908
- return b.commitsAhead === 0 && (b.unreleased?.count ?? 0) > 0
909
- ? `${line} — release-only flow: ${b.unreleased!.count} unreleased commit(s) on ${defaultBranch}${b.unreleased!.since ? ` since ${b.unreleased!.since}` : " (nothing tagged yet)"}; verify proves that tree, the version bump is the pre-release commit`
910
- : line;
911
- }
912
-
913
- // ---------------------------------------------------------------- gate runner
914
-
915
- interface RunResult {
916
- text: string;
917
- isError?: boolean;
918
- }
919
-
920
- interface Session {
921
- slug: string | null;
922
- key: string;
923
- bind: (slug: string | null) => void;
924
- /** Name the pi session after a slug (one session = one feature: the picker shows the feature). */
925
- rename: (slug: string) => void;
926
- }
927
-
928
- /** Is this checkout the dev-flow repo itself? Plugin reflections are fixable in-repo only here. */
929
- function isSelfRepo(root: string): boolean {
930
- try {
931
- return (JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as { name?: unknown }).name === "pi-dev-flow";
932
- } catch {
933
- return false;
934
- }
935
- }
936
-
937
- /** Which tag convention the repo already uses — read off its newest tags, like the merge style is read off
938
- * its history. null = no version-like tags yet (the v{version} default stands, and is asked about). */
939
- async function tagPatternEvidence(root: string): Promise<{ pattern: string; note: string } | null> {
940
- const r = await sh("git tag --list --sort=-creatordate", root, 10_000);
941
- if (!r.ok) return null;
942
- const tags = r.out.split("\n").map((t) => t.trim()).filter((t) => /\d+\.\d+\.\d+/.test(t)).slice(0, 20);
943
- if (!tags.length) return null;
944
- const prefix = (t: string) => t.slice(0, t.search(/\d+\.\d+\.\d+/));
945
- const counts = new Map<string, number>();
946
- for (const t of tags) counts.set(prefix(t), (counts.get(prefix(t)) ?? 0) + 1);
947
- const [top] = [...counts.entries()].sort((x, y) => y[1] - x[1]);
948
- return { pattern: `${top[0]}{version}`, note: `${tags.length} version tag(s), newest ${tags[0]}${counts.size > 1 ? ` (mixed prefixes: ${[...counts.keys()].map((k) => k || "none").join(", ")})` : ""}` };
949
- }
950
-
951
- /** One setup question: what to ask, what detection found, why it matters, and the answer that accepts it. */
952
- export interface SetupQuestion {
953
- key: string;
954
- ask: string;
955
- detected?: string;
956
- /** `flow init --answers` token(s) that accept the detected/suggested value */
957
- accept?: string;
958
- why: string;
959
- }
960
-
961
- /** The questions `flow init` asks before writing a playbook — detection fills what it can, the operator
962
- * answers the rest (the agent relays them). Every question says why it matters and what skipping costs,
963
- * so it is answerable without reading docs/playbook.md first. */
964
- function setupQuestions(det: Detection, ev: { merge?: { note: string; recent: string | null } | null; tag?: { pattern: string; note: string } | null }): SetupQuestion[] {
965
- const sug = (k: string) => det.suggestions.filter((x) => x.key === k);
966
- const q: SetupQuestion[] = [];
967
- const forge = det.partial.forge;
968
- q.push({ key: "forge", ask: "Where is the repo hosted: github, gitlab or self (plain git)?", detected: forge ? `${forge} (from the origin URL)` : "no origin remote", accept: forge ? `forge=${forge}` : undefined, why: "decides who creates the release and how dev-flow proves a PR really merged (gh/glab); self = git only, no automatic releases" });
969
- const vf = det.partial.versioning?.file;
970
- q.push({ key: "versionFile", ask: vf ? `Version lives in ${vf} — keep it?` : "Which file holds the version? (VERSION recommended for non-package repos; or answer that releases carry no version)", detected: vf, accept: vf ? `versionFile=${vf}` : undefined, why: "a release bumps this file and the tag must match it; without one, every release is merge-only (no bump, no tag)" });
971
- const tag = ev.tag?.pattern ?? "v{version}";
972
- q.push({ key: "versionTag", ask: `Tag pattern: ${tag}?`, detected: ev.tag ? `${ev.tag.note}` : "no version tags yet — default v{version}", accept: `versionTag=${tag}`, why: "release tags and the manifest are checked against each other; a pattern that differs from your existing tags breaks the last-release lookup" });
973
- q.push({ key: "merge", ask: "How should a merged PR land on the default branch: squash, merge (a merge commit), rebase, or any (no policy)?", detected: ev.merge?.note ?? "no history to read a style from", accept: ev.merge?.recent ? `merge=${ev.merge.recent}` : undefined, why: "the guard blocks a PR merge in a different style and release-done proves what landed; flow start refuses until this is answered" });
974
- q.push({ key: "releases", ask: "Should release-done create the forge release automatically (gh/glab release from the changelog entry)?", detected: forge === "self" ? "forge = self: no CLI to create one" : undefined, accept: forge === "self" ? "releases=false" : "releases=true", why: "off = the tag is pushed and publishing the release page stays your manual step" });
975
- const art = sug("artifact");
976
- q.push({ key: "artifact", ask: art.length ? "Verify the published artifact after release with this command?" : "Do you publish anything to a registry (npm, crates.io, a container image)? If so, which command proves the version is out?", detected: art.map((a) => a.why).join("; ") || undefined, accept: art[0] ? `artifact=${art[0].value}` : undefined, why: "release-done refuses to finish until the artifact is really there — catches a CI publish that silently failed; none = no check" });
977
- const pre = sug("preflight");
978
- if (pre.length) q.push({ key: "preflight", ask: `Run \`${pre[0].value}\` before anything ships?`, detected: pre[0].why, accept: `preflight=${pre[0].value}`, why: "flow release runs it in the worktree first — a build the tag would trigger, proven before the tag exists" });
979
- const checks = det.partial.checks ?? {};
980
- q.push({
981
- key: "check.<name>",
982
- ask: `Tier-1 checks: ${det.missing.length ? `not detected: ${det.missing.join(", ")}` : "test/build/run detected"}${Object.keys(checks).length ? `; drafted extra checks: ${Object.keys(checks).join(", ")}` : ""}. Correct? Anything CI runs that is missing (lint, typecheck, e2e)?`,
983
- detected: Object.entries(det.partial.commands).filter(([k]) => k !== "setup").map(([k, v]) => `${k}: ${v}`).join(" · ") || undefined,
984
- why: "flow check runs every one of these and the gates refuse while any fails — a check missing here is a failure only CI will see; answer test=… / build=… / check.<name>=<cmd> (empty value removes)",
985
- });
986
- const dev = sug("dev");
987
- q.push({ key: "health", ask: `Does the app expose a health probe (e.g. curl -fs localhost:PORT/healthz)?${dev.length ? ` And use \`${dev[0].value}\` as the dev deploy reviewed before verify?` : " Is there a dev deploy reviewed before verify?"}`, detected: dev[0]?.why, accept: dev[0] ? `dev=${dev[0].value}` : undefined, why: "verify proves the running build is healthy only with a probe; none is fine for libraries and CLIs" });
988
- if (det.partial.changelog === "") q.push({ key: "changelog", ask: "No changelog found — create CHANGELOG.md, or run without one?", accept: "changelog=", why: "the release gates fold the branch's entry into the version heading; empty = no changelog checks at all" });
989
- q.push({ key: "guard", ask: `Any commands the agent must never run, or files it must never touch?${det.partial.guards?.length ? ` (drafted from disk: ${det.partial.guards.map((g) => g.split(" :: ")[0].replace(/\s+/g, " ")).join(", ")})` : ""}`, why: "flow-guard rules are hard blocks or operator confirmations on every shell call and edit; added with flow init --write-file (free text)" });
990
- q.push({ key: "checklist", ask: "Anything you want to tick off by hand per stage (e.g. 'migration tested on a prod copy'), or standing guidance the agent should read at a stage?", why: "checklist items are confirmed as a set at the gate; prose is injected when the stage begins — both are free text: flow init --write-file" });
991
- return q;
992
- }
993
-
994
- function renderQuestions(qs: SetupQuestion[]): string[] {
995
- const out: string[] = [];
996
- qs.forEach((x, i) => {
997
- out.push(` ${i + 1}. [${x.key}] ${x.ask}`);
998
- if (x.detected) out.push(` detected: ${x.detected}`);
999
- if (x.accept) out.push(` accept: ${x.accept}`);
1000
- out.push(` why: ${x.why}`);
1001
- });
1002
- return out;
1003
- }
1004
-
1005
- const GIT_TRACK_NOTE = '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)';
1006
-
1007
- /** The dev-flow repo plugin notes are filed against: the manifest's repository field; the dev-flow
1008
- * checkout itself falls back to its origin. */
1009
- async function pluginUpstream(root: string): Promise<string> {
1010
- return pluginVersion(import.meta.dirname).repo || (isSelfRepo(root) ? githubSlug((await originUrl(root)) ?? "") : "");
1011
- }
1012
-
1013
- /** `flow reflect <note>` — this project's queue, operator decides. `--playbook` / `--code` states the
1014
- * section (the agent knows what its own note is about); `--plugin` is dev-flow feedback, which never
1015
- * lands in a project's file — it prints the upstream issue recipe instead (in the dev-flow repo itself
1016
- * plugin IS code, so it files under `## code`). With no flag the wording guesses and the echo prints why. */
1017
- async function reflectNote(root: string, sess: Session, note: string[], forced: ReflectTarget | null): Promise<RunResult> {
1018
- const file = path.join(dfDir(root), "reflections.md");
1019
- const text = existsSync(file) ? readFileSync(file, "utf8") : "";
1020
- const guess = guessReflectSections(note.join(" "));
1021
- const self = isSelfRepo(root);
1022
- const target = forced ?? guess.target;
1023
- const why = forced ? "as told" : guess.why;
1024
- const date = now().slice(0, 10);
1025
- 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") };
1026
- const section: ReflectSection = target === "plugin" ? "code" : target;
1027
- const line = reflectionLine(note.join(" "), sess.slug, date);
1028
- const next = appendReflection(text, [section], line);
1029
- if (next === text) return { text: `already reflected (duplicate): ${line}` };
1030
- writeFileSync(file, next);
1031
- // queueing is exactly when the operator hears about the checked-off pile — nudge only once it is worth a tidy
1032
- const { tidy } = reflectionNudges(next, date);
1033
- return { text: `reflected (${section} — ${target === "plugin" ? "dev-flow repo: plugin feedback is this project's code" : why}): ${line}` + (tidy ? `\n${tidy}` : "") };
1034
- }
1035
-
1036
- /** In-process TTL cache per repo slug — repeat doctor runs in one session must not re-hit the API. */
1037
- const ghFoldCache = new Map<string, { at: number; issues: GhIssue[] }>();
1038
- const GH_FOLD_TTL_MS = 5 * 60_000;
1039
-
1040
- /** Open GitHub issues of the repo's own origin — the channel external parties can file through.
1041
- * Three outcomes, only the third ever speaks: absent (no GitHub remote — not every repo has one,
1042
- * say nothing), skipped (gh missing / unauthenticated / offline / DEV_FLOW_NO_ISSUES — one line
1043
- * with the reason, never a guess), ok (the parsed list). */
1044
- async function fetchUpstream(root: string): Promise<{ slug: string; issues: GhIssue[] } | { skipped: string } | { absent: true }> {
1045
- if (process.env.DEV_FLOW_NO_ISSUES) return { skipped: "disabled (DEV_FLOW_NO_ISSUES)" };
1046
- const slug = githubSlug((await originUrl(root)) ?? "");
1047
- if (!slug) return { absent: true };
1048
- const hit = ghFoldCache.get(slug);
1049
- if (hit && Date.now() - hit.at < GH_FOLD_TTL_MS) return { slug, issues: hit.issues };
1050
- const r = await sh(`gh issue list --repo ${slug} --state open --json number,title,body --limit 100`, root, 10_000);
1051
- if (!r.ok) return { skipped: `gh: ${r.out.split("\n").find(Boolean)?.slice(0, 140) || "failed"}` };
1052
- const parsed = parseGhIssues(r.out);
1053
- if (parsed === null) return { skipped: "unparseable gh output" };
1054
- ghFoldCache.set(slug, { at: Date.now(), issues: parsed });
1055
- return { slug, issues: parsed };
1056
- }
1057
-
1058
- type FoldView = { state: "absent" } | { state: "skipped"; why: string } | { state: "ok"; slug: string; result: FoldResult; open: number };
1059
-
1060
- async function foldView(root: string, items: ReflectItem[]): Promise<FoldView> {
1061
- const up = await fetchUpstream(root);
1062
- if ("absent" in up) return { state: "absent" };
1063
- if ("skipped" in up) return { state: "skipped", why: up.skipped };
1064
- return { state: "ok", slug: up.slug, result: dedupeReflections(items, up.issues), open: up.issues.length };
1065
- }
1066
-
1067
- /** The fold block shared by flow doctor and flow reflect list: header, one row per unmatched
1068
- * issue with its route, then the unmerged near-miss hints. Local rows carry their ⟷ gh#N tag
1069
- * at the call site — the fold lists upstream items, it never re-numbers the local queue. */
1070
- function foldRows(fold: FoldView, selfRepo: boolean): string[] {
1071
- if (fold.state === "absent") return [];
1072
- if (fold.state === "skipped") return [`upstream issues: skipped (${fold.why})`];
1073
- if (!fold.open) return [];
1074
- const rows = [`upstream on ${fold.slug} — ${fold.open} open issue(s) on GitHub (canonical there — close on GitHub, never here; this is a fold, not a copy):`];
1075
- for (const i of fold.result.upstreamOnly) rows.push(` gh#${i.number} ${i.title} → ${selfRepo ? "fix in a flow here (patch flow if small)" : "fix in a flow here, or close won't-fix on GitHub"}`);
1076
- for (const s of fold.result.similar) rows.push(` ${similarNote(s, s.item + 1)}`);
1077
- return rows;
1078
- }
1079
-
1080
- /** `flow reflect list` — the queue numbered, so `move <n>` can address an item (same numbering as
1081
- * `flow roadmap`). Upstream items ride below the local queue as gh#N — never numbered, never
1082
- * addressable by move: each item keeps the home it is resolved in. */
1083
- async function reflectList(root: string): Promise<RunResult> {
1084
- const items = readReflections(root);
1085
- const fold = await foldView(root, items);
1086
- const local = items.length
1087
- ? [
1088
- `reflections — ${items.length} open:`,
1089
- ...items.map((it, i) => {
1090
- const link = fold.state === "ok" ? fold.result.linked.find((l) => l.item === i) : undefined;
1091
- return ` ${i + 1}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}${link ? linkedTag(link.issue) : ""}`;
1092
- }),
1093
- ]
1094
- : fold.state === "absent" || fold.state === "skipped"
1095
- ? ["reflections: nothing open"]
1096
- : ["reflections: nothing open locally"];
1097
- return { text: [...local, ...legacyPluginRows(readReflectionsText(root), isSelfRepo(root)), ...foldRows(fold, isSelfRepo(root))].join("\n") };
1098
- }
1099
-
1100
- /** Open rows still under the legacy `## plugin` heading: they belong on GitHub, not in a project's queue. */
1101
- function legacyPluginRows(text: string, selfRepo: boolean): string[] {
1102
- const n = reflectLegacyPluginCount(text);
1103
- if (!n) return [];
1104
- return [
1105
- selfRepo
1106
- ? `reflections: ${n} open item(s) under the legacy ## plugin heading — in the dev-flow repo plugin is code: flow reflect move <n> --code`
1107
- : `reflections: ${n} open item(s) under the legacy ## plugin heading belong on GitHub, not here — file each upstream (flow reflect --plugin "<note>" prints the recipe), then check it off '— filed: gh#NNN'`,
1108
- ];
1109
- }
1110
-
1111
- /** `flow reflect move <n> --playbook|--code` — re-file an item under the other heading, so fixing a
1112
- * misfile is one command instead of hand-editing markdown. Nothing moves INTO `## plugin`: dev-flow
1113
- * feedback is filed upstream (flow reflect --plugin prints the recipe), then the row is checked off. */
1114
- function reflectMoveNote(root: string, args: string[], forced: ReflectTarget | null): RunResult {
1115
- 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 };
1116
- if (!forced) return { text: "usage: flow reflect move <n> --playbook | --code", isError: true };
1117
- const section = forced;
1118
- const n = Number(args[0]);
1119
- const text = readReflectionsText(root);
1120
- const items = reflectItems(text);
1121
- if (!Number.isInteger(n) || n < 1 || n > items.length) return { text: `move: open item 1–${items.length} required — flow reflect list numbers them`, isError: true };
1122
- if (items[n - 1].section === section) return { text: `reflect: item ${n} is already under ## ${section}` };
1123
- // the same note open under both headings (an old --both filing): the move merges it, it does not copy it
1124
- const twin = items.some((it, i) => i !== n - 1 && it.section === section && it.body === items[n - 1].body);
1125
- const next = reflectMove(text, n, section);
1126
- if (next === null) return { text: `move: open item 1–${items.length} required — flow reflect list numbers them`, isError: true };
1127
- writeFileSync(path.join(dfDir(root), "reflections.md"), next);
1128
- const note = items[n - 1].line.replace(/^- \[ \] /, "");
1129
- return { text: twin ? `reflect: item ${n} was already recorded under ## ${section} — the duplicate is gone (${note})` : `reflect: item ${n} re-filed under ## ${section} — ${note}` };
1130
- }
1131
-
1132
- /** `flow reflect done <n> [what fixed it]` — check a folded/fixed item off, so doctor stops re-reporting it (#165). */
1133
- function reflectDoneNote(root: string, sess: Session, args: string[]): RunResult {
1134
- const text = readReflectionsText(root);
1135
- const items = reflectItems(text);
1136
- const n = Number(args[0]);
1137
- if (!Number.isInteger(n) || n < 1 || n > items.length)
1138
- return { text: items.length ? `done: open item 1–${items.length} required — flow reflect list numbers them` : "done: nothing open in reflections.md", isError: true };
1139
- const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
1140
- const what = args.slice(1).join(" ").trim();
1141
- const next = reflectDone(text, n, what ? `${stamp} — ${what}` : stamp)!;
1142
- writeFileSync(path.join(dfDir(root), "reflections.md"), next);
1143
- const { tidy } = reflectionNudges(next, now().slice(0, 10));
1144
- return { text: `reflect: item ${n} checked off — ${items[n - 1].body}` + (tidy ? `\n${tidy}` : "") };
1145
- }
1146
-
1147
- /** `flow reflect tidy` — drop the closed (`- [x]`) items; the `— fixed:` note already recorded the outcome. */
1148
- function reflectTidy(root: string): RunResult {
1149
- const file = path.join(dfDir(root), "reflections.md");
1150
- if (!existsSync(file)) return { text: "reflections: nothing to tidy (no queue yet)" };
1151
- const text = readFileSync(file, "utf8");
1152
- const closed = doneItemCount(text);
1153
- const open = openChecklistItems(text).length;
1154
- if (!closed) return { text: `reflections: nothing to tidy (${open} open, 0 closed)` };
1155
- writeFileSync(file, reflectionsTidy(text));
1156
- return { text: `reflections: dropped ${closed} closed item(s) — ${open} open` };
1157
- }
1158
-
1159
- /** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
1160
- export interface FlowHooks {
1161
- reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean }>;
1162
- }
1163
-
1164
- /** Single runner for both the /flow command and the flow tool. */
1165
- async function runFlow(args: string[], root: string, ui: Ui, sess: Session, hooks: FlowHooks = {}): Promise<RunResult> {
1166
- const [sub = "status", ...rest] = args;
1167
- // help and version are questions about the plugin, not the repo: answerable with no .dev-flow/ at all
1168
- if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, loadedVersion()) : `usage: flow <sub> — ${GATE_HELP}` };
1169
- // an uninitiated folder is dormant: every gate verb but init and version needs the operator playbook (project.md)
1170
- 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 };
1171
- const cfg = loadProject(dfDir(root)).cfg;
1172
- const flag = (name: string) => rest.includes(`--${name}`);
1173
- // the yolo word at Verified?/Release?/Finish?: the operator said it in chat, then re-run with --confirmed; checks and guardrails stay enforced
1174
- const takeYoloWord = (state: FlowState): string | null => {
1175
- if (!flag("yolo")) return null;
1176
- if (!state.yolo && !flag("confirmed")) return "yolo is the operator's word — the operator must have said it in chat, then re-run with --yolo --confirmed";
1177
- state.yolo = true;
1178
- return null;
1179
- };
1180
- const slugArg = rest.find((a) => !a.startsWith("--"));
1181
- const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord, hooks };
1182
-
1183
- switch (sub) {
1184
- case "init":
1185
- return gateInit(o);
1186
-
1187
- case "start":
1188
- return gateStart(o);
1189
-
1190
- case "status":
1191
- return gateStatus(o);
1192
-
1193
- case "reflect":
1194
- return gateReflect(o);
1195
-
1196
- case "roadmap":
1197
- return gateRoadmap(o);
1198
-
1199
- case "doctor":
1200
- return gateDoctor(o);
1201
-
1202
- case "version":
1203
- return gateVersion(o);
1204
-
1205
- case "approve":
1206
- return gateApprove(o);
1207
-
1208
- case "test":
1209
- return gateTest(o);
1210
-
1211
- case "verify":
1212
- return gateVerify(o);
1213
-
1214
- case "check":
1215
- return gateCheck(o);
1216
-
1217
- case "health":
1218
- return gateHealth(o);
1219
-
1220
- case "release":
1221
- return gateRelease(o);
1222
-
1223
- case "release-done":
1224
- return gateReleaseDone(o);
1225
-
1226
- case "finish":
1227
- return gateFinish(o);
1228
-
1229
- case "use":
1230
- return gateUse(o);
1231
-
1232
- case "abort":
1233
- return gateAbort(o);
1234
-
1235
- default:
1236
- return { text: `unknown subcommand "${sub}" — ${GATE_HELP}`, isError: true };
1237
- }
1238
- }
1239
- /** Records the checkpoint word a gate asked for and has not been given: the footer shows 💬 (“operator,
1240
- * your turn”, the legend in docs/playbook.md) while a session is parked on an answer. Presentation only —
1241
- * no verdict reads it — and the same gate clears it when the word arrives (or when the answer is no and the
1242
- * turn returns to the agent). */
1243
- function markPendingAsk(root: string, state: FlowState, word: string): void {
1244
- state.pendingAsk = word;
1245
- writeState(root, state);
1246
- }
1247
-
1248
- async function gateVerify(o: GateCtx): Promise<RunResult> {
1249
- const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
1250
- const { state, err } = needState(root, sess, slugArg);
1251
- if (err) return err;
1252
- const items = applicableItems(cfg, state!, "implement");
1253
- // the operator reviews the tree that ships: catch up with the default branch before anything runs
1254
- const caught = state!.stage === "implement" ? await catchUp(root, state!, cfg, flag("confirmed")) : { note: "" };
1255
- if ("text" in caught) return caught;
1256
- const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
1257
- if (branch.commitsAhead === 0 && cfg.versioning.file) branch.unreleased = await unreleasedOnMain(gateCwd(root, state!), cfg.versioning.pattern);
1258
- const branchLine = describeBranchState(branch, cfg.defaultBranch);
1259
- // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
1260
- // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
1261
- // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
1262
- const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1263
- if (staleAtGate.length) writeState(root, state!);
1264
- const pending = pendingChecks(state!, cfg);
1265
- const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
1266
- if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
1267
- // tier-1 gate first (tier-2 confirmation is recorded by this very command, so it is excluded here)
1268
- const preGate = verifyGate({ ...state!, confirmations: { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } } }, cfg, branch);
1269
- if (preGate.length) return { text: `verify gate FAILED:\n- ${preGate.join("\n- ")}\n${branchLine}`, isError: true };
1270
- // a stack another flow is reviewing or releasing on is not this gate's to take — ask before deploying
1271
- const slotted = cfg.commands.dev && !state!.docs ? await devSlotCheck(o, state!) : { note: "" };
1272
- if ("text" in slotted) return slotted;
1273
- // commands that take minutes and touch live services must say so (#38): a terse gate let the
1274
- // agent tell the operator the dev deploy had never run, right after it recreated a container.
1275
- const did: string[] = [];
1276
- if (caught.note) did.push(caught.note);
1277
- if (slotted.note) did.push(slotted.note);
1278
- if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
1279
- if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
1280
- if (state!.docs) {
1281
- // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
1282
- did.push("docs mode: project commands skipped (build/dev/health)");
1283
- } else {
1284
- if (cfg.commands.build) {
1285
- const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
1286
- state!.checks.build = { ok: res.ok, at: now() };
1287
- writeState(root, state!);
1288
- if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
1289
- did.push(`build ran (${cfg.commands.build})`);
1290
- }
1291
- // deploy to dev before asking — the operator reviews the running dev app, not a promise
1292
- const probe = healthProbe(cfg);
1293
- if (cfg.commands.dev) {
1294
- const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
1295
- state!.checks.dev = { ok: res.ok, at: now() };
1296
- writeState(root, state!);
1297
- if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
1298
- did.push(`dev ran (${cfg.commands.dev})${devPortOf(state!, cfg) !== undefined ? ` on port ${devPortOf(state!, cfg)}` : ""}`);
1299
- // the deploy is what must be proven, not just run: a container that came back unhealthy, or
1300
- // still serves the previous build, must not pass on a health PASS recorded before it was
1301
- // recreated. What "the expected version" means is the project's business — the probe runs in
1302
- // the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
1303
- if (!probe) did.push("health: none configured");
1304
- else {
1305
- const probed = await probeHealth(root, state!, cfg, probe);
1306
- if ("seedFail" in probed) return probed.seedFail;
1307
- if (!probed.ok) return { text: `post-deploy probe FAILED (${probe}) — the deploy is not healthy / not serving this build (gave up after ${probed.attempts} attempt(s), healthWait ${cfg.healthWait}s):\n${tail(probed.out)}`, isError: true };
1308
- did.push(`health: PASS (${probe}${triedNote(probed.attempts)})`);
1309
- }
1310
- } else if (!probe) did.push("dev: none configured");
1311
- else {
1312
- // no deploy to prove, but the operator still reviews a live app — and a green health record
1313
- // survives a killed server (process death dirties no worktree fingerprint), so the record
1314
- // cannot stand for liveness: re-probe, before anyone is asked.
1315
- const probed = await probeHealth(root, state!, cfg, probe);
1316
- if ("seedFail" in probed) return probed.seedFail;
1317
- if (!probed.ok)
1318
- return { text: `live probe FAILED (${probe}) — nothing is answering and no dev deploy is configured: the app the operator must review has to be running before verify — start it and rerun (gave up after ${probed.attempts} attempt(s), healthWait ${cfg.healthWait}s):\n${tail(probed.out)}`, isError: true };
1319
- did.push(`health: live re-probe PASS (${probe}${triedNote(probed.attempts)})`);
1320
- }
1321
- }
1322
- if (!state!.docs && cfg.commands.servedBuild) {
1323
- // "something answers" is not "this branch answers": the served commit must be the worktree's HEAD
1324
- const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
1325
- const sb = await sh(cfg.commands.servedBuild, gateCwd(root, state!), 60_000, devEnv(root, state!, cfg));
1326
- if (!sb.ok || !servedBuildMatches(sb.out, head))
1327
- return { text: `served-build check FAILED (${cfg.commands.servedBuild}) — the app is up but does not serve this branch's HEAD ${head.slice(0, 12)}:\n${tail(sb.out)}`, isError: true };
1328
- did.push(`serves ${head.slice(0, 7)} (HEAD)`);
1329
- }
1330
- if (!state!.docs && cfg.commands.dev) {
1331
- const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
1332
- writeDevPorts(root, { ...readDevPorts(root), [slotKey(devPortOf(state!, cfg))]: { slug: state!.slug, head, at: now() } });
1333
- }
1334
- const ran = [branchLine, ...did].join("; ");
1335
- // yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
1336
- const yoloWord = takeYoloWord(state!);
1337
- if (yoloWord) return { text: yoloWord, isError: true };
1338
- let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1339
- const askPending = !flag("confirmed") && !state!.yolo;
1340
- if (askPending) {
1341
- markPendingAsk(root, state!, "Verified?"); // pending however it is asked — a chat question or a dialog
1342
- // the agent's call never opens a dialog (#181): this is the review deploy — the app is up for the
1343
- // operator, and the answer comes back in chat as flow verify --confirmed
1344
- if (!ui.hasUI) {
1345
- const port = devPortOf(state!, cfg);
1346
- const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : "live app re-probed for review";
1347
- return { text: `${needsOperator(`${what} — look at the change in the running app yourself first (the playbook's self-check), then ask the operator Verified? in chat and run flow verify --confirmed once they answer. Keep it running until they answer.`, "Verified?")}\n${ran}` };
1348
- }
1349
- const ok = await ui.confirm("Operator verification", `Verified? All checks green${cfg.commands.dev && !state!.docs ? `; dev deploy is up for review (${cfg.commands.dev})` : ""} \u2014 does it work?`);
1350
- if (!ok) {
1351
- delete state!.pendingAsk;
1352
- writeState(root, state!);
1353
- return { text: "verification declined — stay in implement and fix what failed" };
1354
- }
1355
- audit = " (confirmed in dialog)";
1356
- }
1357
- state!.confirmations = { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } };
1358
- const final = verifyGate(state!, cfg, branch);
1359
- if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
1360
- state!.approvals.verify = now();
1361
- if (isReleaseOnly(cfg, branch)) state!.releaseOnly = true;
1362
- else delete state!.releaseOnly;
1363
- // the tree the word was given over (#162) — a git that cannot answer leaves it unset, never a refusal
1364
- const vHead = await sh("git rev-parse HEAD", gateCwd(root, state!));
1365
- if (vHead.ok && vHead.out.trim()) state!.verifiedHead = vHead.out.trim();
1366
- else delete state!.verifiedHead;
1367
- state!.stage = "pre-release";
1368
- delete state!.pendingAsk;
1369
- writeState(root, state!);
1370
- return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${nextHint(state!, cfg)}` };
1371
- }
1372
-
1373
- async function gateRelease(o: GateCtx): Promise<RunResult> {
1374
- const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
1375
- const { state, err } = needState(root, sess, slugArg);
1376
- if (err) return err;
1377
- // operator's word at Release?: this flow ships without a version bump or tag — recorded only once Release? is answered
1378
- const noVersion = flag("no-version") || !!state!.noVersion;
1379
- // (versioned) items stand down on an unversioned flow — the set confirmed here is the one that applies to it
1380
- const items = applicableItems(cfg, { ...state!, noVersion }, "pre-release");
1381
- // yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
1382
- const yoloWord = takeYoloWord(state!);
1383
- if (yoloWord) return { text: yoloWord, isError: true };
1384
- // prep evidence is read from the worktree: the bump and changelog entry exist on the branch before the PR merges
1385
- const wtCwd = gateCwd(root, state!);
1386
- // gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix
1387
- // that never ships. verify shows the operator uncommitted paths; release proves them away. A git
1388
- // that cannot answer is a measurement failure, never a refusal — same stance as the merge-base probes.
1389
- const dirtyWt = await sh("git status --porcelain", wtCwd);
1390
- if (dirtyWt.ok && dirtyWt.out.trim()) {
1391
- const n = dirtyWt.out.split("\n").filter((l) => l.trim()).length;
1392
- return { text: `release gate FAILED:\n- ${n} uncommitted path(s) in ${state!.worktree} — a merge ships the branch, not your working tree: commit or discard them, then re-run\n${tail(dirtyWt.out)}`, isError: true };
1393
- }
1394
- const branchProof = await branchState(wtCwd, cfg.defaultBranch);
1395
- const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
1396
- ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
1397
- : null;
1398
- // tags are only needed on the versioned path; a project without versioning must not be held up by an offline origin
1399
- const remoteTags = cfg.versioning.file && !noVersion ? await releaseTags(root) : [];
1400
- if (remoteTags === null) return { text: "release gate FAILED:\n- cannot list tags on origin (offline?) — retry; local tags do not decide what is already released", isError: true };
1401
- const changelog =
1402
- cfg.release.changelog && existsSync(path.join(wtCwd, cfg.release.changelog))
1403
- ? { file: cfg.release.changelog, content: readFileSync(path.join(wtCwd, cfg.release.changelog), "utf8") }
1404
- : null;
1405
- // The changelog's baseline is what was pending before this release. The newest tag wins over the
1406
- // merge base: it is what actually shipped, and a rebase or squash merge can leave the merge base
1407
- // unreachable — a git-topology accident must not refuse a legal release (#97).
1408
- let changelogChanged: boolean | null = null;
1409
- const changelogBase: { pending: string[]; source: "tag" | "merge-base" | "none" } = { pending: [], source: "none" };
1410
- if (changelog) {
1411
- const p = sq(cfg.release.changelog!);
1412
- const mbRef = await mergeBase(wtCwd, cfg.defaultBranch);
1413
- // proof the branch touched the changelog: local refs only, so the check stays offline-safe
1414
- if (mbRef) {
1415
- const changes = await sh(`git diff --name-only ${sq(mbRef)} -- ${p} 2>/dev/null; git ls-files --others --exclude-standard -- ${p}`, wtCwd);
1416
- changelogChanged = changes.out.split("\n").some((l) => l.trim());
1417
- }
1418
- const newest = !noVersion && cfg.versioning.file ? newestTaggedVersion(cfg.versioning.pattern, remoteTags) : null;
1419
- // tag first, merge base as the understudy: `releaseTags` asks origin, so a clone that has not
1420
- // fetched the tag yet must still get a baseline instead of losing the fold proof
1421
- const bases: { ref: string; source: "tag" | "merge-base" }[] = [];
1422
- if (newest) bases.push({ ref: cfg.versioning.pattern.replace("{version}", newest), source: "tag" });
1423
- if (mbRef) bases.push({ ref: mbRef, source: "merge-base" });
1424
- for (const b of bases) {
1425
- const base = await sh(`git show ${sq(b.ref)}:${p} 2>/dev/null || true`, wtCwd);
1426
- if (base.out.trim()) {
1427
- changelogBase.pending = pendingEntryLines(base.out);
1428
- changelogBase.source = b.source;
1429
- break;
1430
- }
1431
- }
1432
- }
1433
- // #164: a hand-resolved merge can commit a leftover marker — content to git, so nothing else catches it
1434
- const markerBase = await mergeBase(wtCwd, cfg.defaultBranch);
1435
- const markerDiff = markerBase ? await sh(`git diff -U0 --no-color --no-ext-diff ${sq(markerBase)} HEAD`, wtCwd) : null;
1436
- const conflictMarkers = markerDiff?.ok ? conflictMarkerLines(markerDiff.out) : undefined;
1437
- const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check"), conflictMarkers, noMarkerCheck: flag("no-marker-check") };
1438
- // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1439
- if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1440
- // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1441
- const preGate = preReleaseGate({ ...state!, noVersion, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1442
- if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
1443
- // the build the tag will trigger, proven before anything ships: a broken artifact build found after the
1444
- // tag costs follow-up PRs and a re-cut tag
1445
- if (cfg.release.preflight) {
1446
- const pf = await sh(cfg.release.preflight, wtCwd);
1447
- if (!pf.ok) return { text: `release gate FAILED:\n- release.preflight failed in ${state!.worktree} (${cfg.release.preflight}) — fix it on the branch before anything ships:\n${tail(pf.out)}`, isError: true };
1448
- }
1449
- // a stale session build is the operator's decision, never a block: publishing under an older gate is a
1450
- // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1451
- // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
1452
- // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
1453
- const { disk: selfBuild, behind } = buildSkew(root);
1454
- // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
1455
- // has every proof the checkout would run, and asking about it would be noise.
1456
- const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
1457
- let staleAsk = "";
1458
- let staleNote = "";
1459
- if (stale) {
1460
- const clPath = path.join(selfBuild.dir, "CHANGELOG.md");
1461
- const missing = existsSync(clPath) && selfBuild.version ? changelogVersionsBetween(readFileSync(clPath, "utf8"), behind, selfBuild.version) : [];
1462
- staleAsk =
1463
- ` This session runs dev-flow ${behind}, ${selfBuild.label} ships ${selfBuild.version ?? "?"} — gate proofs shipped between the two will NOT run. ` +
1464
- (missing.length
1465
- ? `Shipped since ${behind}: ${missing.slice(0, 8).join(", ")}${missing.length > 8 ? ` …(${missing.length} total)` : ""} — see ${clPath}. `
1466
- : `What shipped between them is not readable from the checkout's CHANGELOG.md — read it before deciding. `) +
1467
- `Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
1468
- staleNote = `released under dev-flow ${behind} (${selfBuild.label} ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
1469
- }
1470
- // #162: Verified? was answered over one tree; commits after it ship under that word unless someone says
1471
- // so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
1472
- let postVerify = "";
1473
- if (state!.verifiedHead) {
1474
- // gh#180: upstream work merged in after the verdict was approved on its own branch — only the branch's
1475
- // own commits are news to the operator; the merged-in ones are a count, not a list to wade through
1476
- const d = cfg.defaultBranch;
1477
- const upstream = (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, wtCwd)).ok ? `origin/${d}` : (await sh(`git rev-parse --verify -q ${sq(`refs/heads/${d}`)}`, wtCwd)).ok ? d : "";
1478
- const since = await sh(`git log --oneline --no-decorate ${upstream ? "--no-merges " : ""}${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`, wtCwd);
1479
- const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
1480
- const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
1481
- const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
1482
- // a release-only flow commits its bump and changelog after verify by design — only other files count
1483
- const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
1484
- const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
1485
- const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
1486
- if (commits.length && !prepOnly)
1487
- postVerify = `${commits.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${commits.slice(0, 6).join(" | ")}${commits.length > 6 ? ` …(${commits.length - 6} more)` : ""}${mergedIn ? ` (+${mergedIn} merged in from ${upstream}, not listed)` : ""} — the verify verdict does not cover them: if behaviour changed, have the operator check the current build before Release?, and either way say in the PR body which commit the verdict was given over`;
1488
- }
1489
- // a standing yolo (given at an earlier checkpoint) stops short of Release? when the playbook says so, or
1490
- // when commits landed after Verified? — the word was given before those commits existed (gh#176).
1491
- // --confirmed is the operator's own answer at this checkpoint, yolo-at-Release? included: it always stands.
1492
- const yoloHeld = !state!.yolo || flag("confirmed")
1493
- ? ""
1494
- : cfg.release.yolo === "until-release"
1495
- ? "the playbook sets yolo = until-release: a yolo given earlier never answers Release? — ask it"
1496
- : postVerify
1497
- ? "a yolo given earlier does not cover commits that landed after Verified? — ask Release? with them named"
1498
- : "";
1499
- let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1500
- const askPending = !flag("confirmed") && (!state!.yolo || !!yoloHeld);
1501
- if (askPending) {
1502
- markPendingAsk(root, state!, "Release?");
1503
- if (!ui.hasUI) {
1504
- return { text: needsOperator(`release confirmation needs the operator${yoloHeld ? ` (${yoloHeld})` : ""}: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}${postVerify ? ` — tell them: ${postVerify}` : ""}`, "Release?"), isError: true };
1505
- }
1506
- const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}${postVerify ? `\n\n${postVerify}` : ""}${yoloHeld ? `\n\n(${yoloHeld})` : ""}`);
1507
- if (!ok) {
1508
- delete state!.pendingAsk;
1509
- writeState(root, state!);
1510
- return { text: "release declined — keep preparing in pre-release" };
1511
- }
1512
- audit = " (confirmed in dialog)";
1513
- }
1514
- if (noVersion) state!.noVersion = true;
1515
- state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
1516
- state!.approvals["pre-release"] = now();
1517
- state!.stage = "release";
1518
- // a skipped proof is never silent: the gate says which one and why (#97)
1519
- const foldNote = !changelog
1520
- ? ""
1521
- : flag("no-fold-check")
1522
- ? " Warning: the changelog fold proofs were skipped (--no-fold-check) — check that the entry carries what was pending."
1523
- : changelogBase.source === "none"
1524
- ? " Warning: no tag or merge base to compare against, so the changelog fold was not proven — check the entry by hand."
1525
- : "";
1526
- // the version of record is fixed here, from the manifest this gate validated: release-done must not
1527
- // re-read a checkout that may still be behind (#52)
1528
- if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
1529
- if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1530
- delete state!.pendingAsk;
1531
- writeState(root, state!);
1532
- return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}${postVerify ? ` Warning: ${postVerify}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
1533
- }
1534
-
1535
- async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1536
- const { root, sess, cfg, flag, slugArg } = o;
1537
- const { state, err } = needState(root, sess, slugArg);
1538
- if (err) return err;
1539
- const errs = releaseGate(state!);
1540
- // the version of record is what flow release approved (#52) — never a re-read of a checkout that may be behind
1541
- const manifestVer: string | null = state!.releaseVersion ?? null;
1542
- if (cfg.versioning.file && !state!.noVersion && !manifestVer) errs.push(`flow release approved no version (versioning.file "${cfg.versioning.file}" was set after it?) — fix the playbook, or ship this flow unversioned`);
1543
- const expectedTag = manifestVer ? cfg.versioning.pattern.replace("{version}", manifestVer) : null;
1544
- const origin = await originUrl(root);
1545
- const hasOrigin = origin !== null;
1546
- const forgeName = forgeOf(cfg, origin);
1547
- // one round-trip answers both questions about the tag: is it there, and did it leave this laptop (#52)
1548
- const tags = expectedTag ? await releaseTags(root) : [];
1549
- if (tags === null) errs.push("cannot list tags on origin (offline?) — retry: local tags must not decide what is already released");
1550
- else if (expectedTag && manifestVer) {
1551
- const verrs = versionTagGate(manifestVer, cfg.versioning.pattern, tags);
1552
- if (verrs.length) {
1553
- // the actionable version of "not on the forge": the tag exists but never got pushed
1554
- const local = hasOrigin ? (await sh(`git tag --list ${sq(expectedTag)}`, root)).out.trim() : "";
1555
- if (local) errs.push(`tag ${expectedTag} is local-only — git push origin ${expectedTag} (git push --follow-tags silently skips lightweight tags; tag with git tag -a and push the ref explicitly)`);
1556
- else errs.push(...verrs);
1557
- }
1558
- // never publish behind what the forge already has — that is how a stale manifest republished
1559
- // the previous version and its artifact probe passed (#52)
1560
- const newest = newestTaggedVersion(cfg.versioning.pattern, tags);
1561
- if (newest && cmpVersions(newest, manifestVer) > 0) errs.push(`${cfg.versioning.pattern.replace("{version}", newest)} is already tagged — refusing to release ${expectedTag} behind it`);
1562
- if (!verrs.length) {
1563
- const reach = await sh(`git merge-base --is-ancestor ${sq(expectedTag)} origin/${cfg.defaultBranch} 2>/dev/null || git merge-base --is-ancestor ${sq(expectedTag)} ${cfg.defaultBranch}`, root);
1564
- if (!reach.ok) errs.push(`tag ${expectedTag} is not reachable from ${cfg.defaultBranch} — tag what actually shipped on ${cfg.defaultBranch}`);
1565
- }
1566
- }
1567
- let artNote = "";
1568
- if (expectedTag && cfg.release.artifact) {
1569
- if (flag("no-artifact-check")) artNote = "Artifact check skipped (--no-artifact-check).";
1570
- else {
1571
- const cmd = cfg.release.artifact.replaceAll("{version}", manifestVer!).replaceAll("{tag}", expectedTag);
1572
- const art = await sh(cmd, root);
1573
- if (art.ok) artNote = `Artifact verified for ${manifestVer}.`;
1574
- else errs.push(`artifact not published — release.artifact check failed (${cmd}):\n${tail(art.out)}`);
1575
- }
1576
- }
1577
- // merge policy: did what actually landed agree with what the playbook says? A measured contradiction
1578
- // refuses the release record; what dev-flow cannot see stays an advisory — the split the changelog
1579
- // proofs learned (#97): an invisible topology never blocks a legal release.
1580
- let mergeNote = "";
1581
- if (cfg.release.merge && cfg.release.merge !== "any" && state!.branch) {
1582
- const br = state!.branch;
1583
- await sh(`git fetch -q origin ${sq(br)} 2>/dev/null; git fetch -q origin ${sq(cfg.defaultBranch)} 2>/dev/null`, root);
1584
- const refsOk = hasOrigin && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${br}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1585
- // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1586
- // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1587
- const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1588
- const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeName, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1589
- if (proof.errors.length) errs.push(...proof.errors);
1590
- else mergeNote = proof.note;
1591
- }
1592
- if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1593
- // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
1594
- const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false;
1595
- let ghNote = "";
1596
- let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1597
- let bodyNote = "";
1598
- if (manifestVer && flag("no-release-create")) ghNote = "Forge release skipped (--no-release-create).";
1599
- else if (manifestVer && !releasesWanted) ghNote = "no forge release created (release.releases = false — the playbook says publication is manual; a stale key is how a repo ends up with tags and an empty Releases page #85).";
1600
- else if (manifestVer && releasesWanted) {
1601
- // forge release for the verified tag — gh for GitHub, glab for GitLab. A failed create is no
1602
- // longer the end of the story: the proof below asks the forge whether anything is there (#63, #85)
1603
- const tag = expectedTag!;
1604
- if (forgeName === "self") ghNote = "Forge release skipped (forge=self — publication stays manual).";
1605
- else {
1606
- // the body is the changelog entry for this version (#97); the tag annotation only stands in
1607
- // when the changelog has no entry for it — and never the output of a failed command, which
1608
- // is how a shell error became a release body (#51)
1609
- const notesRes = await sh(tagNotesCommand(tag), root);
1610
- const annotation = notesRes.ok ? notesRes.out.trim() : "";
1611
- let changelogText: string | null = null;
1612
- if (cfg.release.changelog) {
1613
- const cl = path.join(gateCwd(root, state!), cfg.release.changelog);
1614
- if (existsSync(cl)) changelogText = readFileSync(cl, "utf8");
1615
- }
1616
- const picked = pickReleaseNotes({ changelog: changelogText, version: manifestVer, annotation });
1617
- const notes = picked.notes;
1618
- if (picked.source === "changelog") bodyOfRecord = notes;
1619
- let notesNote = "";
1620
- if (picked.source === "changelog") notesNote = `notes from ${cfg.release.changelog}. `;
1621
- else if (picked.source === "annotation") notesNote = `notes from the ${tag} tag annotation — ${cfg.release.changelog ?? "no changelog"} has no ${manifestVer} entry, so the release page does not read like the changelog. `;
1622
- else if (!notesRes.ok) notesNote = `no release notes (the tag command failed: ${tail(notesRes.out)}). `;
1623
- else if (annotation && looksLikeShellError(annotation)) notesNote = "no release notes (the tag command returned a shell error, not a body). ";
1624
- else notesNote = `no release notes (tag ${tag} carries no annotation${cfg.release.changelog ? ` and ${cfg.release.changelog} has no ${manifestVer} entry` : ""} — tag with git tag -a). `;
1625
- const cmd = forgeName === "gitlab"
1626
- ? `glab release create ${sq(tag)} --name ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`
1627
- : `gh release create ${sq(tag)} --title ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`;
1628
- const gr = await sh(cmd, root);
1629
- // a failed create is the operator's call to decline, never a choice we make for them — stamp it so finish names it (#63)
1630
- if (gr.ok) delete state!.forgeReleaseSkipped; // a successful retry lifts the stamp
1631
- else state!.forgeReleaseSkipped = tail(gr.out);
1632
- ghNote = gr.ok ? `${forgeName} release ${tag} created. ${notesNote}`.trim() : `${forgeName} release skipped: ${tail(gr.out)}`;
1633
- }
1634
- }
1635
- const skew = buildSkew(root);
1636
- const openRelease = checklistPending(cfg, state!, "release");
1637
- // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
1638
- // name them at the last objective gate — on the way out too, or the refusal hides half the story
1639
- const openNote = openRelease ? `release-stage checklist still open (${openRelease}): ${applicableItems(cfg, state!, "release").map((i) => i.text).join(" | ")} — close these with the operator before finishing.` : "";
1640
- // #85: ask the forge whether the release exists instead of trusting the attempt. #51, #60 and #63
1641
- // were three ways of recording a release nothing published, and the artifact probe saw none of them
1642
- if (releasesWanted && expectedTag && forgeName !== "self") {
1643
- const view = forgeName === "gitlab" ? `glab release view ${sq(expectedTag)}` : `gh release view ${sq(expectedTag)}`;
1644
- if (!(await sh(view, root)).ok) {
1645
- return { text: `release gate FAILED:\n- no ${forgeName} release exists for ${expectedTag} — create it (${view.split(" ")[0]} release create ${expectedTag}) or, if publication is deliberately manual, say so with release.releases = false in project.md${ghNote ? `. ${ghNote}` : ""}${openNote ? ` ${openNote}` : ""}`, isError: true };
1646
- }
1647
- delete state!.forgeReleaseSkipped; // the forge has it, whatever the create call reported
1648
- ghNote += `${ghNote ? " " : ""}Release ${expectedTag} verified on ${forgeName}.`;
1649
- // #97: the changelog entry is the release body — prove the forge kept it. gh normalizes the
1650
- // markdown it stored, so the comparison normalizes too; on another forge say it was skipped
1651
- // rather than guess at a JSON shape nobody pinned.
1652
- if (bodyOfRecord !== null) {
1653
- if (forgeName !== "github") bodyNote = `Release body proof skipped (forge=${forgeName}).`;
1654
- else {
1655
- const got = await sh(`gh release view ${sq(expectedTag)} --json body --jq .body`, root);
1656
- if (!got.ok) bodyNote = `warning: could not read back the ${expectedTag} release body — compare it with ${cfg.release.changelog} by hand.`;
1657
- else if (normalizeReleaseBody(got.out) !== normalizeReleaseBody(bodyOfRecord))
1658
- return {
1659
- text: `release gate FAILED:\n- the ${expectedTag} release body is not the ${cfg.release.changelog} entry for ${manifestVer} — publish the entry as the body: gh release edit ${expectedTag} --title ${expectedTag} --notes-file <(the entry)\n forge body starts: ${tail(normalizeReleaseBody(got.out), 4)}\n changelog entry starts: ${tail(normalizeReleaseBody(bodyOfRecord), 4)}`,
1660
- isError: true,
1661
- };
1662
- else bodyNote = `Release ${expectedTag} body matches ${cfg.release.changelog}.`;
1663
- }
1664
- }
1665
- }
1666
- state!.approvals.release = now();
1667
- const tailNote = [
1668
- // a session that shipped from behind: the code it runs is not the code the checkout just released
1669
- state!.staleBuild
1670
- ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
1671
- : skew.behind
1672
- // #117: the pair (session vs what the disk ships) makes the warning actionable where it prints;
1673
- // a second registered copy is what made the skew confusing on the report — name it too
1674
- ? `warning: ${skew.line}.${copyWarning() ? ` ${copyWarning()}` : ""}`
1675
- : "",
1676
- mergeNote,
1677
- openNote,
1678
- ghNote,
1679
- bodyNote,
1680
- artNote,
1681
- ].filter(Boolean).join(" ");
1682
- writeState(root, state!);
1683
- return { text: `release recorded as complete${state!.noVersion ? " (unversioned — the changelog entry ships under Unreleased; the next versioned release folds it)" : ""}.${tailNote ? ` ${tailNote}` : ""}\n${nextHint(state!, cfg)}` };
1684
- }
1685
-
1686
- async function gateFinish(o: GateCtx): Promise<RunResult> {
1687
- const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
1688
- const { state, err } = needState(root, sess, slugArg);
1689
- if (err) return err;
1690
- if (!state!.approvals.release)
1691
- return { text: `finish closes a released feature — stage is "${state!.stage}" and no release is recorded; run flow release-done first (to abandon an unfinished feature, run flow abort)`, isError: true };
1692
- // after this the flow state is gone: nothing may sit uncommitted or unpushed
1693
- const dirty = await sh("git status --porcelain", root);
1694
- if (dirty.ok && dirty.out.trim()) return { text: `main checkout has uncommitted changes — commit them first (finish deletes .dev-flow/${state!.slug}/):\n${tail(dirty.out)}`, isError: true };
1695
- const origin = await originUrl(root);
1696
- const hasOriginF = origin !== null;
1697
- if (hasOriginF) {
1698
- const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1699
- if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
1700
- }
1701
- // close-out also syncs the main checkout: a released flow must never leave local
1702
- // <default> trailing origin — the push check above proved nothing local-only remains, so a
1703
- // differing sha means local trails and the fast-forward is safe. never a merge: a diverged
1704
- // or not-checked-out main prints the operator's exact command instead of touching anything
1705
- let syncNote = "";
1706
- if (hasOriginF) {
1707
- const headSha = await sh("git rev-parse HEAD", root);
1708
- const originSha = await sh(`git rev-parse ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1709
- if (headSha.ok && originSha.ok && headSha.out.trim() !== originSha.out.trim()) {
1710
- const onDefault = (await currentBranch(root)) === cfg.defaultBranch;
1711
- const ff = onDefault ? await sh(`git merge --ff-only ${sq(`origin/${cfg.defaultBranch}`)}`, root) : { ok: false, out: "" };
1712
- syncNote = ff.ok
1713
- ? ` local ${cfg.defaultBranch} fast-forwarded to origin/${cfg.defaultBranch}.`
1714
- : ` local ${cfg.defaultBranch} trails origin/${cfg.defaultBranch} and did not fast-forward cleanly — sync by hand: git -C ${sq(root)} pull --ff-only`;
1715
- }
1716
- }
1717
- // the cleanup part of closing out: drop the worktree and branch the release consumed
1718
- const wt = worktreeAbs(root, state!);
1719
- let closeNote: string;
1720
- let unmergedNote = "";
1721
- if (wt && existsSync(wt)) {
1722
- const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
1723
- const unmerged = await sh(`git -C ${sq(wt)} log origin/${cfg.defaultBranch}..HEAD --oneline 2>/dev/null || git -C ${sq(wt)} log ${cfg.defaultBranch}..HEAD --oneline`, root);
1724
- const unmergedLines = unmerged.out.split("\n").filter(Boolean);
1725
- // the refusal names the paths, not just the count — same proof verify and release print (gh#131)
1726
- if (status.out.trim()) return { text: `finish blocked:\n- worktree has uncommitted changes — commit or discard them first:\n${tail(status.out)}`, isError: true };
1727
- if (unmergedLines.length) {
1728
- const policy = cfg.release.merge;
1729
- // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1730
- // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1731
- const measurable = hasOriginF && !!state!.branch && (await sh(`git show-ref --quiet --verify ${sq(`refs/remotes/origin/${state!.branch}`)} ${sq(`refs/remotes/origin/${cfg.defaultBranch}`)}`, root)).ok;
1732
- unmergedNote =
1733
- policy && policy !== "merge" && policy !== "any"
1734
- ? ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1735
- : policy === "merge" && measurable
1736
- ? ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} although the playbook says merge = merge — that PR did not land as a merge commit`
1737
- : ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1738
- // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1739
- // answer it, only the operator does
1740
- if (policy === "merge" && measurable && !flag("confirmed")) {
1741
- markPendingAsk(root, state!, "Merge policy violation?");
1742
- return { text: needsOperator(`the playbook says merge = merge, but ${unmergedLines.length} commit(s) of ${state!.slug} are not on ${cfg.defaultBranch} — the PR landed as a squash or a rebase. Ask the operator how to proceed, then re-run with --confirmed`, "Merge policy violation?"), isError: true };
1743
- }
1744
- }
1745
- }
1746
- // a forge release that failed at release-done is still the operator's call — but they must see it before the state vanishes (#63)
1747
- const forgeSkipNote = state!.forgeReleaseSkipped ? ` WARNING: the forge release was not created (${state!.forgeReleaseSkipped}) — recreate it manually or re-run release-done before finishing.` : "";
1748
- // the one finish question — asked after the safety checks so it can never be a wasted question
1749
- // yolo works uniformly at every gate: at Finish? nothing later remains to pre-confirm, the flag just answers this one
1750
- const yoloWord = takeYoloWord(state!);
1751
- if (yoloWord) return { text: yoloWord, isError: true };
1752
- // The closing reflection runs here, before anything is removed: the worker reads this session's
1753
- // transcripts and .dev-flow/<slug>/tmp, and finish is about to drop that folder and the binding — a
1754
- // reflection asked for after finish has nothing bound to run against. Only the operator's explicit
1755
- // --no-reflect skips it; yolo never does (it answers checkpoints, it does not waive the review).
1756
- const skipReflect = flag("no-reflect");
1757
- if (skipReflect && !flag("confirmed")) return { text: "--no-reflect is the operator's word — ask them whether to skip the closing reflection, then re-run with --no-reflect --confirmed", isError: true };
1758
- if (!state!.reflectedAt && !skipReflect) {
1759
- const skipHint = "or — only on the operator's explicit word — flow finish --no-reflect --confirmed";
1760
- if (!o.hooks.reflect) return { text: `finish: no reflection recorded for ${state!.slug} and no reflect worker available here — run flow_stage(op: "reflect") first, ${skipHint}`, isError: true };
1761
- const r = await o.hooks.reflect(state!, flagValue(o.rest, "note") ?? "");
1762
- const cur = readState(root, state!.slug) ?? state!; // the worker stamped reflectedAt on disk
1763
- if (!r.recorded)
1764
- return { text: `finish: the closing reflection did not report — nothing was removed.\n\n${r.text}\n\nNext: re-run flow finish to retry, or review inline (bare flow reflect prints the protocol) and then flow_stage(op: "reflect"), ${skipHint}.`, isError: true };
1765
- if (!r.findings) {
1766
- markPendingAsk(root, cur, "Finish?");
1767
- return { text: needsOperator(`the closing reflection ran before cleanup and found nothing new to fold — nothing was removed yet.\n\n${r.text}\n\nAsk the operator Finish? and run flow finish --confirmed when they answer: the worktree, branch and .dev-flow/${state!.slug}/ go on that run.`, "Finish?"), isError: true };
1768
- }
1769
- markPendingAsk(root, cur, "Fold or drop?");
1770
- return { text: needsOperator(`the closing reflection ran before cleanup — nothing was removed yet.\n\n${r.text}\n\nThe fold/drop answer is the Finish? answer: apply it, then run flow finish --confirmed without asking again — the worktree, branch and .dev-flow/${state!.slug}/ go on that run.`, "Fold or drop?"), isError: true };
1771
- }
1772
- const reflectSkipNote = skipReflect && !state!.reflectedAt ? ` Reflection skipped on the operator's word — nothing re-checked this session or the open reflections.` : "";
1773
- const askPending = !flag("confirmed") && !state!.yolo;
1774
- if (askPending) {
1775
- markPendingAsk(root, state!, "Finish?");
1776
- if (!ui.hasUI) {
1777
- return { text: needsOperator(`finish needs the operator: ask them Finish? in chat, then re-run with --confirmed (or run /flow finish interactively)${forgeSkipNote}`, "Finish?"), isError: true };
1778
- }
1779
- const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1780
- if (!ok) {
1781
- delete state!.pendingAsk;
1782
- writeState(root, state!);
1783
- return { text: "finish declined" };
1784
- }
1785
- }
1786
- // a side-by-side dev instance (a port the operator picked at verify) is this flow's to stop; the default
1787
- // port's stack stays up — it is the machine's shared app, and the next flow redeploys over it
1788
- let devDownNote = "";
1789
- if (state!.devPort !== undefined && state!.devPort !== cfg.devPort) {
1790
- if (cfg.commands.devDown) {
1791
- const down = await sh(cfg.commands.devDown, gateCwd(root, state!), 5 * 60_000, devEnv(root, state!, cfg));
1792
- devDownNote = 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`;
1793
- } else devDownNote = ` dev instance on port ${state!.devPort} is still running — the playbook has no devDown to stop it; stop it by hand.`;
1794
- }
1795
- const reg = readDevPorts(root);
1796
- const mine = Object.keys(reg).filter((k) => reg[k].slug === state!.slug);
1797
- if (mine.length) {
1798
- for (const k of mine) delete reg[k];
1799
- writeDevPorts(root, reg);
1800
- }
1801
- if (wt && existsSync(wt)) {
1802
- const rm = await sh(`git worktree remove ${sq(wt)} && git branch -D ${sq(state!.branch)}`, root);
1803
- if (!rm.ok) return { text: `worktree removal failed:\n${rm.out}\nif files are owned by another user (e.g. root-owned docker build output), remove ${state!.worktree} manually and rerun flow finish`, isError: true };
1804
- closeNote = `worktree and branch ${state!.branch} removed`;
1805
- } else {
1806
- await sh("git worktree prune", root);
1807
- closeNote = "worktree already gone";
1808
- if (state!.branch && (await sh(`git rev-parse --verify --quiet refs/heads/${state!.branch}`, root)).ok) {
1809
- const del = await sh(`git branch -d ${sq(state!.branch)}`, root);
1810
- closeNote = del.ok ? `branch ${state!.branch} deleted` : `branch ${state!.branch} kept (not fully merged — git branch -D if sure)`;
1811
- }
1812
- }
1813
- // remote cleanup: origin/<branch> is deleted only on proof it was released — being an ancestor of
1814
- // origin/<default> (merge-commit merges) or a merged PR via gh (squash merges); else it stays.
1815
- let remoteNote = "";
1816
- if (state!.branch && hasOriginF) {
1817
- const br = state!.branch;
1818
- const onRemote = await sh("git ls-remote --heads origin", root);
1819
- if (onRemote.out.split("\n").some((l) => l.endsWith(`\trefs/heads/${br}`))) {
1820
- await sh(`git fetch -q origin ${sq(br)}`, root);
1821
- let merged = (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok;
1822
- // squash merges leave no ancestry — ask the forge (gh/glab); self-hosted stays on ancestry proof
1823
- if (!merged) merged = (await forgeMergeStyle(root, forgeOf(cfg, origin), br)) !== null;
1824
- if (merged) remoteNote = (await sh(`git push origin --delete ${sq(`refs/heads/${br}`)}`, root)).ok
1825
- ? ` origin/${br} deleted (verified merged)`
1826
- : ` origin/${br} delete failed — git push origin --delete ${br}`;
1827
- else remoteNote = ` origin/${br} kept — merged state not verifiable from here (git push origin --delete ${br} when sure)`;
1828
- }
1829
- }
1830
- rmSync(featDir(root, state!.slug), { recursive: true, force: true });
1831
- if (sess.slug === state!.slug) sess.bind(null);
1832
- // a feature picked from the backlog closes its own item: check off what `roadmap pick` stamped (slug)
1833
- let roadmapNote = "";
1834
- if (existsSync(roadmapFile(root))) {
1835
- const r = roadmapDoneForSlug(readRoadmap(root), state!.slug, new Date().toISOString().slice(0, 10));
1836
- if (r.count) {
1837
- writeFileSync(roadmapFile(root), r.text);
1838
- roadmapNote = ` roadmap: ${r.count} item(s) marked done.`;
1839
- }
1840
- }
1841
- // finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
1842
- const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
1843
- const nudgeNote = [nudge.fix, nudge.tidy].filter(Boolean).map((n) => ` ${n} — offer it to the operator.`).join("");
1844
- return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${devDownNote}${roadmapNote}${forgeSkipNote}${reflectSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
1845
- }
1846
-
1847
- /** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
1848
- const mainHookBody = (branch: string) =>
1849
- `branch=$(git rev-parse --abbrev-ref HEAD)\nif [ "$branch" = "${branch}" ] && [ -z "$DEV_FLOW_ALLOW_MAIN" ]; then\n echo "dev-flow: direct commits to ${branch} are forbidden — use a feature worktree and a PR" >&2\n exit 1\nfi\n`;
1850
-
1851
- /** Value tokens of a multi-value flag: everything after `--name` up to the next `--flag`. */
1852
- function flagValues(rest: string[], name: string): string[] {
1853
- const i = rest.indexOf(`--${name}`);
1854
- if (i === -1) return [];
1855
- const out: string[] = [];
1856
- for (let j = i + 1; j < rest.length && !rest[j].startsWith("--"); j++) out.push(rest[j]);
1857
- return out;
1858
- }
1859
-
1860
- async function gateInit(o: GateCtx): Promise<RunResult> {
1861
- const { root, ui, rest, flag } = o;
1862
- // a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
1863
- // only sanctioned agent path to the playbook: claiming "created" when the folder was already
1864
- // there sends the agent diffing its own config for damage that never happened (#39).
1865
- const dfExisted = existsSync(dfDir(root));
1866
- mkdirSync(dfDir(root), { recursive: true });
1867
- const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
1868
- // self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
1869
- writeFileSync(path.join(dfDir(root), ".gitignore"), "*\n!project.md\n");
1870
- const mdFile = path.join(dfDir(root), "project.md");
1871
- const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
1872
- const curBr = await currentBranch(root);
1873
- // never propose a feature branch (contains "/") as the default branch
1874
- const branch = (head.ok ? head.out.match(/refs\/remotes\/origin\/(.+)/)?.[1] : undefined) || (curBr.includes("/") ? undefined : curBr) || "main";
1875
- const det = detectProject(root, branch);
1876
- const origin = await originUrl(root);
1877
- det.partial.forge = origin ? detectForge(origin) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
1878
- const mergeEv = await mergeHistoryEvidence(root, branch); // "what do you actually do when a PR merges", read off the log
1879
- det.partial.merge = mergeEv?.note;
1880
- const tagEv = await tagPatternEvidence(root);
1881
- if (tagEv) {
1882
- det.partial.versionTag = tagEv.pattern;
1883
- det.report.push(`tags: ${tagEv.note} → versionTag = ${tagEv.pattern}`);
1884
- }
1885
- const draftFresh = buildDraft(det);
1886
- const questions = setupQuestions(det, { merge: mergeEv, tag: tagEv });
1887
- if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
1888
- // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
1889
- const ghosts = ghostFeatureDirs(root);
1890
- if (ghosts.length) {
1891
- if (!ui.hasUI) notes.push(`${ghosts.length} ghost feature dir(s) — a plan/ with no state.json, no flow owns them (${ghosts.join(", ")}); adopt one with flow start <slug> --confirmed, delete them, or run flow init interactively`);
1892
- else if (await ui.confirm("Remove ghost feature dirs?", `${ghosts.map((g) => `${g} — plan/ with no state.json`).join("\n")}\n\nNo flow owns these; their plan/*.md is not recoverable afterwards. To keep one as a new feature's draft, decline and run flow start <slug> --confirmed.`)) {
1893
- for (const g of ghosts) rmSync(path.join(root, g), { recursive: true, force: true });
1894
- notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
1895
- } else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
1896
- }
1897
- const current = existsSync(mdFile) ? readFileSync(mdFile, "utf8") : null;
1898
- /** Validate, back up what was there (the operator's rules are not regenerable), write. */
1899
- const writeMd = (text: string): { rej: RunResult } | { warn: string[] } => {
1900
- const parsed = parseProjectMd(text);
1901
- if (parsed.hard.length) return { rej: { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true } };
1902
- if (existsSync(mdFile)) copyFileSync(mdFile, `${mdFile}.bak`);
1903
- writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
1904
- return { warn: parsed.warn };
1905
- };
1906
- /** After a write: the playbook belongs in git — commit it on the operator's word, else say how. */
1907
- const afterWrite = async (w: { warn: string[] }, before: string | null, after: string, offer = false): Promise<void> => {
1908
- notes.push(`changes:\n${lineDiff(before ?? "", after)}`);
1909
- if (w.warn.length) notes.push("warnings:", ...w.warn.map((x) => ` ${x}`));
1910
- // the dialog belongs to the human-driven first init only: an agent write (--write/--answers) follows a chat
1911
- // confirmation and must not open a second question — it commits on --track
1912
- const track = flag("track") || (offer && ui.hasUI && (await ui.confirm("Commit project.md?", "The playbook belongs in git. Commit .dev-flow/project.md now (only that file, as a playbook chore)?")));
1913
- if (!track) {
1914
- notes.push(GIT_TRACK_NOTE, "(or re-run the same call with --track on the operator's word)");
1915
- return;
1916
- }
1917
- const c = await sh(`git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(before ? "chore: update dev-flow playbook" : "chore: add dev-flow playbook")} -- .dev-flow/project.md`, root, 60_000);
1918
- notes.push(c.ok ? "project.md committed (git add -f + playbook chore)" : `commit failed — ${c.out.split("\n").find(Boolean) ?? "?"}; ${GIT_TRACK_NOTE}`);
1919
- };
1920
- 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 ?? ""}>`]; })() : [])];
1921
- if (flag("answers") || flag("answers-file")) {
1922
- // the operator's answers, applied as targeted edits onto the draft (first init) or the current file —
1923
- // hand-written lines survive; the result is previewed until the operator's word anchors the write
1924
- const parsed = parseAnswers(answerToks);
1925
- if (parsed.errors.length) return { text: `answers REJECTED:\n- ${parsed.errors.join("\n- ")}`, isError: true };
1926
- if (!parsed.answers.length) return { text: "usage: flow init --answers key=value [key=value …] | --answers-file <path> (one key=value per line)", isError: true };
1927
- const base = current ?? draftFresh;
1928
- const applied = applyAnswers(base, parsed.answers);
1929
- const lint = parseProjectMd(applied.text);
1930
- if (lint.hard.length) return { text: `project.md REJECTED:\n- ${lint.hard.join("\n- ")}`, isError: true };
1931
- const preview = [`${current ? "playbook" : "draft"} with ${parsed.answers.length} answer(s):`, ...applied.changes.map((c) => ` ${c}`), "", mdDigest(applied.text)];
1932
- const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Write project.md?", preview.join("\n"))));
1933
- if (!ok) {
1934
- const open = questions.filter((x) => !parsed.answers.some(([k]) => k === x.key || (x.key === "check.<name>" && (k.startsWith("check.") || ["test", "build", "run"].includes(k)))));
1935
- return { text: [...preview, "", `changes:\n${lineDiff(base, applied.text)}`, "", "not written — present this to the operator; on their confirmation re-run the same call with --confirmed", ...(open.length ? ["still unanswered:", ...renderQuestions(open)] : [])].join("\n") };
1936
- }
1937
- const w = writeMd(applied.text);
1938
- if ("rej" in w) return w.rej;
1939
- notes.push(`project.md written with ${parsed.answers.length} answer(s)`);
1940
- await afterWrite(w, current, applied.text);
1941
- } else if (flag("write") || flag("write-file")) {
1942
- let content: string | undefined;
1943
- if (flag("write-file")) {
1944
- const f = flagValues(rest, "write-file")[0];
1945
- if (!f || !existsSync(path.resolve(root, f))) return { text: `usage: flow init --write-file <path> — ${f ? `${f} does not exist` : "no path given"}`, isError: true };
1946
- content = readFileSync(path.resolve(root, f), "utf8");
1947
- } else {
1948
- content = rest[rest.indexOf("--write") + 1];
1949
- if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>" (or --write-file <path>)', isError: true };
1950
- }
1951
- const w = writeMd(content);
1952
- if ("rej" in w) return w.rej;
1953
- notes.push("project.md written (operator-owned playbook)");
1954
- await afterWrite(w, current, content);
1955
- } else if (!current) {
1956
- // first init: never write silently. The questions come first — a dialog that offered the bare detection
1957
- // draft before them wrote a playbook with the merge style, forge and versioning still unanswered.
1958
- const brief = [
1959
- "setup — project.md not written yet; nothing is drafted to disk until the operator confirms.",
1960
- "detected:",
1961
- ...det.report.map((r) => ` ${r}`),
1962
- "questions for the operator (detected value shown; `accept` is the answer that keeps it):",
1963
- ...renderQuestions(questions),
1964
- "agent: ask these in chat — group the ones with an `accept` line as \"keep these?\", explain the rest in a line each. Then apply every answer in one call: flow init --answers key=value … (previews the digest and diff, writes nothing); on the operator's confirmation re-run it with --confirmed (add --track to commit the playbook). Free-text additions — checklist items, prose, flow-guard rules — go in through flow init --write-file <path> with the full file (flow init --draft prints the current draft).",
1965
- ];
1966
- let wrote = false;
1967
- if (ui.hasUI) {
1968
- const accepts = questions.filter((x) => x.accept).map((x) => x.accept!);
1969
- const withAccepts = applyAnswers(draftFresh, parseAnswers(accepts).answers).text;
1970
- const ok = await ui.confirm("Accept the detected setup?", `${mdDigest(withAccepts)}\n\nWrite this now, keeping every detected value? ${questions.length - accepts.length} question(s) have no detected answer (${questions.filter((x) => !x.accept).map((x) => x.key).join(", ")}) — decline to answer them in chat first.`);
1971
- if (ok) {
1972
- const w = writeMd(withAccepts);
1973
- if ("rej" in w) return w.rej;
1974
- wrote = true;
1975
- notes.push("wrote .dev-flow/project.md from detection with the detected values accepted — change any of them with flow init --answers key=value", ...det.report.map((r) => ` ${r}`));
1976
- const open = questions.filter((x) => !x.accept);
1977
- if (open.length) notes.push("still open (answer any time):", ...renderQuestions(open));
1978
- await afterWrite(w, null, withAccepts, true);
1979
- }
1980
- }
1981
- if (!wrote) notes.push(...brief);
1982
- } else if (flag("force")) {
1983
- // a destructive reset of the operator's own file needs their word: --confirmed for an agent, one dialog for a human
1984
- const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Overwrite project.md?", `flow init --force replaces the operator playbook with a fresh detection draft. Hand-written rules, checklist items and guidance are lost (a copy is kept as project.md.bak).`)));
1985
- if (!ok) return { text: "flow init --force overwrites the operator playbook — that needs the operator's word: re-run with --confirmed (the current file is kept as project.md.bak)", isError: true };
1986
- copyFileSync(mdFile, `${mdFile}.bak`);
1987
- writeFileSync(mdFile, draftFresh);
1988
- notes.push("project.md OVERWRITTEN (--force; previous copy kept as project.md.bak):", ...det.report.map((r) => ` ${r}`), GIT_TRACK_NOTE);
1989
- } else {
1990
- // re-init is the doctor's file-level check: findings are printed, the playbook is never regenerated —
1991
- // a draft cannot reproduce hand-written prose, items and keys. Edit the file, or flow init --write.
1992
- const loaded = loadProject(dfDir(root));
1993
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
1994
- notes.push("project.md already exists — kept (edit it directly, flow init --answers key=value for one knob, --write-file to replace it, --force to redraft)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
1995
- }
1996
- const initCfg = loadProject(dfDir(root)).cfg;
1997
- if (initCfg.mainHook) {
1998
- // a hook manager (husky, lefthook…) points core.hooksPath elsewhere: git never runs .git/hooks then,
1999
- // so a hook installed there would guard nothing — print the lines for the manager's own hook instead
2000
- const hp = await sh("git config --get core.hooksPath", root, 10_000);
2001
- const hooksPath = hp.ok ? hp.out.trim() : ""; // unset exits 1, and sh() then carries the error text
2002
- const hookDir = path.join(root, ".git", "hooks");
2003
- const hook = path.join(hookDir, "pre-commit");
2004
- const body = mainHookBody(initCfg.defaultBranch);
2005
- if (hooksPath && path.resolve(root, hooksPath) !== hookDir) {
2006
- const theirs = path.join(hooksPath, "pre-commit");
2007
- const has = existsSync(path.resolve(root, theirs)) && readFileSync(path.resolve(root, theirs), "utf8").includes("DEV_FLOW_ALLOW_MAIN");
2008
- if (!has) notes.push(`core.hooksPath = ${hooksPath} — git runs hooks from there, not .git/hooks, so dev-flow installed none; to block main commits outside Pi, add to ${theirs}:\n${body}`);
2009
- } else if (existsSync(hookDir) && !existsSync(hook)) {
2010
- writeFileSync(hook, `#!/bin/sh\n# installed by dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden (override: DEV_FLOW_ALLOW_MAIN=1)\n${body}`, { mode: 0o755 });
2011
- notes.push("pre-commit hook installed (blocks commits on main)");
2012
- } else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow") && !readFileSync(hook, "utf8").includes("DEV_FLOW_ALLOW_MAIN")) {
2013
- notes.push(`existing pre-commit hook found — dev-flow did not replace it; main commits outside Pi stay unguarded until you add to .git/hooks/pre-commit:\n${body}`);
2014
- }
2015
- }
2016
- return { text: notes.join("\n") };
2017
- }
2018
-
2019
- async function gateStart(o: GateCtx): Promise<RunResult> {
2020
- const { root, sess, cfg, rest, flag, slugArg } = o;
2021
- if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --ui/--patch/--docs are operator-granted — ask the operator in chat, then add --confirmed", isError: true };
2022
- // a ghost (plan/ but no state.json — typically a spin-off someone wrote by hand) is adopted, never a dead end:
2023
- // "already exists, flow use it" sent the agent to use, which found no state, and doctor offered to delete it
2024
- const ghost = existsSync(featDir(root, slugArg)) && !existsSync(stateFile(root, slugArg)) && existsSync(path.join(featDir(root, slugArg), "plan"));
2025
- if (ghost && !flag("confirmed")) {
2026
- const files = listFiles(path.join(featDir(root, slugArg), "plan"));
2027
- return { text: `.dev-flow/${slugArg}/ is a ghost — plan/ (${files.join(", ") || "empty"}) but no state.json, so no flow owns it. Adopt it as this feature's draft plan: flow start ${slugArg} --confirmed (the operator agrees in chat), or delete the dir to start clean`, isError: true };
2028
- }
2029
- if (existsSync(featDir(root, slugArg)) && !ghost) {
2030
- // --ui on the plan-stage feature this session drives: the operator asked for mockups after the start,
2031
- // so turn the mockup gate on instead of refusing — a UI feature left at ui=false skips the mockup
2032
- // proof at approve and every (ui) checklist item (lettuce rail-ui-fixes shipped 20 ungated mockups)
2033
- const existing = readState(root, slugArg);
2034
- if (flag("ui") && existing && sess.slug === slugArg) {
2035
- if (!flag("confirmed")) return { text: "--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate; ask the operator, then re-run with --confirmed", isError: true };
2036
- if (existing.ui) return { text: `feature ${slugArg} already has the ui flag` };
2037
- if (existing.stage !== "plan") return { text: `feature ${slugArg} is at ${existing.stage} — the ui flag can be set only at plan (the mockup gate is approve's); render the screens anyway and say so in the verify report`, isError: true };
2038
- writeState(root, { ...existing, ui: true });
2039
- return { text: `ui flag set on existing feature ${slugArg} (plan stage): the approve gate now requires rendered mockups under plan/mockups/ (${cfg.mockupGlobs.join(", ")}), each embedded in plan.md, and the (ui) checklist items apply` };
2040
- }
2041
- return { text: `feature ${slugArg} already exists — flow use ${slugArg} to resume it${existing?.stage === "plan" ? `; to add the mockup gate at plan, run flow start ${slugArg} --ui --confirmed from the session bound to it` : ""}`, isError: true };
2042
- }
2043
- // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
2044
- if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
2045
- const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
2046
- if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — the operator must grant it in chat, then re-run with --confirmed`, isError: true };
2047
- // --ui adds the rendered-mockup gate to plan: worth it only when screens change, and the operator says so
2048
- if (flag("ui") && !flag("confirmed")) return { text: "--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate, so use it only when the feature changes screens; ask the operator, then re-run with --confirmed", isError: true };
2049
- // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
2050
- const curBr = await currentBranch(root);
2051
- if (curBr !== cfg.defaultBranch && !flag("force")) return { text: `main checkout is on ${curBr}, not ${cfg.defaultBranch} — check out ${cfg.defaultBranch} first (git checkout ${cfg.defaultBranch} && git pull) or flow use an unfinished feature; --force to override`, isError: true };
2052
- // --- preflight: is this session running the current build, and is the playbook complete? ---
2053
- const notes: string[] = [];
2054
- const skew = buildSkew(root);
2055
- if (skew.line) notes.push(`warning: ${skew.line}`);
2056
- const dupStart = copyWarning();
2057
- if (dupStart) notes.push(dupStart);
2058
- if (flag("check-upstream")) {
2059
- const newest = await publishedVersion(root);
2060
- notes.push(newest ? `published dev-flow: ${newest} (this build: ${loadedVersion() ?? "?"})${loadedVersion() && newest !== loadedVersion() ? " — an update is available" : ""}` : "could not read the published dev-flow version (offline?)");
2061
- }
2062
- // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
2063
- const gaps = doctorFindings(root, cfg, loadProject(dfDir(root)).md).filter((x) => !x.startsWith("no merge policy"));
2064
- if (gaps.length) notes.push(`playbook gaps (${gaps.length}) — advisory, flow doctor reviews and routes them:\n${gaps.slice(0, 5).map((g) => ` ${g}`).join("\n")}`);
2065
- // the merge policy is the one blocking gap: it decides the shape of the default branch and nobody can
2066
- // reconstruct it afterwards. Ask once in chat (a checkpoint word like any other), write the answer, continue.
2067
- const styleArg = flagValue(rest, "merge");
2068
- const style = styleArg === null ? null : parseMergeStyle(styleArg);
2069
- if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
2070
- if (!cfg.release.merge || (style && style !== cfg.release.merge)) {
2071
- if (!style) {
2072
- const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
2073
- return {
2074
- text: needsOperator(
2075
- `the playbook has no merge policy — ask the operator how a merged PR should land on ${cfg.defaultBranch}: squash, merge (a merge commit), rebase, or any (no policy).${ev ? ` ${ev.note}${ev.recent ? ` Detected suggestion: ${ev.recent}.` : ""}` : ""} Then re-run: flow start ${slugArg} --merge=<style> --confirmed (the answer is written into .dev-flow/project.md)`,
2076
- "Merge policy?",
2077
- ),
2078
- isError: true,
2079
- };
2080
- }
2081
- if (!flag("confirmed")) return { text: `writing merge = ${style} changes the operator playbook — the operator must answer it in chat first, then re-run with --confirmed`, isError: true };
2082
- const written = await writePlaybookMergePolicy(root, style);
2083
- if ("err" in written) return { text: written.err, isError: true };
2084
- // the flow that just wrote the policy must see it: nextHint and the merge guard read this config
2085
- cfg.release.merge = style;
2086
- notes.push(written.note);
2087
- }
2088
- // stamp the dev-flow build that started this feature — a stuck flow can later be read against its tooling.
2089
- // the stamp is what ran, not what the disk claims (that mismatch is the warning above).
2090
- const state = newState(slugArg, flag("ui"), flag("patch"), flag("docs"), loadedVersion() ?? undefined);
2091
- const planDir = path.join(featDir(root, slugArg), "plan");
2092
- if (ghost) notes.push(`adopted ghost .dev-flow/${slugArg}/ — its plan/ (${listFiles(planDir).join(", ") || "empty"}) is this feature's draft`);
2093
- mkdirSync(planDir, { recursive: true });
2094
- // a roadmap item stamped for this slug carries its brief into the plan: the spin-off's context outlives the session that split it
2095
- const picked = roadmapBriefFor(readRoadmap(root), slugArg);
2096
- if (picked) {
2097
- const planMd = path.join(planDir, "plan.md");
2098
- const carried = `> Carried over from the roadmap: ${picked.item}${picked.brief ? `\n>\n${picked.brief.split("\n").map((l) => `> ${l}`.trimEnd()).join("\n")}` : ""}\n`;
2099
- if (!existsSync(planMd)) {
2100
- writeFileSync(planMd, `# ${slugArg} — plan (draft)\n\n${carried}`);
2101
- notes.push(`roadmap item "${picked.item}" seeded plan/plan.md${picked.brief ? " with its brief" : ""} — a draft: plan it out and approve as usual`);
2102
- } else notes.push(`roadmap item "${picked.item}"${picked.brief ? ` — brief:\n${picked.brief}` : ""}`);
2103
- }
2104
- writeState(root, state);
2105
- sess.bind(slugArg);
2106
- sess.rename(slugArg);
2107
- return { text: `feature ${slugArg} started at stage plan (ui=${state.ui}${state.patch ? ", patch" : state.docs ? ", docs" : ""}${state.flowVersion ? `, dev-flow ${state.flowVersion}` : ""}); session renamed to ${slugArg}.${notes.length ? `\n${notes.join("\n")}` : ""}\n${nextHint(state, cfg)}` };
2108
- }
2109
-
2110
- async function gateApprove(o: GateCtx): Promise<RunResult> {
2111
- const { root, ui, sess, cfg, flag, slugArg } = o;
2112
- const { state, err } = needState(root, sess, slugArg);
2113
- if (err) return err;
2114
- const planDir = path.join(featDir(root, state!.slug), "plan");
2115
- // the embed proofs read the plan document itself: a render that exists on disk but is not
2116
- // embedded in plan.md is one the operator would never be shown
2117
- const planMd = path.join(planDir, "plan.md");
2118
- const planFiles = listFiles(planDir);
2119
- const mockupHtml = planFiles.filter((f) => /^mockups\/.+\.html?$/i.test(f)).map((f) => ({ file: f, html: readFileSync(path.join(planDir, f), "utf8") }));
2120
- const errs = approveGate(state!, cfg, planFiles, existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined, foreignWorktreeLinks(dfDir(root), state!.slug, mockupHtml));
2121
- if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
2122
- const planItems = applicableItems(cfg, state!, "plan");
2123
- let audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
2124
- const askPending = !flag("confirmed");
2125
- if (askPending) {
2126
- markPendingAsk(root, state!, "Approve?");
2127
- if (!ui.hasUI) {
2128
- return { text: needsOperator("plan approval needs the operator: approve interactively, or re-run with --confirmed once the operator answered in chat", "Approve?"), isError: true };
2129
- }
2130
- 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." : ""}`);
2131
- if (!ok) {
2132
- delete state!.pendingAsk;
2133
- writeState(root, state!);
2134
- return { text: "approval declined — keep iterating on the plan" };
2135
- }
2136
- audit = " (confirmed in dialog)";
2137
- }
2138
- // the operator's word at Approve?, recorded only once given: every later gate question is pre-confirmed; checks and guardrails stay
2139
- if (flag("yolo")) state!.yolo = true;
2140
- if (planItems.length) state!.confirmations = { ...state!.confirmations, plan: { hash: checklistHash(planItems), at: now() } };
2141
- const branch = subst(cfg.branchPattern, state!.slug);
2142
- const wtRel = subst(cfg.worktreeDir, state!.slug);
2143
- const wt = path.resolve(root, wtRel);
2144
- let setupNote = "";
2145
- if (!existsSync(wt)) {
2146
- // branch discipline: features branch off the default branch — never from a stale checkout HEAD
2147
- const base = (await sh(`git rev-parse --verify -q origin/${cfg.defaultBranch}`, root)).ok ? `origin/${cfg.defaultBranch}` : cfg.defaultBranch;
2148
- const res = await sh(`git worktree add ${sq(wt)} -b ${branch} ${base}`, root);
2149
- if (!res.ok) return { text: `worktree creation failed:\n${res.out}`, isError: true };
2150
- }
2151
- // setup is worktree work of a normal feature: a docs flow runs no project command at all (#49),
2152
- // and a worktree left behind by a setup that never succeeded must be retried — "fix it and run
2153
- // approve again" was a silent no-op on the reused directory (#49). setup is expected to be idempotent.
2154
- const setupCmd = state!.docs ? undefined : cfg.commands.setup;
2155
- if (setupCmd && !state!.setupAt) {
2156
- const s = await sh(setupCmd, wt);
2157
- if (!s.ok) return { text: `setup failed in ${wtRel} — fix commands.setup, then run flow approve again (the worktree is kept and setup retried):\n${tail(s.out)}`, isError: true };
2158
- state!.setupAt = now();
2159
- setupNote = `\nsetup ran in the worktree (${setupCmd}).`;
2160
- } else if (state!.docs && cfg.commands.setup) {
2161
- setupNote = "\nsetup skipped (docs mode — no project commands run).";
2162
- }
2163
- state!.branch = branch;
2164
- state!.worktree = wtRel;
2165
- state!.stage = "implement";
2166
- state!.approvals.plan = now();
2167
- delete state!.pendingAsk;
2168
- writeState(root, state!);
2169
- return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${setupNote}\n${nextHint(state!, cfg)}` };
2170
- }
2171
-
2172
- async function gateStatus(o: GateCtx): Promise<RunResult> {
2173
- const { root, sess, cfg, flag, slugArg } = o;
2174
- const df = dfDir(root);
2175
- const { md } = loadProject(df);
2176
- // cheap fs probes only (no git subprocesses) — status is a glance, `flow doctor` is the full list
2177
- const findings = md ? doctorFindings(root, cfg, md) : [];
2178
- // a session running an older build than the disk ships is the one thing a glance must say: every
2179
- // gate proof printed since the drift began belongs to the older code.
2180
- const skew = buildSkew(root);
2181
- const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(skew.line ? [`⚠ ${skew.line}`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
2182
- // the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
2183
- const rmap = roadmapOpenCount(readRoadmap(root));
2184
- const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
2185
- const slugs = slugArg ? [slugArg] : unfinishedStates(root).map((s) => s.slug);
2186
- const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
2187
- if (flag("json")) {
2188
- const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
2189
- return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
2190
- }
2191
- if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
2192
- const lines = slugs.flatMap((s) => {
2193
- const st = readState(root, s);
2194
- if (!st) return [];
2195
- return [
2196
- `${s === cur ? "→" : " "} ${s}: stage=${st.stage}${st.ui ? " [ui]" : ""}${st.yolo ? " [yolo]" : ""}${st.noVersion ? " [no-version]" : ""}${st.pendingAsk ? ` 💬 ${st.pendingAsk}` : ""} branch=${st.branch || "-"} worktree=${st.worktree || "-"}${st.flowVersion ? ` flow=${st.flowVersion}` : ""}`,
2197
- ` approvals: ${Object.keys(st.approvals).join(", ") || "none"} | checks: ${Object.entries(st.checks).map(([k, v]) => `${k}:${v.ok ? "ok" : "FAILED"}`).join(", ") || "none"}${st.confirmations?.implement ? " | checklist: confirmed" : ""}`,
2198
- ` next: ${nextHint(st, cfg)}`,
2199
- ];
2200
- });
2201
- // who holds the dev stack: the one thing two parallel flows on one machine must not guess
2202
- for (const [k, v] of Object.entries(readDevPorts(root))) lines.push(`dev: ${k === "default" ? "stack" : `port ${k}`} → ${v.slug} @ ${v.head.slice(0, 7)}, deployed ${ago(v.at)}`);
2203
- if (warn.length) lines.push(...warn);
2204
- // which identity this session's state is keyed by: a claim fight is undiagnosable when the key
2205
- // could be a session id or a shared directory and the output does not say which
2206
- lines.push(`session: ${sess.key}${sess.key.startsWith("cwd:") ? " — no session id from pi, so every pi session in this directory shares one dev-flow binding (pass flow use <slug> in each)" : ""}`);
2207
- const refl = readReflections(root);
2208
- if (refl.length) lines.push(`↻ ${refl.length} reflection(s) open — run flow doctor (it reviews and routes them)`);
2209
- lines.push(...rmapLine);
2210
- return { text: lines.join("\n") || "no features" };
2211
- }
2212
-
2213
- async function gateReflect(o: GateCtx): Promise<RunResult> {
2214
- const { root, sess, rest, flag } = o;
2215
- // gate flags belong to the state verbs — pasted into the note they read as part of the operator's
2216
- // own sentence in reflections.md (#43). --plugin/--playbook/--both are reflect's own: they state
2217
- // the filing instead of leaving it to a keyword guess.
2218
- const words = rest.filter((a) => !a.startsWith("--"));
2219
- const forced: ReflectTarget | null = flag("plugin") ? "plugin" : flag("code") ? "code" : flag("playbook") || flag("docs") ? "playbook" : null;
2220
- // single words are verbs (roadmap-style); a note merely starting with one stays a note
2221
- if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
2222
- if (words.length === 1 && words[0] === "list") return await reflectList(root);
2223
- if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
2224
- if (words[0] === "done") return reflectDoneNote(root, sess, words.slice(1));
2225
- if (words.length) return await reflectNote(root, sess, words, forced);
2226
- const self = pluginVersion(import.meta.dirname);
2227
- const upstream = await pluginUpstream(root);
2228
- const refl = readReflections(root);
2229
- const fold = await foldView(root, refl);
2230
- const nudges = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: !sess.slug });
2231
- return {
2232
- text: reflectProtocol(refl, isSelfRepo(root), {
2233
- version: self.version,
2234
- upstream,
2235
- bound: !!sess.slug,
2236
- fix: nudges.fix,
2237
- tidy: nudges.tidy,
2238
- ghFold: fold.state === "ok" && fold.open ? { repo: fold.slug, open: fold.open, similar: fold.result.similar.length } : undefined,
2239
- }).join("\n"),
2240
- };
2241
- }
2242
-
2243
- async function gateRoadmap(o: GateCtx): Promise<RunResult> {
2244
- const { root, sess, rest } = o;
2245
- // the backlog is advisory — no state, no gating; direct file edits stay allowed like reflections.md
2246
- const words = rest.filter((a) => !a.startsWith("--")); // gate flags are not backlog prose (#43 applies here too)
2247
- const [verb = "list", ...args] = words;
2248
- const text = readRoadmap(root);
2249
- const open = roadmapOpenCount(text);
2250
- const done = doneItemCount(text);
2251
- const save = (next: string) => writeFileSync(roadmapFile(root), next); // .dev-flow/ existence is runFlow's precondition
2252
- const idx = Number(args[0]);
2253
- const validIdx = Number.isInteger(idx) && idx >= 1 && idx <= open;
2254
- switch (verb) {
2255
- case "list": {
2256
- if (!open) return { text: done ? `roadmap: nothing open (${done} done — flow roadmap tidy drops them)` : "roadmap: empty — flow roadmap add \"<future feature>\"" };
2257
- return { text: [`roadmap — ${open} open (${done} done):`, ...openChecklistItems(text).map((l, i) => ` ${i + 1}. ${l.slice(6)}`)].join("\n") };
2258
- }
2259
- case "add": {
2260
- if (!args.length) return { text: 'usage: flow roadmap add "<future feature>" [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]', isError: true };
2261
- // a spin-off: --slug stamps it like pick (flow start finds it), the brief carries what was worked
2262
- // out in chat into the new feature's plan, and a bound session records where it was split from
2263
- const slug = flagValue(rest, "slug");
2264
- if (slug !== null && !validSlug(slug)) return { text: `--slug=${slug} is not a slug (lowercase, dashes)`, isError: true };
2265
- const briefFile = flagValue(rest, "brief-file");
2266
- if (briefFile !== null && !existsSync(path.resolve(root, briefFile))) return { text: `--brief-file=${briefFile} does not exist`, isError: true };
2267
- const brief = briefFile !== null ? readFileSync(path.resolve(root, briefFile), "utf8") : (flagValue(rest, "brief") ?? "");
2268
- const item = [args.join(" "), sess.slug && sess.slug !== slug ? `— split from ${sess.slug}` : "", slug ? `(${slug})` : ""].filter(Boolean).join(" ");
2269
- save(appendRoadmapItem(text, item, brief));
2270
- return { text: `roadmap: added — ${open + 1} open${slug ? `; stamped for ${slug}${brief.trim() ? " with a brief" : ""} — flow start ${slug} seeds its plan from it${sess.slug ? ` (after ${sess.slug} ships)` : ""}` : ""}` };
2271
- }
2272
- case "pick": {
2273
- const slug = args[1] ?? "";
2274
- if (!validIdx) return { text: `pick: open item 1–${open} required — flow roadmap lists them`, isError: true };
2275
- if (!slug || !validSlug(slug)) return { text: `usage: flow roadmap pick <n> <slug> — the slug flow start will use (lowercase, dashes)`, isError: true };
2276
- save(roadmapPick(text, idx, slug)!);
2277
- return { text: `roadmap: item ${idx} picked for ${slug} — now: flow start ${slug} (flow finish checks the item off when it ships)` };
2278
- }
2279
- case "done": {
2280
- if (!validIdx) return { text: `done: open item 1–${open} required — flow roadmap lists them`, isError: true };
2281
- // stamped with date + bound slug, so history says what shipped it
2282
- save(roadmapDone(text, idx, [new Date().toISOString().slice(0, 10), sess.slug].filter(Boolean).join(" "))!);
2283
- return { text: `roadmap: item ${idx} marked done (${open - 1} open)` };
2284
- }
2285
- case "tidy": {
2286
- if (!done) return { text: `roadmap: nothing to tidy (${open} open, 0 done)` };
2287
- save(roadmapTidy(text));
2288
- return { text: `roadmap: dropped ${done} done item(s) — ${open} open` };
2289
- }
2290
- default:
2291
- return { text: "usage: flow roadmap [list|add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy]", isError: true };
2292
- }
2293
- }
2294
-
2295
- async function gateDoctor(o: GateCtx): Promise<RunResult> {
2296
- const { root, rest } = o;
2297
- // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
2298
- const df = dfDir(root);
2299
- const loaded = loadProject(df);
2300
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
2301
- findings.push(...(await gitConsistency(root, loaded.cfg)));
2302
- const refl = readReflections(root);
2303
- const fold = await foldView(root, refl);
2304
- if (refl.length) {
2305
- findings.push(`reflection review — ${refl.length} open item(s); doctor never implements: investigate each, present the fix, the operator confirms, then the routed flow implements it:`);
2306
- // labelled from the heading each item sits under — the file is the record, re-guessing from the
2307
- // note text made doctor's table disagree with where the note was actually filed
2308
- reflectionRoutes(refl, isSelfRepo(root)).forEach((r, i) => {
2309
- const link = fold.state === "ok" ? fold.result.linked.find((l) => l.item === i) : undefined;
2310
- 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` : ""}`);
2311
- });
2312
- }
2313
- findings.push(...foldRows(fold, isSelfRepo(root)));
2314
- const reflText = readReflectionsText(root);
2315
- const unfiled = reflectUnfiledCount(reflText);
2316
- if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## code — flow reflect list shows them, flow reflect move <n> --playbook|--code files them`);
2317
- findings.push(...legacyPluginRows(reflText, isSelfRepo(root)).map((r) => ` ${r}`));
2318
- const nudges = reflectionNudges(reflText, now().slice(0, 10), { between: !o.sess.slug });
2319
- if (nudges.fix) findings.push(nudges.fix);
2320
- if (nudges.tidy) findings.push(nudges.tidy);
2321
- if (!rest.length) return { text: findings.length ? `doctor: ${findings.length} finding(s)\n${findings.map((f) => ` ${f}`).join("\n")}` : "doctor: no findings — playbook, flow state and git layout are consistent" };
2322
- // flow doctor <note>: a fresh observation gets an investigation brief and a fix route
2323
- return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
2324
- }
2325
-
2326
- /** What a gate handler needs from the runFlow preamble. */
2327
- interface GateCtx {
2328
- root: string;
2329
- ui: Ui;
2330
- sess: Session;
2331
- cfg: Config;
2332
- rest: string[];
2333
- flag: (name: string) => boolean;
2334
- slugArg?: string;
2335
- takeYoloWord: (state: FlowState) => string | null;
2336
- hooks: FlowHooks;
2337
- }
2338
-
2339
- async function gateVersion(o: GateCtx): Promise<RunResult> {
2340
- const { root, flag } = o;
2341
- // the plugin's own version — separate from the project's versioning.file version the release gates use
2342
- const { disk: self, behind } = buildSkew(root);
2343
- const head = self.version ? `dev-flow ${self.version} (pi-dev-flow at ${self.dir})` : `dev-flow version unknown — no pi-dev-flow package.json above ${self.dir}`;
2344
- // in the dev-flow repo head names the checkout, so name where the stale code actually lives
2345
- const from = SELF_BUILD.dir !== self.dir ? ` (from ${SELF_BUILD.dir})` : "";
2346
- const dupNote = copyWarning();
2347
- // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
2348
- if (flag("check-upstream")) {
2349
- const newest = await publishedVersion(root);
2350
- return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
2351
- }
2352
- return { text: `${behind ? `${head} — but this session runs ${behind}${from}; /reload to run ${self.version} \u2014 in a shared-process host (pi-web) reload cannot swap loaded code: only a host restart does` : head}${dupNote ? `\n${dupNote}` : ""}` };
2353
- }
2354
-
2355
- async function gateTest(o: GateCtx): Promise<RunResult> {
2356
- const { root, sess, cfg, slugArg } = o;
2357
- const { state, err } = needState(root, sess, slugArg);
2358
- if (err) return err;
2359
- if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
2360
- const res = await sh(cfg.commands.test, gateCwd(root, state!), undefined, featureEnv(root, state!));
2361
- state!.checks.test = { ok: res.ok, at: now() };
2362
- await stampChecks(root, state!, ["test"]);
2363
- writeState(root, state!);
2364
- return { text: `test: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.test})\n${tail(res.out)}` };
2365
- }
2366
-
2367
- async function gateCheck(o: GateCtx): Promise<RunResult> {
2368
- const { root, sess, cfg, slugArg } = o;
2369
- const { state, err } = needState(root, sess, slugArg);
2370
- if (err) return err;
2371
- // a docs flow runs no project command anywhere else — pendingChecks, verifyGate and releaseGate all skip
2372
- // it — so running tier-1 here only produced a FAIL that read like a broken deploy in a checkout that
2373
- // never built the binary (#96)
2374
- // shortcut: --docs is the operator's word, nothing checks the changeset is docs-only, so a mislabelled
2375
- // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
2376
- 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)" };
2377
- if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
2378
- const ran = await runChecks(root, state!, cfg, cfg.checkList);
2379
- return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
2380
- }
2381
-
2382
- async function gateHealth(o: GateCtx): Promise<RunResult> {
2383
- const { root, sess, cfg, slugArg } = o;
2384
- const { state, err } = needState(root, sess, slugArg);
2385
- if (err) return err;
2386
- // commands.health and a flow-check named health are the same probe (healthProbe reads both)
2387
- const probe = healthProbe(cfg);
2388
- if (!probe) return { text: "no health check configured — add `health = <command>` (or a flow-check health block) under ## implement in .dev-flow/project.md", isError: true };
2389
- const res = await probeHealth(root, state!, cfg, probe);
2390
- if ("seedFail" in res) return res.seedFail;
2391
- return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${probe}${triedNote(res.attempts)})\n${tail(res.out)}` };
2392
- }
2393
-
2394
- async function gateUse(o: GateCtx): Promise<RunResult> {
2395
- const { root, sess, slugArg } = o;
2396
- if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
2397
- const st = readState(root, slugArg);
2398
- if (!st) {
2399
- const ghost = existsSync(path.join(featDir(root, slugArg), "plan"));
2400
- return { text: ghost ? `.dev-flow/${slugArg}/ is a ghost — plan/ but no state.json, so there is nothing to resume: flow start ${slugArg} --confirmed adopts its plan as a new feature` : `no unfinished feature ${slugArg}`, isError: true };
2401
- }
2402
- const prior = readClaim(root, slugArg);
2403
- const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
2404
- sess.bind(slugArg);
2405
- sess.rename(slugArg);
2406
- // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
2407
- // must not inherit a 💬 for a question it never posed
2408
- if (st.pendingAsk) {
2409
- delete st.pendingAsk;
2410
- writeState(root, st);
2411
- }
2412
- return { text: `this session is now bound to ${slugArg} (stage ${st.stage})${st.worktree ? ` — work in its worktree: ${st.worktree} (branch ${st.branch})` : ""}; session renamed to ${slugArg}${takeover}` };
2413
- }
2414
-
2415
- async function gateAbort(o: GateCtx): Promise<RunResult> {
2416
- const { root, ui, sess, flag, slugArg } = o;
2417
- // Unbinds the session only; state and worktree stay for manual recovery.
2418
- const target = slugArg ?? sess.slug;
2419
- if (!target) return { text: "nothing bound — pass a slug", isError: true };
2420
- const st = readState(root, target);
2421
- // a live claim locks the whole feature, not only its gates: aborting it out from under the session
2422
- // that works it erases the plan that session is still writing (same rule needState applies)
2423
- const claim = readClaim(root, target);
2424
- if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (pid ${claim!.pid}) — flow use ${target} takes it over explicitly`, isError: true };
2425
- if (st && !st.worktree) {
2426
- // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
2427
- // as a ghost the doctor flags (a plan/ whose state.json is gone). A written plan is the
2428
- // operator's work too — it is not dropped without their word.
2429
- const written = listFiles(path.join(featDir(root, target), "plan"));
2430
- if (written.length && !flag("confirmed")) {
2431
- const ok = ui.hasUI && (await ui.confirm("Drop plan?", `Abort ${target}? Its plan/ (${written.join(", ")}) is deleted for good.`));
2432
- if (!ok) return { text: needsOperator(`aborting ${target} deletes its written plan (${written.join(", ")}) — ask the operator, then re-run with --confirmed`, "Drop plan?"), isError: true };
2433
- }
2434
- if (sess.slug === target) sess.bind(null);
2435
- rmSync(featDir(root, target), { recursive: true, force: true });
2436
- return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
2437
- }
2438
- if (sess.slug === target) sess.bind(null);
2439
- // the scratch dir is the bound session's working junk — it does not outlive the binding
2440
- rmSync(featureTmpDir(dfDir(root), target), { recursive: true, force: true });
2441
- if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
2442
- return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
2443
- }
2444
-
2445
-
2446
- /** Sessions spawned by flow_stage in this process: they get no [dev-flow] driver context injected
2447
- * (their brief is their whole context) — the guards still judge them like any session. */
2448
- const workerSessions = new Set<string>();
2449
-
2450
- /** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
2451
- const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"], reflect: ["read", "bash"] };
2452
-
2453
- /** Test-only timer override: the smoke suite drives the steer, the hard cut and the salvage grace in ms. */
2454
- export const workerTiming: { softMs?: number; hardMs?: number; graceMs?: number } = {};
2455
-
2456
- /** The upstream dev-flow repo's issues in every state, for the reflect brief's dedupe — prefetched so
2457
- * the worker reads a list instead of looping gh searches. null = gh could not answer (the brief then
2458
- * falls back to the search recipe). */
2459
- async function upstreamIssueList(root: string, repo: string): Promise<{ number: number; title: string; state: string }[] | null> {
2460
- if (!repo || process.env.DEV_FLOW_NO_ISSUES) return null;
2461
- const r = await sh(`gh issue list --repo ${sq(repo)} --state all --json number,title,state --limit 200`, root, 15_000);
2462
- if (!r.ok) return null;
2463
- try {
2464
- const a = JSON.parse(r.out) as { number?: unknown; title?: unknown; state?: unknown }[];
2465
- return Array.isArray(a) ? a.filter((i) => Number.isInteger(i?.number)).map((i) => ({ number: Number(i.number), title: String(i.title ?? ""), state: String(i.state ?? "") })) : null;
2466
- } catch {
2467
- return null;
2468
- }
2469
- }
2470
-
2471
- /** Seam: the smoke suite stubs the prefetch instead of calling gh against the real upstream. */
2472
- export const reflectSeams = { upstreamIssues: upstreamIssueList };
2473
-
2474
- /** Build the reflect worker's transcript digests in the feature's scratch dir (driver first). A
2475
- * transcript that cannot be read is skipped — the brief still names the raw file. */
2476
- function writeTranscriptDigests(root: string, slug: string, files: string[]): { transcript: string; digest: string }[] {
2477
- const dir = path.join(featureTmpDir(dfDir(root), slug), "reflect");
2478
- const out: { transcript: string; digest: string }[] = [];
2479
- for (const f of files) {
2480
- try {
2481
- mkdirSync(dir, { recursive: true });
2482
- const digest = path.join(dir, `${path.basename(f, ".jsonl")}.digest.txt`);
2483
- writeFileSync(digest, digestTranscript(readFileSync(f, "utf8")));
2484
- out.push({ transcript: f, digest });
2485
- } catch { /* unreadable transcript: the raw path stays in the brief */ }
2486
- }
2487
- return out;
2488
- }
2489
-
2490
- /** Line 1 of every pi session file in `dir` — the header that names a worker's parent session. A
2491
- * file is read up to its first newline only (transcripts grow large); unreadable files are skipped. */
2492
- function sessionHeaders(dir: string | undefined): SessionHeaderInfo[] {
2493
- if (!dir) return [];
2494
- let names: string[];
2495
- try { names = readdirSync(dir).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
2496
- const out: SessionHeaderInfo[] = [];
2497
- for (const n of names) {
2498
- const file = path.join(dir, n);
2499
- try {
2500
- const fd = openSync(file, "r");
2501
- try {
2502
- const buf = Buffer.alloc(16_384);
2503
- const len = readSync(fd, buf, 0, buf.length, 0);
2504
- const first = buf.subarray(0, len).toString("utf8").split("\n")[0];
2505
- const h = JSON.parse(first) as { type?: unknown; parentSession?: unknown };
2506
- if (h?.type === "session") out.push({ file, parentSession: typeof h.parentSession === "string" ? h.parentSession : undefined });
2507
- } finally { closeSync(fd); }
2508
- } catch { /* not a session file, or a header past the read window: skip */ }
2509
- }
2510
- return out;
2511
- }
2512
-
2513
- /** What makes a worker show up in pi-web's Agents menu: pi-web classifies a subagent from the
2514
- * custom entries its own runtime writes into the child's session file (pi-web lib/subagents.ts
2515
- * readSubagentRun, fed by lib/session-reader.ts). Two placement rules the reader enforces:
2516
- * the meta entry must be the file's FIRST data entry (the scanner reads header + one line and
2517
- * calls anything else a fork), and a persisted `running` the host cannot prove live displays as
2518
- * `interrupted` — so while a worker runs it also claims a slot in pi-web's live run map
2519
- * (piwebLiveClaim), and the final result entry settles the row after.
2520
- * Unknown entry types are inert in plain pi, so stamping is unconditional. */
2521
- const PIWEB_SUBAGENT = { meta: "pi-web:subagent", status: "pi-web:subagent-status", result: "pi-web:subagent-result" } as const;
2522
-
2523
- interface WorkerSubagentMeta {
2524
- parentId: string;
2525
- parentFile: string;
2526
- toolCallId: string;
2527
- profile: string;
2528
- description: string;
2529
- task: string;
2530
- }
2531
-
2532
- /** Only version 1 + the two lineage strings are hard-validated by pi-web's reader; the rest is
2533
- * display. resourceSnapshot is deliberately absent: its presence pins the tool set strictly when
2534
- * pi-web reopens the child, and these workers are never resumed by pi-web. */
2535
- function piwebWorkerMeta(m: WorkerSubagentMeta): Record<string, unknown> {
2536
- return {
2537
- version: 1,
2538
- parentSessionId: m.parentId,
2539
- parentSessionPath: m.parentFile,
2540
- parentToolCallId: m.toolCallId,
2541
- profile: m.profile,
2542
- description: m.description,
2543
- task: m.task,
2544
- runInBackground: false,
2545
- createdAt: now(),
2546
- };
2547
- }
2548
-
2549
- /** Best-effort by contract: a stamp that will not write must never break the worker run —
2550
- * visibility, not function (same rule as the worker's setSessionName renames). */
2551
- function piwebStamp(target: { appendCustomEntry?(customType: string, data?: unknown): unknown } | undefined, customType: string, data: unknown): void {
2552
- try { target?.appendCustomEntry?.(customType, data); } catch { /* visibility only */ }
2553
- }
2554
-
2555
- /** pi-web proves a subagent live only from its own in-process tables (rpc-manager.ts
2556
- * subagentDisplayStatus: its session registry, or globalThis.__piSubagentRuns); anything else with
2557
- * a persisted `running` reads `interrupted`. pi-web hosts extensions in its server process, so the
2558
- * worker claims a slot in that map for the run — pi-web's private global, used only when pi-web
2559
- * created it (never created here: plain pi stays untouched, and a pi-web without it keeps the old
2560
- * mid-run `interrupted`). Side effects: the driver counts as having an unsettled subagent while the
2561
- * tool call runs (it is mid-call anyway); Stop/steer from the Agents menu still answer "not running",
2562
- * since pi-web holds no wrapper for this child — the driver's Stop aborts it. Returns an idempotent
2563
- * release that drops the slot only if it still holds this claim (pi-web's dropSubagentRun rule). */
2564
- function piwebLiveClaim(sm: { getSessionId?(): string; getSessionFile?(): string | undefined } | undefined, m: WorkerSubagentMeta): (status: string) => void {
2565
- try {
2566
- const runs = (globalThis as { __piSubagentRuns?: unknown }).__piSubagentRuns;
2567
- const sessionId = sm?.getSessionId?.();
2568
- if (!(runs instanceof Map) || !sessionId) return () => {};
2569
- let settle: (run: unknown) => void = () => {};
2570
- const run = { sessionId, sessionPath: sm?.getSessionFile?.() ?? "", parentSessionId: m.parentId, parentToolCallId: m.toolCallId, profile: m.profile, description: m.description, task: m.task, runInBackground: false, status: "running", createdAt: now() };
2571
- const stored = { run, completion: new Promise((resolve) => { settle = resolve; }), abortRequested: false, dispatchedAt: Date.now() };
2572
- runs.set(sessionId, stored);
2573
- let released = false;
2574
- return (status) => {
2575
- if (released) return;
2576
- released = true;
2577
- try { if (runs.get(sessionId) === stored) runs.delete(sessionId); settle({ ...run, status, completedAt: now() }); } catch { /* visibility only */ }
2578
- };
2579
- } catch { return () => {}; }
2580
- }
2581
-
2582
- /** The worker's display name — the Agents row and the session name: `<glyph> <slug> <what>`. The
2583
- * model's label often repeats the slug ("flow-list-widget review"), so the slug and stray separators
2584
- * are cut from it; with nothing left the op names the run. */
2585
- function workerName(glyph: string, slug: string, op: string, label: unknown): string {
2586
- const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2587
- const what = String(label ?? "").replace(/[\r\n]+/g, " ").replace(new RegExp(esc, "gi"), " ")
2588
- .replace(/^[\s·:|/,-]+|[\s·:|/,-]+$/g, "").replace(/\s{2,}/g, " ").slice(0, 40).trim();
2589
- return `${glyph} ${slug} ${what || op}`;
2590
- }
2591
-
2592
- /** Seam that spawns a worker as a real pi session — tests replace `.run`. With the driver's session
2593
- * file and directory known, the worker's header links back to the driver (`parentSession`), so pi's
2594
- * picker nests it under the driver, and the pi-web meta lands as the file's first data entry. */
2595
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string; subagent?: WorkerSubagentMeta }) => Promise<AgentSession> } = {
2596
- run: async ({ work, model, name, tools, parent, dir, subagent }) => {
2597
- const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
2598
- await loader.reload();
2599
- const sessionManager = parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
2600
- // The meta must be stamped here — before createAgentSession appends model_change/session_info,
2601
- // because pi-web's scanner classifies the child only from the first data entry after the header.
2602
- if (sessionManager && subagent) piwebStamp(sessionManager, PIWEB_SUBAGENT.meta, piwebWorkerMeta(subagent));
2603
- const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
2604
- try { workerSessions.add(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the default context */ }
2605
- try { session.setSessionName(name); } catch { /* naming is visibility, not function */ }
2606
- return session;
2607
- },
2608
- };
2609
-
2610
- /** Per-cwd cache of the main checkout a linked worktree belongs to (null = not a linked worktree) —
2611
- * every hook resolves its root through flowRoot, so git is asked once per directory. */
2612
- const mainCheckoutCache = new Map<string, string | null>();
2613
-
2614
- /** The root whose .dev-flow/ is the flow truth for a session cwd. A feature worktree is a linked git
2615
- * worktree whose tracked .dev-flow/ holds only project.md — state, claims and plans live in the main
2616
- * checkout. Judging a session by its own cwd found no features and every guard answered "no active
2617
- * flow". So a linked worktree resolves to its main checkout when that checkout is initiated. */
2618
- async function flowRoot(cwd: string): Promise<string> {
2619
- if (!mainCheckoutCache.has(cwd)) {
2620
- const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", cwd);
2621
- const [gitDir, common] = r.ok ? r.out.split("\n").map((l) => l.trim()) : [];
2622
- const linked = !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
2623
- mainCheckoutCache.set(cwd, linked ? mainCheckoutRoot(cwd, common) : null);
2624
- }
2625
- const main = mainCheckoutCache.get(cwd);
2626
- return main && initiated(main) ? main : cwd;
2627
- }
2628
-
2629
- async function currentBranch(root: string): Promise<string> {
2630
- const r = await sh("git branch --show-current", root);
2631
- return r.ok ? r.out.split("\n")[0] : "";
2632
- }
2633
-
2634
- function needState(root: string, sess: Session, slugArg?: string): { state: FlowState | null; err?: RunResult } {
2635
- // no implicit feature: gates run on this session's binding or an explicit slug — never on "the one
2636
- // feature left", which is how an unbound session would end up steering a flow it never took
2637
- const slug = slugArg ?? sess.slug;
2638
- if (!slug) {
2639
- const un = unfinishedStates(root);
2640
- if (!un.length) return { state: null, err: { text: "no unfinished features — flow start <slug> [--ui]", isError: true } };
2641
- return { state: null, err: { text: `nothing bound — flow use <slug> or pass an explicit slug (unfinished: ${un.map((s) => s.slug).join(", ")})`, isError: true } };
2642
- }
2643
- const state = readState(root, slug);
2644
- if (!state) return { state: null, err: { text: `no state for feature ${slug}`, isError: true } };
2645
- // passing a slug is not a takeover: a live session that holds the claim drives its gates, or the two
2646
- // sessions overwrite one state file (last write wins) while both believe they own the stage.
2647
- const claim = readClaim(root, slug);
2648
- if (sess.slug !== slug && claimBlocks(claim, sess.key))
2649
- return { state: null, err: { text: `${slug} is claimed by another live session (pid ${claim!.pid}) — flow use ${slug} takes it over explicitly`, isError: true } };
2650
- return { state };
2651
- }
2652
-
2653
- function tail(out: string, n = 15): string {
2654
- const lines = out.split("\n").filter(Boolean);
2655
- return lines.length > n ? `…(${lines.length - n} lines)…\n${lines.slice(-n).join("\n")}` : out;
2656
- }
2657
-
2658
- // ------------------------------------------------------------------ extension
2659
-
2660
- /** The pi-web chip's current key, per session: the chip's label IS the widget key, so it changes with the
2661
- * footer text and the previous one must be cleared on every repaint. Per session, not per process — one
2662
- * pi-web server repaints many sessions (drivers, chats, workers), and a single shared slot let session B's
2663
- * repaint overwrite A's key, so A's next repaint cleared a key A never had and left its old chip beside
2664
- * the new one. On globalThis so a /reload or a duplicate copy still knows the chip already painted. */
2665
- const WEB_CHIP_KEYS: Map<string, string> = ((globalThis as { __piDevFlowChipKeys?: Map<string, string> }).__piDevFlowChipKeys ??= new Map());
43
+ export const testSeams = { ...baseSeams, piweb: { meta: piwebWorkerMeta, stamp: piwebStamp, liveClaim: piwebLiveClaim, workerName } };
2666
44
 
2667
45
  /** Compact footer: bound flow = stage glyph, slug, mode markers, ⚠️ on its failing checks; unbound = the
2668
46
  * unfinished-flow count, or `💬 no flows` — an initiated repo always carries the footer. An uninitiated
@@ -2708,6 +86,14 @@ async function askOperator(ctx: ExtensionContext, what: string, why: string): Pr
2708
86
  return ok ? null : `operator declined — ${why}`;
2709
87
  }
2710
88
 
89
+ /** What a kill by dev-flow's own timeout tells the agent (and the operator reading the transcript). */
90
+ export function timeoutKillNote(armed: { s: number; cls: string }): string {
91
+ const why = armed.cls.startsWith("its own timeout")
92
+ ? `the command's ${armed.cls.replace(/^its own /, "")} plus a 15s margin — it outlived its own timer`
93
+ : `dev-flow's default for ${armed.cls} commands, armed because the call stated no timeout`;
94
+ return `[dev-flow] stopped at ${armed.s}s: ${why}. If it needs longer, rerun with an explicit timeout (seconds) on the call.`;
95
+ }
96
+
2711
97
  export default function devFlow(pi: ExtensionAPI) {
2712
98
  registerCopy(); // which copy of dev-flow this is — see COPIES
2713
99
  /** Parse "flow <sub> [slug] [--flags]" args shared by command and tool. */
@@ -2763,6 +149,7 @@ export default function devFlow(pi: ExtensionAPI) {
2763
149
  }
2764
150
  const key = sessionKey(ctx);
2765
151
  bindings.set(key, slug);
152
+ lastContext.delete(key); // a restored branch may not hold the last note — hand the next run the full one
2766
153
  // The branch is the truth about what the restored context holds: a marker means the core is in it
2767
154
  // (do not pay twice), no marker means the branch was rewound or forked past the injection (give it
2768
155
  // back), and a stale marker means a compaction summarized it away before the reload (give it back).
@@ -2799,7 +186,11 @@ export default function devFlow(pi: ExtensionAPI) {
2799
186
  // gate output belongs to the conversation, not a toast: display:true renders a [flow] box (TUI + web), no triggerTurn so no model turn fires.
2800
187
  // bare reflect is the exception: its whole output is instructions for the agent — displayed without a turn, they would never execute.
2801
188
  const wake = cmd.length === 1 && cmd[0] === "reflect";
2802
- pi.sendMessage({ customType: "flow", content: res.text, display: true }, wake ? { triggerTurn: true } : undefined);
189
+ // the operator typed a command, so the full text (commands included) is theirs to read; the header and
190
+ // stage line give it the same shape as an agent-run gate
191
+ const { view } = await presentRun(cmd, root, sessionKey(ctx), res);
192
+ const shown = [`**${viewHeader(view)}**`, ...(view.stageLine ? [view.stageLine] : []), "", res.text.split("\n").map((l) => (l.startsWith(AGENT_MARK) ? l.slice(AGENT_MARK.length) : l)).join("\n")].join("\n");
193
+ pi.sendMessage({ customType: "flow", content: wake ? res.text : shown, display: true }, wake ? { triggerTurn: true } : undefined);
2803
194
  refreshStatus(ctx, root);
2804
195
  if (!res.isError) maybeCompactNow(ctx, root);
2805
196
  },
@@ -2820,7 +211,28 @@ export default function devFlow(pi: ExtensionAPI) {
2820
211
  // chat word to ask instead; the /flow slash command (a human at the keyboard) keeps its dialogs.
2821
212
  const res = await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
2822
213
  if (!res.isError) maybeCompactNow(ctx, root);
2823
- return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
214
+ // two readers: the model gets every instruction, the operator's row renders the view (renderResult) —
215
+ // facts, the stage line and the question waiting on them, never a command to type
216
+ // a refusal (not a question for the operator) is friction the closing reflection should look at
217
+ if (res.isError && !res.text.startsWith(NEEDS_OPERATOR) && initiated(root)) noteFriction(root, sessionKey(ctx));
218
+ const { agent, view } = await presentRun(params.args, root, sessionKey(ctx), res);
219
+ return { content: [{ type: "text", text: agent }], details: { view }, isError: res.isError };
220
+ },
221
+ renderResult: (result, options, theme) => {
222
+ const view = (result.details as { view?: GateView } | undefined)?.view;
223
+ if (!view) {
224
+ const t = result.content[0];
225
+ return new Text(t?.type === "text" ? t.text : "", 0, 0);
226
+ }
227
+ const color = view.ask ? "warning" : view.ok ? "success" : "error";
228
+ const out = [theme.fg(color, theme.bold(viewHeader(view)))];
229
+ if (view.stageLine) out.push(theme.fg("muted", view.stageLine.replace(/\*\*/g, "").replace(/`/g, "")));
230
+ const body = options.expanded ? view.lines : view.lines.slice(0, 12);
231
+ if (body.length) out.push(...body.map((l) => theme.fg("text", l)));
232
+ if (!options.expanded && view.lines.length > body.length) out.push(theme.fg("dim", `… ${view.lines.length - body.length} more line(s)`));
233
+ if (view.ask) out.push(theme.fg("warning", askLine(view.ask).replace(/\*\*/g, "")));
234
+ if (options.expanded && view.agent.length) out.push(...view.agent.map((l) => theme.fg("dim", `agent: ${l}`)));
235
+ return new Text(out.join("\n"), 0, 0);
2824
236
  },
2825
237
  });
2826
238
  pi.registerTool(flowTool);
@@ -3101,12 +513,13 @@ export default function devFlow(pi: ExtensionAPI) {
3101
513
  if (!existsSync(dfDir(root))) return;
3102
514
  releaseSession(root, sessionKey(ctx));
3103
515
  });
3104
- pi.on("turn_end", async (_event, ctx) => {
516
+ pi.on("turn_end", async (event, ctx) => {
3105
517
  if (!guardsAreMine()) return;
3106
518
  const root = await flowRoot(ctx.cwd);
3107
519
  refreshStatus(ctx, root);
3108
520
  // pi checks its compaction threshold between every turn; our safe points must be as frequent.
3109
521
  maybeCompactNow(ctx, root);
522
+ return commandAskCorrection(event, ctx, root);
3110
523
  });
3111
524
  // Idle backstop: long between-gate runs compact here instead of letting pi hit the threshold mid-work.
3112
525
  pi.on("agent_settled", async (_event, ctx) => {
@@ -3153,6 +566,7 @@ export default function devFlow(pi: ExtensionAPI) {
3153
566
  if (!guardsAreMine()) return;
3154
567
  if (!initiated(await flowRoot(ctx.cwd))) return;
3155
568
  coreStale.add(sessionKey(ctx));
569
+ lastContext.delete(sessionKey(ctx));
3156
570
  pi.appendEntry("dev-flow-skill", { core: true, stale: true });
3157
571
  });
3158
572
 
@@ -3161,6 +575,8 @@ export default function devFlow(pi: ExtensionAPI) {
3161
575
  // them. Prefixed only after the verdict, so no guard ever judges the prefix.
3162
576
  pi.on("tool_call", async (event, ctx) => {
3163
577
  const verdict = await guardToolCall(event, ctx);
578
+ // a guard block is friction the closing reflection should look at
579
+ if (verdict?.block && guardsAreMine() && initiated(ctx.cwd)) noteFriction(await flowRoot(ctx.cwd), sessionKey(ctx));
3164
580
  if (verdict || !isToolCallEventType("bash", event) || !guardsAreMine() || !initiated(ctx.cwd)) return verdict;
3165
581
  const root = await flowRoot(ctx.cwd);
3166
582
  const bound = boundFeature(root, sessionKey(ctx));
@@ -3171,6 +587,26 @@ export default function devFlow(pi: ExtensionAPI) {
3171
587
  return undefined;
3172
588
  });
3173
589
 
590
+ // A kill by dev-flow's silent default must say so: the transcript shows the call without a timeout, so
591
+ // "Command timed out after 30 seconds" otherwise reads like pi misbehaving, and the agent cannot tell a
592
+ // policy cap from a hang. Keyed by tool call id; a call blocked before it ran never reports, so the map
593
+ // is bounded rather than trusted to drain.
594
+ const armedTimeouts = new Map<string, { s: number; cls: string }>();
595
+ const rememberArmed = (id: string, v: { s: number; cls: string }) => {
596
+ armedTimeouts.set(id, v);
597
+ if (armedTimeouts.size > 500) armedTimeouts.delete(armedTimeouts.keys().next().value as string);
598
+ };
599
+ pi.on("tool_result", async (event) => {
600
+ const armed = armedTimeouts.get(event.toolCallId);
601
+ if (!armed) return undefined;
602
+ armedTimeouts.delete(event.toolCallId);
603
+ if (!event.isError) return undefined;
604
+ const text = event.content.map((c) => (c.type === "text" ? c.text : "")).join("");
605
+ const m = text.match(/timed out after (\d+) seconds/);
606
+ if (!m || Number(m[1]) !== armed.s) return undefined;
607
+ return { content: [...event.content, { type: "text" as const, text: `\n${timeoutKillNote(armed)}` }] };
608
+ });
609
+
3174
610
  async function guardToolCall(event: ToolCallEvent, ctx: ExtensionContext): Promise<ToolCallEventResult | undefined> {
3175
611
  if (!guardsAreMine()) return undefined; // election: only the newest loaded copy judges
3176
612
  // pi kills a shell call only when a timeout was passed, and the model omits it in ~75% of
@@ -3182,7 +618,14 @@ export default function devFlow(pi: ExtensionAPI) {
3182
618
  const noDf = !initiated(ctx.cwd);
3183
619
  // in an initiated repo the silent default stays armed either way: it is the safety net for an
3184
620
  // `inject` project and the number the refusal quotes; an uninitiated folder is not touched at all
3185
- if (shellCmd && shellInput && !noDf) shellInput.timeout = bashTimeout(shellCmd, explicitTimeout);
621
+ if (shellCmd && shellInput && !noDf) {
622
+ // the e2e test shortens only the silent default — an explicit timeout is never touched
623
+ const cls = explicitTimeout === undefined && testSeams.bashTimeout.cap !== undefined ? { ...timeoutClass(shellCmd), s: testSeams.bashTimeout.cap } : timeoutClass(shellCmd);
624
+ shellInput.timeout = explicitTimeout === undefined ? cls.s : bashTimeout(shellCmd, explicitTimeout);
625
+ // the armed value never reaches the transcript (the call records what the model wrote), so a kill
626
+ // by it would read as a mystery hang — remember it, and the tool_result hook names it on a kill
627
+ if (explicitTimeout === undefined) rememberArmed(event.toolCallId, cls);
628
+ }
3186
629
  // an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
3187
630
  // the guards, the no-playbook bash-timeout default included
3188
631
  if (noDf) return undefined;
@@ -3305,6 +748,32 @@ export default function devFlow(pi: ExtensionAPI) {
3305
748
  return undefined;
3306
749
  }
3307
750
 
751
+ /** The model's final answer handed the operator a dev-flow command to type: the operator answers in
752
+ * words, so the next run carries a hidden correction. It never re-runs the turn (no continue) — the
753
+ * answer already reached the operator; the point is that the next one does not repeat it. */
754
+ const commandAskCorrection = (event: TurnEndEvent, ctx: ExtensionContext, root: string): TurnEndEventResult | undefined => {
755
+ const e = event as { outcome?: string; toolResults?: unknown[]; message?: { role?: string; content?: unknown }; entries?: unknown[] };
756
+ if (!initiated(root) || e.outcome !== "completed" || (e.toolResults?.length ?? 0) > 0 || e.message?.role !== "assistant") return undefined;
757
+ try {
758
+ if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined;
759
+ } catch {
760
+ /* not a worker */
761
+ }
762
+ const parts = Array.isArray(e.message.content) ? (e.message.content as { type?: string; text?: string }[]) : [];
763
+ const text = parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n");
764
+ const hits = operatorCommandAsks(text);
765
+ if (!hits.length) return undefined;
766
+ // SAFETY: a custom_message draft is one of the documented boundary entry types; the draft union is not re-exported
767
+ return { entries: [...event.entries, { type: "custom_message", customType: "dev-flow-correction", content: operatorCommandCorrection(hits), display: false } as unknown as TurnEndEvent["entries"][number]] };
768
+ };
769
+
770
+ /** The full note when it changed (or the core was just re-sent), else the one-line reminder. */
771
+ const sameAsLast = (key: string, full: string, short: string): string => {
772
+ if (lastContext.get(key) === full) return short;
773
+ lastContext.set(key, full);
774
+ return full;
775
+ };
776
+
3308
777
  pi.on("before_agent_start", async (_event, ctx) => {
3309
778
  if (!guardsAreMine()) return undefined;
3310
779
  // One [dev-flow] line per run, whatever number of copies of this package are installed. The same
@@ -3342,7 +811,7 @@ export default function devFlow(pi: ExtensionAPI) {
3342
811
  const rmap0 = roadmapOpenCount(readRoadmap(root));
3343
812
  if (rmap0) content += ` Also: ${rmap0} roadmap item(s) open — flow roadmap lists them, flow roadmap pick <n> <slug> hands one to flow start.`;
3344
813
  content += ` Also: the playbook map is ${path.join(SKILL_DIR, "SKILL.md")} — per-stage detail sits in references/ beside it (start: flow init, modes, ownership).`;
3345
- return { message: { customType: "dev-flow-context", display: false, content: `${core}${content}` } };
814
+ return { message: { customType: "dev-flow-context", display: false, content: `${core}${sameAsLast(key, content, `[dev-flow] no flow bound — unchanged since the last [dev-flow] note (playbook map is ${path.join(SKILL_DIR, "SKILL.md")}).`)}` } };
3346
815
  }
3347
816
  const guidance: string[] = [];
3348
817
  if (state.yolo) guidance.push("YOLO mode: the operator pre-confirmed every gate question from here on (Verified?/Release?/Finish?) — run the remaining gates (verify → release → release-done → finish) back to back without stopping to ask; guidance the operator attached to the yolo word (e.g. patch bump, no tag) is a binding directive for the chain; checks and guardrails stay fully enforced.");
@@ -3352,7 +821,7 @@ export default function devFlow(pi: ExtensionAPI) {
3352
821
  if (ref) guidance.push(`Stage playbook: read ${path.join(SKILL_DIR, ref)} before gate work in this stage.`);
3353
822
  const prose = stageGuidance(cfg, state.stage);
3354
823
  if (prose) guidance.push(`Stage guidance (${prose.source}): ${prose.text}`);
3355
- guidance.push("Stage reports: open every report with the stage line (statusbar glyph + slug + provenance-marked decision fields); close a checkpoint with an event title and `Done:` / `Next steps:` on own lines — italic verbs, recommended first, yolo last. See Stage reports in the ground rules.");
824
+ guidance.push("Stage reports: open with the stage line the last gate returned, pasted as is; a checkpoint closes with `Done:` / `Next steps:` (see the ground rules).");
3356
825
  const pend = checklistPending(cfg, state, state.stage);
3357
826
  if (pend) guidance.push(`Tier-2 checklist NOT yet confirmed (${pend} item(s)): ${applicableItems(cfg, state, state.stage).map((i) => i.text).join(" | ")}${state.stage === "release" ? " — release-stage items close with the operator's Finish? answer; no earlier gate records them" : ""}`);
3358
827
  // mid-feature is the wrong moment to divert into old reflections — they surface at the release
@@ -3363,14 +832,10 @@ export default function devFlow(pi: ExtensionAPI) {
3363
832
  }
3364
833
  const rmap = roadmapOpenCount(readRoadmap(root));
3365
834
  if (rmap) guidance.push(`◇ ${rmap} roadmap item(s) open — flow roadmap lists them (pick only on the operator's word).`);
3366
- return {
3367
- message: {
3368
- customType: "dev-flow-context",
3369
- display: false,
3370
- content: `${core}[dev-flow] this session is bound to: ${state.slug}${state.patch ? " (patch)" : state.docs ? " (docs)" : ""} — stage: ${state.stage}${state.ui ? " (UI)" : ""}${state.worktree ? `, worktree: ${state.worktree} (branch ${state.branch})` : ""}.
835
+ const stageNote = `[dev-flow] this session is bound to: ${state.slug}${state.patch ? " (patch)" : state.docs ? " (docs)" : ""} — stage: ${state.stage}${state.ui ? " (UI)" : ""}${state.worktree ? `, worktree: ${state.worktree} (branch ${state.branch})` : ""}.
3371
836
  Next: ${nextHint(state, cfg)}.
3372
- ${guidance.length ? guidance.join("\n") + "\n" : ""}Rules: follow the dev-flow skill playbook; gates run through the flow tool only — \`flow\` is not a shell command, and the operator answers words in chat, never commands: you run the gate. \`/flow\` is the operator's manual override, not yours. Stage guards block out-of-stage edits and main-branch git ops — do not work around them.`,
3373
- },
3374
- };
837
+ ${guidance.length ? guidance.join("\n") + "\n" : ""}Rules: gates run through the flow tool only; the operator answers words in chat — never ask them to type a flow command.`;
838
+ const short = `[dev-flow] still bound to ${state.slug} at ${state.stage} — unchanged since the last [dev-flow] note; follow it.`;
839
+ return { message: { customType: "dev-flow-context", display: false, content: `${core}${sameAsLast(key, stageNote, short)}` } };
3375
840
  });
3376
841
  }