pi-dev-flow 0.73.0 → 0.75.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.
@@ -40,13 +40,11 @@ import {
40
40
  pickReleaseNotes,
41
41
  checklistHash,
42
42
  checklistPending,
43
- checkoutTarget,
43
+ checkoutInvocation,
44
44
  claimBlocks,
45
45
  classifyMergeHistory,
46
46
  cmpVersions,
47
- cleanupAssess,
48
- closedReflectionCount,
49
- compactionReflectionLine,
47
+ doneItemCount,
50
48
  detectForge,
51
49
  extractSkillCore,
52
50
  featureBranchPrefix,
@@ -92,11 +90,9 @@ import {
92
90
  newState,
93
91
  nextHint,
94
92
  openChecklistItems,
95
- openReflections,
96
93
  releaseGate,
97
94
  parseVersion,
98
95
  roadmapDone,
99
- roadmapDoneCount,
100
96
  roadmapDoneForSlug,
101
97
  roadmapOpenCount,
102
98
  roadmapPick,
@@ -123,7 +119,6 @@ import {
123
119
  WORKER_NUDGES,
124
120
  type WorkerOp,
125
121
  releaseOrderInvocation,
126
- branchCreateTarget,
127
122
  type BranchState,
128
123
  type Config,
129
124
  type FeatureRef,
@@ -161,6 +156,14 @@ function checkoutBuild(root: string): { version: string | null; dir: string; rep
161
156
  : { ...SELF_BUILD, label: "the dev-flow install" };
162
157
  }
163
158
 
159
+ /** The build this session runs vs the one the disk ships: `behind` is the loaded version when they differ
160
+ * ("" when current or unknown), `line` the one warning every surface prints for it. */
161
+ function buildSkew(root: string): { disk: ReturnType<typeof checkoutBuild>; behind: string; line: string } {
162
+ const disk = checkoutBuild(root);
163
+ const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
164
+ 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` : "" };
165
+ }
166
+
164
167
  /** Cross-copy registry: one process can register dev-flow more than once (the documented
165
168
  * two-sources-at-once hazard: a project dogfood pointer plus an installed copy), and EVERY copy
166
169
  * evaluates every guard hook. The flow-tool binding belongs to whichever copy served the call,
@@ -203,13 +206,11 @@ function copyWarning(): string | null {
203
206
  }
204
207
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
205
208
  * entries and asserts the warnings the real duplicate would print. */
206
- export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined } };
209
+ export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined }, piweb: { meta: piwebWorkerMeta, stamp: piwebStamp } };
207
210
 
208
211
  interface Ui {
209
212
  hasUI: boolean;
210
213
  confirm: (title: string, message: string) => Promise<boolean>;
211
- /** Multi-line review/edit dialog where the client has one (TUI); undefined elsewhere. */
212
- editor?: (title: string, prefill?: string) => Promise<string | undefined>;
213
214
  }
214
215
 
215
216
  const now = () => new Date().toISOString();
@@ -226,6 +227,27 @@ async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000): Promis
226
227
  }
227
228
  }
228
229
 
230
+ /** origin's URL, or null when the repo has no origin. */
231
+ async function originUrl(root: string): Promise<string | null> {
232
+ const r = await sh("git remote get-url origin", root, 10_000);
233
+ return r.ok && r.out.trim() ? r.out.trim() : null;
234
+ }
235
+
236
+ /** The forge the release machinery targets: the playbook's `forge`, else detected from origin ("self" without one). */
237
+ const forgeOf = (cfg: Config, origin: string | null): string => cfg.forge || detectForge(origin ?? "");
238
+
239
+ /** The branch's merge base with the default branch (origin's when fetched), or "" when git cannot say. */
240
+ async function mergeBase(cwd: string, defaultBranch: string): Promise<string> {
241
+ 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);
242
+ return mb.ok ? mb.out.trim() : "";
243
+ }
244
+
245
+ /** The published pi-dev-flow version (`--check-upstream`), or "" when the registry cannot be asked. */
246
+ async function publishedVersion(root: string): Promise<string> {
247
+ const pub = await sh("npm view pi-dev-flow version", root);
248
+ return pub.ok ? (pub.out.trim().split("\n").pop() ?? "") : "";
249
+ }
250
+
229
251
  const dfDir = (root: string) => path.join(root, ".dev-flow");
230
252
  /** dev-flow is initiated once the operator playbook exists: before flow init writes project.md the
231
253
  * extension is silent in that folder — no injections, no guards (not even the no-playbook bash-timeout
@@ -327,14 +349,14 @@ async function runHealthProbe(cmd: string, cwd: string, waitSec: number): Promis
327
349
  * decide what is already tagged (#52). Local tags only when there is no remote to ask; null when an
328
350
  * origin exists but could not be asked (offline, no ssh agent) — then local tags must not stand in. */
329
351
  async function releaseTags(root: string): Promise<string[] | null> {
330
- if (!(await sh("git remote get-url origin", root)).ok) return (await sh("git tag --sort=-creatordate", root)).out.split("\n").filter(Boolean);
352
+ if (!(await originUrl(root))) return (await sh("git tag --sort=-creatordate", root)).out.split("\n").filter(Boolean);
331
353
  const remote = await sh("git ls-remote --tags origin", root);
332
354
  if (!remote.ok) return null;
333
355
  return parseLsRemoteTags(remote.out);
334
356
  }
335
357
 
336
358
  const GATE_HELP =
337
- "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|list|tidy|move <n> --plugin|--playbook] | roadmap [add <text>|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] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — start preflights the playbook before creating anything: it prints playbook gaps and warns when the session runs an older dev-flow build than the disk ships (in the dev-flow repo, an older build than this checkout's own manifest), and it refuses until a merge policy is set (ask the operator squash / merge / rebase / any in chat, then re-run with --merge=<style> --confirmed — the answer is written into project.md and enforced from then on: gh/glab merges that contradict it are blocked, and release-done proves what actually landed); version prints the build the disk says to run (this checkout's own manifest in the dev-flow repo, the installed package's elsewhere) and names any other dev-flow copies registered in the same process (--check-upstream also asks the registry for the published one) — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there; --plugin / --playbook / --both state the section instead of leaving it to the wording, and the echo prints why the note landed where it did); reflect list numbers the open items with their section; reflect move <n> --plugin|--playbook re-files one of them; reflect tidy drops the closed (`- [x]`) items from reflections.md — every surface that queues or reviews reflections nudges when the checked-off pile grows; bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --ui/--patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned); when the session runs an older dev-flow build than the checkout, release names both builds, lists what the running code can no longer prove, and asks the operator update (/reload) or proceed with the old release — an operator decision recorded in state and repeated by release-done, never a block";
359
+ "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|list|tidy|move <n> --plugin|--playbook] | roadmap [add <text>|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] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --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 — 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 suggestion in reflections.md (--plugin/--playbook/--both state the section); bare reflect prints the session-reflection protocol; list numbers open items, move <n> re-files one, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — 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)";
338
360
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
339
361
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
340
362
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -379,9 +401,8 @@ const compacting = new Set<string>();
379
401
  const coreInjected = new Set<string>();
380
402
  /** Sessions whose last compaction dropped the core out of context — the next run pays it once more. */
381
403
  const coreStale = new Set<string>();
382
- /** The skill dir of THIS loaded copy. Since 0.57.1 dropped the `.pi/extensions` dogfood shim, the
383
- * copy a session runs and a development checkout are different installs, so playbook paths
384
- * resolve from the code actually loaded — never from cwd. */
404
+ /** The skill dir of THIS loaded copy: the copy a session runs and a development checkout can be
405
+ * different installs, so playbook paths resolve from the code actually loaded — never from cwd. */
385
406
  const SKILL_DIR = path.join(import.meta.dirname, "..", "skills", "dev-flow");
386
407
  let skillCoreCache: string | null | undefined;
387
408
  /** The core block between SKILL.md's markers, read once per process (/reload reloads the module
@@ -406,12 +427,13 @@ export const compactionTakeover: { run: typeof compact } = { run: compact };
406
427
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
407
428
  const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
408
429
 
430
+ /** Every feature with a state file — finish deletes the state, so whatever is on disk is unfinished. */
409
431
  function unfinishedStates(root: string): FlowState[] {
410
432
  if (!existsSync(dfDir(root))) return [];
411
433
  return readdirSync(dfDir(root), { withFileTypes: true })
412
434
  .filter((d) => d.isDirectory())
413
435
  .map((d) => readState(root, d.name))
414
- .filter((s): s is FlowState => !!s && s.stage !== "done");
436
+ .filter((s): s is FlowState => !!s);
415
437
  }
416
438
 
417
439
  /** Open items of the agent's suggestion queue (.dev-flow/reflections.md), each with its section. */
@@ -442,7 +464,7 @@ function boundFeature(root: string, key: string): FlowState | null {
442
464
  const bound = bindings.get(key);
443
465
  if (bound) {
444
466
  const s = readState(root, bound);
445
- if (s && s.stage !== "done") return s;
467
+ if (s) return s;
446
468
  }
447
469
  return unfinishedStates(root).find((s) => readClaim(root, s.slug)?.key === key) ?? null;
448
470
  }
@@ -492,12 +514,12 @@ const flowCompactInstructions = (st: FlowState) =>
492
514
  * (computed with the *effective* reserveTokens — settings + model overrides, like pi does) and
493
515
  * never while chat-only state is pending (open dialog, undigested plan) — see shouldSelfCompact.
494
516
  */
495
- function maybeCompactNow(ctx: ExtensionContext): void {
496
- if (!initiated(ctx.cwd)) return;
517
+ function maybeCompactNow(ctx: ExtensionContext, root: string): void {
518
+ if (!initiated(root)) return;
497
519
  const u = ctx.getContextUsage?.(); // minimal/fake contexts may lack usage info — treat as unknown
498
520
  if (!u || u.tokens === null) return;
499
521
  const key = sessionKey(ctx);
500
- const st = boundFeature(ctx.cwd, key);
522
+ const st = boundFeature(root, key);
501
523
  if (!st) return;
502
524
  let reserve: number;
503
525
  try {
@@ -507,27 +529,23 @@ function maybeCompactNow(ctx: ExtensionContext): void {
507
529
  } catch {
508
530
  return;
509
531
  }
510
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
532
+ const cfg = loadProject(dfDir(root)).cfg;
511
533
  const decision = {
512
534
  tokens: u.tokens,
513
535
  contextWindow: u.contextWindow,
514
536
  stage: st.stage,
515
- planFiles: listFiles(path.join(featDir(ctx.cwd, st.slug), "plan")).length,
537
+ planFiles: listFiles(path.join(featDir(root, st.slug), "plan")).length,
516
538
  checklistPending: checklistPending(cfg, st, st.stage),
517
539
  compacting: compacting.has(key),
518
540
  };
519
541
  if (!shouldSelfCompact(decision, reserve)) return;
520
- compacting.add(key);
521
- const done = () => compacting.delete(key);
522
- try {
523
- ctx.compact({
524
- customInstructions: flowCompactInstructions(st),
525
- onComplete: done,
526
- onError: done,
527
- });
528
- } catch {
529
- 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
530
- }
542
+ compacting.add(key);
543
+ const done = () => compacting.delete(key);
544
+ try {
545
+ ctx.compact({ customInstructions: flowCompactInstructions(st), onComplete: done, onError: done });
546
+ } catch {
547
+ 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
548
+ }
531
549
  }
532
550
 
533
551
  function featureRefs(root: string): FeatureRef[] {
@@ -569,13 +587,6 @@ async function gitConsistency(root: string, cfg: Config): Promise<string[]> {
569
587
 
570
588
  /** Where feature commands run: the feature worktree once it exists (that is where the
571
589
  * code under test lives), else the main checkout. Keeps gates off the main branch. */
572
-
573
- /** Lines the current project.md has that a regenerated draft cannot reproduce. */
574
- function droppableLines(current: string, draft: string): string[] {
575
- const keep = new Set(draft.split("\n").map((l) => l.trim()).filter(Boolean));
576
- return current.split("\n").map((l) => l.trim()).filter((l) => l && !keep.has(l));
577
- }
578
-
579
590
  function gateCwd(root: string, state: FlowState): string {
580
591
  const wt = worktreeAbs(root, state);
581
592
  return wt && existsSync(wt) ? wt : root;
@@ -595,18 +606,17 @@ async function runChecks(root: string, state: FlowState, cfg: Config, checks: St
595
606
  let failed = false;
596
607
  const ran: string[] = [];
597
608
  for (const c of checks) {
598
- if (c.name === "health" && cfg.commands.seedData) {
599
- const seed = await sh(cfg.commands.seedData, gateCwd(root, state));
600
- if (!seed.ok) {
601
- lines.push(`seedData FAILED:\n${tail(seed.out)}`);
602
- failed = true;
603
- break;
604
- }
609
+ // health is the same probe `flow health` runs: seeded first, retried within healthWait
610
+ const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state));
611
+ if ("seedFail" in res) {
612
+ lines.push(res.seedFail.text);
613
+ failed = true;
614
+ break;
605
615
  }
606
- const res = await sh(c.cmd, gateCwd(root, state));
607
616
  state.checks[c.name] = { ok: res.ok, at: now() };
608
617
  ran.push(c.name);
609
- lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd})${res.ok ? "" : `\n${tail(res.out)}`}`);
618
+ const tried = triedNote((res as { attempts?: number }).attempts ?? 1);
619
+ lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd}${tried})${res.ok ? "" : `\n${tail(res.out)}`}`);
610
620
  if (!res.ok) failed = true;
611
621
  }
612
622
  await stampChecks(root, state, ran);
@@ -628,6 +638,27 @@ async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{
628
638
  return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
629
639
  }
630
640
 
641
+ type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: RunResult };
642
+
643
+ /** Seed (when configured), then run the health probe within the playbook's wait budget. */
644
+ async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
645
+ const seedFail = await seedStep(root, state, cfg);
646
+ return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait);
647
+ }
648
+
649
+ /** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
650
+ async function probeHealth(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
651
+ const res = await seededProbe(root, state, cfg, probe);
652
+ if ("seedFail" in res) return res;
653
+ state.checks.health = { ok: res.ok, at: now() };
654
+ await stampChecks(root, state, ["health"]);
655
+ writeState(root, state);
656
+ return res;
657
+ }
658
+
659
+ /** A probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42). */
660
+ const triedNote = (attempts: number) => (attempts > 1 ? `, ${attempts} attempts` : "");
661
+
631
662
  /** Fingerprint of the working-tree state the checks ran against: paths (`status --porcelain`),
632
663
  * tracked content (a hash of the uncommitted diff) and HEAD. Null when git cannot answer — a
633
664
  * measurement failure must never mark a green record stale (see freshenChecks). */
@@ -653,9 +684,8 @@ async function stampChecks(root: string, state: FlowState, names: string[]): Pro
653
684
  * question. Local refs only — same offline-safe stance as the changelog proof — and an
654
685
  * unanswerable merge base reports null instead of refusing on a measurement failure. */
655
686
  async function branchState(cwd: string, defaultBranch: string): Promise<BranchState> {
656
- 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);
657
- const base = mb.out.trim();
658
- if (!mb.ok || !base) return { commitsAhead: null, uncommitted: 0 };
687
+ const base = await mergeBase(cwd, defaultBranch);
688
+ if (!base) return { commitsAhead: null, uncommitted: 0 };
659
689
  const ahead = await sh(`git rev-list --count ${sq(base)}..HEAD`, cwd);
660
690
  const n = Number.parseInt(ahead.out.trim(), 10);
661
691
  const dirty = await sh("git status --porcelain", cwd);
@@ -725,7 +755,7 @@ function reflectNote(root: string, sess: Session, note: string[], forced: Reflec
725
755
  if (next === text) return { text: `already reflected (duplicate): ${line}` };
726
756
  writeFileSync(file, next);
727
757
  // queueing is exactly when the operator hears about the checked-off pile — nudge instead of letting it grow
728
- const closed = closedReflectionCount(next);
758
+ const closed = doneItemCount(next);
729
759
  const why = forced ? "as told" : guess.why;
730
760
  return { text: `reflected (${sections.join(" + ")} — ${why}): ${line}` + (closed ? `\n${reflectionsTidyHint(closed)}` : "") };
731
761
  }
@@ -740,8 +770,7 @@ const GH_FOLD_TTL_MS = 5 * 60_000;
740
770
  * with the reason, never a guess), ok (the parsed list). */
741
771
  async function fetchUpstream(root: string): Promise<{ slug: string; issues: GhIssue[] } | { skipped: string } | { absent: true }> {
742
772
  if (process.env.DEV_FLOW_NO_ISSUES) return { skipped: "disabled (DEV_FLOW_NO_ISSUES)" };
743
- const origin = await sh("git remote get-url origin", root, 10_000);
744
- const slug = origin.ok ? githubSlug(origin.out) : "";
773
+ const slug = githubSlug((await originUrl(root)) ?? "");
745
774
  if (!slug) return { absent: true };
746
775
  const hit = ghFoldCache.get(slug);
747
776
  if (hit && Date.now() - hit.at < GH_FOLD_TTL_MS) return { slug, issues: hit.issues };
@@ -755,7 +784,7 @@ async function fetchUpstream(root: string): Promise<{ slug: string; issues: GhIs
755
784
 
756
785
  type FoldView = { state: "absent" } | { state: "skipped"; why: string } | { state: "ok"; slug: string; result: FoldResult; open: number };
757
786
 
758
- async function foldView(root: string, items: ReflectItem[], selfRepo: boolean): Promise<FoldView> {
787
+ async function foldView(root: string, items: ReflectItem[]): Promise<FoldView> {
759
788
  const up = await fetchUpstream(root);
760
789
  if ("absent" in up) return { state: "absent" };
761
790
  if ("skipped" in up) return { state: "skipped", why: up.skipped };
@@ -780,7 +809,7 @@ function foldRows(fold: FoldView, selfRepo: boolean): string[] {
780
809
  * addressable by move: each item keeps the home it is resolved in. */
781
810
  async function reflectList(root: string): Promise<RunResult> {
782
811
  const items = readReflections(root);
783
- const fold = await foldView(root, items, isSelfRepo(root));
812
+ const fold = await foldView(root, items);
784
813
  const local = items.length
785
814
  ? [
786
815
  `reflections — ${items.length} open:`,
@@ -819,8 +848,8 @@ function reflectTidy(root: string): RunResult {
819
848
  const file = path.join(dfDir(root), "reflections.md");
820
849
  if (!existsSync(file)) return { text: "reflections: nothing to tidy (no queue yet)" };
821
850
  const text = readFileSync(file, "utf8");
822
- const closed = closedReflectionCount(text);
823
- const open = openReflections(text).length;
851
+ const closed = doneItemCount(text);
852
+ const open = openChecklistItems(text).length;
824
853
  if (!closed) return { text: `reflections: nothing to tidy (${open} open, 0 closed)` };
825
854
  writeFileSync(file, reflectionsTidy(text));
826
855
  return { text: `reflections: dropped ${closed} closed item(s) — ${open} open` };
@@ -910,11 +939,6 @@ function markPendingAsk(root: string, state: FlowState, word: string): void {
910
939
  writeState(root, state);
911
940
  }
912
941
 
913
- /** The pending checkpoint is answered either way — the 💬 leaves the footer with it. */
914
- function clearPendingAsk(state: FlowState): void {
915
- delete state.pendingAsk;
916
- }
917
-
918
942
  async function gateVerify(o: GateCtx): Promise<RunResult> {
919
943
  const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
920
944
  const { state, err } = needState(root, sess, slugArg);
@@ -963,32 +987,21 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
963
987
  // the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
964
988
  if (!probe) did.push("health: none configured");
965
989
  else {
966
- const seedFail = await seedStep(root, state!, cfg);
967
- if (seedFail) return seedFail;
968
- const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
969
- state!.checks.health = { ok: probed.ok, at: now() };
970
- await stampChecks(root, state!, ["health"]);
971
- writeState(root, state!);
972
- // a probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42)
973
- const tried = probed.attempts > 1 ? `, ${probed.attempts} attempts` : "";
990
+ const probed = await probeHealth(root, state!, cfg, probe);
991
+ if ("seedFail" in probed) return probed.seedFail;
974
992
  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 };
975
- did.push(`health: PASS (${probe}${tried})`);
993
+ did.push(`health: PASS (${probe}${triedNote(probed.attempts)})`);
976
994
  }
977
995
  } else if (!probe) did.push("dev: none configured");
978
996
  else {
979
997
  // no deploy to prove, but the operator still reviews a live app — and a green health record
980
998
  // survives a killed server (process death dirties no worktree fingerprint), so the record
981
999
  // cannot stand for liveness: re-probe, before anyone is asked.
982
- const seedFail = await seedStep(root, state!, cfg);
983
- if (seedFail) return seedFail;
984
- const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
985
- state!.checks.health = { ok: probed.ok, at: now() };
986
- await stampChecks(root, state!, ["health"]);
987
- writeState(root, state!);
988
- const tried = probed.attempts > 1 ? `, ${probed.attempts} attempts` : "";
1000
+ const probed = await probeHealth(root, state!, cfg, probe);
1001
+ if ("seedFail" in probed) return probed.seedFail;
989
1002
  if (!probed.ok)
990
1003
  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 };
991
- did.push(`health: live re-probe PASS (${probe}${tried})`);
1004
+ did.push(`health: live re-probe PASS (${probe}${triedNote(probed.attempts)})`);
992
1005
  }
993
1006
  }
994
1007
  const ran = [branchLine, ...did].join("; ");
@@ -1005,7 +1018,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1005
1018
  }
1006
1019
  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?`);
1007
1020
  if (!ok) {
1008
- clearPendingAsk(state!);
1021
+ delete state!.pendingAsk;
1009
1022
  writeState(root, state!);
1010
1023
  return { text: "verification declined — stay in implement and fix what failed" };
1011
1024
  }
@@ -1015,7 +1028,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1015
1028
  if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
1016
1029
  state!.approvals.verify = now();
1017
1030
  state!.stage = "pre-release";
1018
- clearPendingAsk(state!);
1031
+ delete state!.pendingAsk;
1019
1032
  writeState(root, state!);
1020
1033
  return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${nextHint(state!, cfg)}` };
1021
1034
  }
@@ -1025,7 +1038,8 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1025
1038
  const { state, err } = needState(root, sess, slugArg);
1026
1039
  if (err) return err;
1027
1040
  const items = applicableItems(cfg, state!, "pre-release");
1028
- if (flag("no-version")) state!.noVersion = true; // operator's word at Release?: this flow ships without a version bump or tag
1041
+ // operator's word at Release?: this flow ships without a version bump or tag — recorded only once Release? is answered
1042
+ const noVersion = flag("no-version") || !!state!.noVersion;
1029
1043
  // yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
1030
1044
  const yoloWord = takeYoloWord(state!);
1031
1045
  if (yoloWord) return { text: yoloWord, isError: true };
@@ -1044,7 +1058,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1044
1058
  ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
1045
1059
  : null;
1046
1060
  // tags are only needed on the versioned path; a project without versioning must not be held up by an offline origin
1047
- const remoteTags = cfg.versioning.file && !state!.noVersion ? await releaseTags(root) : [];
1061
+ const remoteTags = cfg.versioning.file && !noVersion ? await releaseTags(root) : [];
1048
1062
  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 };
1049
1063
  const changelog =
1050
1064
  cfg.release.changelog && existsSync(path.join(wtCwd, cfg.release.changelog))
@@ -1057,14 +1071,13 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1057
1071
  const changelogBase: { pending: string[]; source: "tag" | "merge-base" | "none" } = { pending: [], source: "none" };
1058
1072
  if (changelog) {
1059
1073
  const p = sq(cfg.release.changelog!);
1060
- const mb = await sh(`git merge-base origin/${sq(cfg.defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(cfg.defaultBranch)} HEAD 2>/dev/null || true`, wtCwd);
1061
- const mbRef = mb.ok ? mb.out.trim() : "";
1074
+ const mbRef = await mergeBase(wtCwd, cfg.defaultBranch);
1062
1075
  // proof the branch touched the changelog: local refs only, so the check stays offline-safe
1063
1076
  if (mbRef) {
1064
1077
  const changes = await sh(`git diff --name-only ${sq(mbRef)} -- ${p} 2>/dev/null; git ls-files --others --exclude-standard -- ${p}`, wtCwd);
1065
1078
  changelogChanged = changes.out.split("\n").some((l) => l.trim());
1066
1079
  }
1067
- const newest = !state!.noVersion && cfg.versioning.file ? newestTaggedVersion(cfg.versioning.pattern, remoteTags) : null;
1080
+ const newest = !noVersion && cfg.versioning.file ? newestTaggedVersion(cfg.versioning.pattern, remoteTags) : null;
1068
1081
  // tag first, merge base as the understudy: `releaseTags` asks origin, so a clone that has not
1069
1082
  // fetched the tag yet must still get a baseline instead of losing the fold proof
1070
1083
  const bases: { ref: string; source: "tag" | "merge-base" }[] = [];
@@ -1083,7 +1096,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1083
1096
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1084
1097
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1085
1098
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1086
- const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1099
+ const preGate = preReleaseGate({ ...state!, noVersion, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1087
1100
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
1088
1101
  // the build the tag will trigger, proven before anything ships: a broken artifact build found after the
1089
1102
  // tag costs follow-up PRs and a re-cut tag
@@ -1095,8 +1108,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1095
1108
  // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1096
1109
  // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
1097
1110
  // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
1098
- const selfBuild = checkoutBuild(root);
1099
- const behind = sessionRunsOlderBuild(loadedVersion(), selfBuild.version);
1111
+ const { disk: selfBuild, behind } = buildSkew(root);
1100
1112
  // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
1101
1113
  // has every proof the checkout would run, and asking about it would be noise.
1102
1114
  const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
@@ -1120,13 +1132,14 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1120
1132
  if (!ui.hasUI) {
1121
1133
  return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}`, "Release?"), isError: true };
1122
1134
  }
1123
- const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${state!.noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${state!.noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}`);
1135
+ 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}` : ""}`);
1124
1136
  if (!ok) {
1125
- clearPendingAsk(state!);
1137
+ delete state!.pendingAsk;
1126
1138
  writeState(root, state!);
1127
1139
  return { text: "release declined — keep preparing in pre-release" };
1128
1140
  }
1129
1141
  }
1142
+ if (noVersion) state!.noVersion = true;
1130
1143
  state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
1131
1144
  state!.approvals["pre-release"] = now();
1132
1145
  state!.stage = "release";
@@ -1142,7 +1155,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1142
1155
  // re-read a checkout that may still be behind (#52)
1143
1156
  if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
1144
1157
  if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1145
- clearPendingAsk(state!);
1158
+ delete state!.pendingAsk;
1146
1159
  writeState(root, state!);
1147
1160
  return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
1148
1161
  }
@@ -1152,20 +1165,13 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1152
1165
  const { state, err } = needState(root, sess, slugArg);
1153
1166
  if (err) return err;
1154
1167
  const errs = releaseGate(state!);
1155
- let manifestVer: string | null = state!.releaseVersion ?? null;
1156
- if (cfg.versioning.file && !state!.noVersion && !manifestVer) {
1157
- // a flow approved before releaseVersion existed: the worktree copy is what the release gate
1158
- // validated, the main checkout is the last resort (#52)
1159
- for (const dir of [gateCwd(root, state!), root]) {
1160
- const p = path.join(dir, cfg.versioning.file);
1161
- if (!existsSync(p)) continue;
1162
- manifestVer = parseVersion(cfg.versioning.file, readFileSync(p, "utf8"));
1163
- if (manifestVer) break;
1164
- }
1165
- if (!manifestVer) errs.push(`versioning.file "${cfg.versioning.file}" has no parsable version — fix the playbook`);
1166
- }
1168
+ // the version of record is what flow release approved (#52) — never a re-read of a checkout that may be behind
1169
+ const manifestVer: string | null = state!.releaseVersion ?? null;
1170
+ 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`);
1167
1171
  const expectedTag = manifestVer ? cfg.versioning.pattern.replace("{version}", manifestVer) : null;
1168
- const hasOrigin = (await sh("git remote get-url origin", root)).ok;
1172
+ const origin = await originUrl(root);
1173
+ const hasOrigin = origin !== null;
1174
+ const forgeName = forgeOf(cfg, origin);
1169
1175
  // one round-trip answers both questions about the tag: is it there, and did it leave this laptop (#52)
1170
1176
  const tags = expectedTag ? await releaseTags(root) : [];
1171
1177
  if (tags === null) errs.push("cannot list tags on origin (offline?) — retry: local tags must not decide what is already released");
@@ -1207,25 +1213,23 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1207
1213
  // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1208
1214
  // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1209
1215
  const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1210
- const forgeProof = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1211
- const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeProof, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1216
+ const proof = mergeShapeProof(cfg.release.merge, { ancestor, forgeStyle: ancestor === false ? await forgeMergeStyle(gateCwd(root, state!), forgeName, br) : null, branch: br, defaultBranch: cfg.defaultBranch });
1212
1217
  if (proof.errors.length) errs.push(...proof.errors);
1213
1218
  else mergeNote = proof.note;
1214
1219
  }
1215
1220
  if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1216
1221
  // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
1217
- const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false; let ghNote = "";
1222
+ const releasesWanted = !!manifestVer && !flag("no-release-create") && cfg.release.releases !== false;
1223
+ let ghNote = "";
1218
1224
  let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1219
1225
  let bodyNote = "";
1220
- const forgeName = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1221
1226
  if (manifestVer && flag("no-release-create")) ghNote = "Forge release skipped (--no-release-create).";
1222
1227
  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).";
1223
1228
  else if (manifestVer && releasesWanted) {
1224
1229
  // forge release for the verified tag — gh for GitHub, glab for GitLab. A failed create is no
1225
1230
  // longer the end of the story: the proof below asks the forge whether anything is there (#63, #85)
1226
1231
  const tag = expectedTag!;
1227
- const forge = forgeName;
1228
- if (forge === "self") ghNote = "Forge release skipped (forge=self — publication stays manual).";
1232
+ if (forgeName === "self") ghNote = "Forge release skipped (forge=self — publication stays manual).";
1229
1233
  else {
1230
1234
  // the body is the changelog entry for this version (#97); the tag annotation only stands in
1231
1235
  // when the changelog has no entry for it — and never the output of a failed command, which
@@ -1246,18 +1250,17 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1246
1250
  else if (!notesRes.ok) notesNote = `no release notes (the tag command failed: ${tail(notesRes.out)}). `;
1247
1251
  else if (annotation && looksLikeShellError(annotation)) notesNote = "no release notes (the tag command returned a shell error, not a body). ";
1248
1252
  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). `;
1249
- const cmd = forge === "gitlab"
1253
+ const cmd = forgeName === "gitlab"
1250
1254
  ? `glab release create ${sq(tag)} --name ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`
1251
1255
  : `gh release create ${sq(tag)} --title ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`;
1252
1256
  const gr = await sh(cmd, root);
1253
1257
  // a failed create is the operator's call to decline, never a choice we make for them — stamp it so finish names it (#63)
1254
1258
  if (gr.ok) delete state!.forgeReleaseSkipped; // a successful retry lifts the stamp
1255
1259
  else state!.forgeReleaseSkipped = tail(gr.out);
1256
- ghNote = gr.ok ? `${forge} release ${tag} created. ${notesNote}`.trim() : `${forge} release skipped: ${tail(gr.out)}`;
1260
+ ghNote = gr.ok ? `${forgeName} release ${tag} created. ${notesNote}`.trim() : `${forgeName} release skipped: ${tail(gr.out)}`;
1257
1261
  }
1258
1262
  }
1259
- const diskBuild = checkoutBuild(root);
1260
- const behind = sessionRunsOlderBuild(loadedVersion(), diskBuild.version);
1263
+ const skew = buildSkew(root);
1261
1264
  const openRelease = checklistPending(cfg, state!, "release");
1262
1265
  // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
1263
1266
  // name them at the last objective gate — on the way out too, or the refusal hides half the story
@@ -1293,10 +1296,10 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1293
1296
  // a session that shipped from behind: the code it runs is not the code the checkout just released
1294
1297
  state!.staleBuild
1295
1298
  ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
1296
- : behind
1299
+ : skew.behind
1297
1300
  // #117: the pair (session vs what the disk ships) makes the warning actionable where it prints;
1298
1301
  // a second registered copy is what made the skew confusing on the report — name it too
1299
- ? `warning: this session runs dev-flow ${behind}, ${diskBuild.label} ships ${diskBuild.version ?? "?"} — /reload before trusting what it printed.${copyWarning() ? ` ${copyWarning()}` : ""}`
1302
+ ? `warning: ${skew.line}.${copyWarning() ? ` ${copyWarning()}` : ""}`
1300
1303
  : "",
1301
1304
  mergeNote,
1302
1305
  openNote,
@@ -1317,7 +1320,8 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1317
1320
  // after this the flow state is gone: nothing may sit uncommitted or unpushed
1318
1321
  const dirty = await sh("git status --porcelain", root);
1319
1322
  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 };
1320
- const hasOriginF = (await sh("git remote get-url origin", root)).ok;
1323
+ const origin = await originUrl(root);
1324
+ const hasOriginF = origin !== null;
1321
1325
  if (hasOriginF) {
1322
1326
  const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1323
1327
  if (!pushed.ok) return { text: `HEAD is not on origin/${cfg.defaultBranch} — push the release (git push origin ${cfg.defaultBranch}) before finish`, isError: true };
@@ -1345,25 +1349,25 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1345
1349
  if (wt && existsSync(wt)) {
1346
1350
  const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
1347
1351
  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);
1348
- const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1352
+ const unmergedLines = unmerged.out.split("\n").filter(Boolean);
1349
1353
  // the refusal names the paths, not just the count — same proof verify and release print (gh#131)
1350
- if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}${status.out.trim() ? `:\n${tail(status.out)}` : ""}`, isError: true };
1351
- if (assess.unmerged.length) {
1354
+ if (status.out.trim()) return { text: `finish blocked:\n- worktree has uncommitted changes — commit or discard them first:\n${tail(status.out)}`, isError: true };
1355
+ if (unmergedLines.length) {
1352
1356
  const policy = cfg.release.merge;
1353
1357
  // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1354
1358
  // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1355
1359
  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;
1356
1360
  unmergedNote =
1357
1361
  policy && policy !== "merge" && policy !== "any"
1358
- ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1362
+ ? ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} — expected, the playbook merges with ${policy}.`
1359
1363
  : policy === "merge" && measurable
1360
- ? ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} although the playbook says merge = merge — that PR did not land as a merge commit`
1361
- : ` ${assess.unmerged.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1364
+ ? ` ${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`
1365
+ : ` ${unmergedLines.length} commit(s) in ${state!.worktree} are not on ${cfg.defaultBranch} (squash merge?)`;
1362
1366
  // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1363
1367
  // answer it, only the operator does
1364
1368
  if (policy === "merge" && measurable && !flag("confirmed")) {
1365
1369
  markPendingAsk(root, state!, "Merge policy violation?");
1366
- return { text: needsOperator(`the playbook says merge = merge, but ${assess.unmerged.length} commit(s) of ${state!.slug} are not on ${cfg.defaultBranch} — the PR landed as a squash or a rebase. Ask the operator how to proceed, then re-run with --confirmed`, "Merge policy violation?"), isError: true };
1370
+ 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 };
1367
1371
  }
1368
1372
  }
1369
1373
  }
@@ -1381,7 +1385,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1381
1385
  }
1382
1386
  const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1383
1387
  if (!ok) {
1384
- clearPendingAsk(state!);
1388
+ delete state!.pendingAsk;
1385
1389
  writeState(root, state!);
1386
1390
  return { text: "finish declined" };
1387
1391
  }
@@ -1401,24 +1405,14 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1401
1405
  // remote cleanup: origin/<branch> is deleted only on proof it was released — being an ancestor of
1402
1406
  // origin/<default> (merge-commit merges) or a merged PR via gh (squash merges); else it stays.
1403
1407
  let remoteNote = "";
1404
- if (state!.branch && (await sh("git remote get-url origin", root)).ok) {
1408
+ if (state!.branch && hasOriginF) {
1405
1409
  const br = state!.branch;
1406
1410
  const onRemote = await sh("git ls-remote --heads origin", root);
1407
1411
  if (onRemote.out.split("\n").some((l) => l.endsWith(`\trefs/heads/${br}`))) {
1408
1412
  await sh(`git fetch -q origin ${sq(br)}`, root);
1409
1413
  let merged = (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok;
1410
- if (!merged) {
1411
- // squash merges leave no ancestry — ask the forge: gh pr list, or the GitLab API via glab; self-hosted stays on ancestry proof
1412
- const originUrl = await sh("git remote get-url origin", root);
1413
- const forge = cfg.forge || detectForge(originUrl.out);
1414
- if (forge === "gitlab") {
1415
- const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${br}&state=merged&per_page=1`)}`, root);
1416
- merged = mr.ok && mr.out.trim() !== "[]";
1417
- } else if (forge === "github") {
1418
- const pr = await sh(`gh pr list --state merged --head ${sq(br)} --json number --jq length`, root);
1419
- merged = pr.ok && pr.out.trim() !== "0";
1420
- }
1421
- }
1414
+ // squash merges leave no ancestry — ask the forge (gh/glab); self-hosted stays on ancestry proof
1415
+ if (!merged) merged = (await forgeMergeStyle(root, forgeOf(cfg, origin), br)) !== null;
1422
1416
  if (merged) remoteNote = (await sh(`git push origin --delete ${sq(`refs/heads/${br}`)}`, root)).ok
1423
1417
  ? ` origin/${br} deleted (verified merged)`
1424
1418
  : ` origin/${br} delete failed — git push origin --delete ${br}`;
@@ -1440,7 +1434,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1440
1434
  }
1441
1435
 
1442
1436
  async function gateInit(o: GateCtx): Promise<RunResult> {
1443
- const { root, ui, cfg, rest, flag } = o;
1437
+ const { root, ui, rest, flag } = o;
1444
1438
  // a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
1445
1439
  // only sanctioned agent path to the playbook: claiming "created" when the folder was already
1446
1440
  // there sends the agent diffing its own config for damage that never happened (#39).
@@ -1449,20 +1443,16 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1449
1443
  const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
1450
1444
  // self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
1451
1445
  writeFileSync(path.join(dfDir(root), ".gitignore"), "*\n!project.md\n");
1452
- rmSync(path.join(dfDir(root), ".current"), { force: true }); // migrate away the legacy repo-global pointer
1453
1446
  const mdFile = path.join(dfDir(root), "project.md");
1454
1447
  const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
1455
1448
  const curBr = await currentBranch(root);
1456
1449
  // never propose a feature branch (contains "/") as the default branch
1457
1450
  const branch = (head.ok ? head.out.match(/refs\/remotes\/origin\/(.+)/)?.[1] : undefined) || (curBr.includes("/") ? undefined : curBr) || "main";
1458
1451
  const det = detectProject(root, branch);
1459
- const origin = await sh("git remote get-url origin", root);
1460
- det.partial.forge = origin.ok && origin.out.trim() ? detectForge(origin.out) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
1452
+ const origin = await originUrl(root);
1453
+ det.partial.forge = origin ? detectForge(origin) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
1461
1454
  det.partial.merge = (await mergeHistoryEvidence(root, branch))?.note; // "what do you actually do when a PR merges", read off the log
1462
- const loaded = loadProject(dfDir(root));
1463
1455
  const draftFresh = buildDraft(det);
1464
- const draftRefresh = buildDraft(det, loaded.cfg);
1465
- const editHint = "to change anything: edit .dev-flow/project.md directly (flow init = doctor revalidates), or from an agent session: flow init --draft → discuss → --write";
1466
1456
  if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
1467
1457
  // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
1468
1458
  const ghosts = ghostFeatureDirs(root);
@@ -1473,22 +1463,21 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1473
1463
  notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
1474
1464
  } else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
1475
1465
  }
1476
- const writeMd = (text: string): RunResult | null => {
1466
+ /** Validate, back up what was there (the operator's rules are not regenerable), write. */
1467
+ const writeMd = (text: string): { rej: RunResult } | { warn: string[] } => {
1477
1468
  const parsed = parseProjectMd(text);
1478
- if (parsed.hard.length) return { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true };
1479
- // the operator's rules are not regenerable — keep what was there before any overwrite
1469
+ if (parsed.hard.length) return { rej: { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true } };
1480
1470
  if (existsSync(mdFile)) copyFileSync(mdFile, `${mdFile}.bak`);
1481
1471
  writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
1482
- return null;
1472
+ return { warn: parsed.warn };
1483
1473
  };
1484
1474
  if (flag("write")) {
1485
1475
  const content = rest[rest.indexOf("--write") + 1];
1486
1476
  if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>"', isError: true };
1487
- const parsed = parseProjectMd(content);
1488
- const rej = writeMd(content);
1489
- if (rej) return rej;
1477
+ const w = writeMd(content);
1478
+ if ("rej" in w) return w.rej;
1490
1479
  notes.push("project.md written (operator-owned playbook)", GIT_TRACK_NOTE);
1491
- if (parsed.warn.length) notes.push("warnings:", ...parsed.warn.map((w) => ` ${w}`));
1480
+ if (w.warn.length) notes.push("warnings:", ...w.warn.map((x) => ` ${x}`));
1492
1481
  } else if (!existsSync(mdFile)) {
1493
1482
  // first init: never write silently. The setup brief lists what detection could not decide;
1494
1483
  // the agent relays the questions to the operator and applies the answers via flow init --write
@@ -1504,8 +1493,8 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1504
1493
  if (ui.hasUI) {
1505
1494
  const ok = await ui.confirm("Write project.md draft?", `${mdDigest(draftFresh)}\n\nWrite this detection draft now? Declining leaves the setup questions open for chat clarification.`);
1506
1495
  if (ok) {
1507
- const rej = writeMd(draftFresh);
1508
- if (rej) return rej;
1496
+ const w = writeMd(draftFresh);
1497
+ if ("rej" in w) return w.rej;
1509
1498
  notes.push("wrote .dev-flow/project.md from detection — review it and adjust as needed", GIT_TRACK_NOTE);
1510
1499
  } else notes.push("draft not written — answer the setup questions, then flow init --write");
1511
1500
  }
@@ -1517,44 +1506,12 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1517
1506
  copyFileSync(mdFile, `${mdFile}.bak`);
1518
1507
  writeFileSync(mdFile, draftFresh);
1519
1508
  notes.push("project.md OVERWRITTEN (--force; previous copy kept as project.md.bak):", ...det.report.map((r) => ` ${r}`), GIT_TRACK_NOTE);
1520
- } else if (!ui.hasUI) {
1521
- // the CI/agent path: the doctor's findings have to be printed, not just promised
1522
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
1523
- notes.push("project.md already exists — kept (flow init --force to overwrite, --write to edit)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
1524
- } else if (existsSync(mdFile)) {
1525
- // doctor mode: cheap consistency probes only — never runs project commands
1509
+ } else {
1510
+ // re-init is the doctor's file-level check: findings are printed, the playbook is never regenerated —
1511
+ // a draft cannot reproduce hand-written prose, items and keys. Edit the file, or flow init --write.
1512
+ const loaded = loadProject(dfDir(root));
1526
1513
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
1527
- findings.push(...(await gitConsistency(root, loaded.cfg)));
1528
- // a repo that never said how a PR merges gets the evidence next to the finding, so the answer is a choice and not a guess
1529
- if (!loaded.cfg.release.merge) {
1530
- const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
1531
- if (ev?.recent) findings.push(`${ev.note} — write it into the playbook: merge = ${ev.recent} under ## release (or let the next flow start ask and write it)`);
1532
- }
1533
- for (const it of readReflections(root)) findings.push(`open reflection [${it.section}]: ${it.line.slice(6)}`);
1534
- if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
1535
- else {
1536
- // a refresh is regenerated from detection + config: lines it cannot reproduce are
1537
- // hand-written (prose, checklist items, hand-set keys) and would vanish silently.
1538
- const dropped = droppableLines(readFileSync(mdFile, "utf8"), draftRefresh);
1539
- let edited: string | undefined;
1540
- if (dropped.length)
1541
- notes.push(`doctor: refresh refused — a regenerated draft would drop ${dropped.length} hand-written line(s):`, ...dropped.slice(0, 8).map((l) => ` ${l}`), ...(dropped.length > 8 ? [` …(${dropped.length - 8} more)`] : []));
1542
- else
1543
- edited = ui.editor
1544
- ? await ui.editor(`flow init — doctor: ${findings.length} finding(s) — edit & save to apply, Esc skips`, draftRefresh)
1545
- : (await ui.confirm(`flow init — doctor: ${findings.length} finding(s)`, `${findings.join("\n")}
1546
-
1547
- Write refreshed project.md? Your file; cancel writes nothing.
1548
- ${mdDigest(draftRefresh)}`))
1549
- ? draftRefresh
1550
- : undefined;
1551
- if (edited === undefined) notes.push(dropped.length ? "findings — fix them by editing the file:" : "declined — project.md unchanged", ...findings.map((f) => ` ${f}`));
1552
- else {
1553
- const rej = writeMd(edited);
1554
- if (rej) return rej;
1555
- notes.push("project.md refreshed — findings addressed:", ...findings.map((f) => ` ${f}`), editHint);
1556
- }
1557
- }
1514
+ notes.push("project.md already exists — kept (edit it directly, flow init --write to replace it, --force to redraft)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
1558
1515
  }
1559
1516
  const initCfg = loadProject(dfDir(root)).cfg;
1560
1517
  if (initCfg.mainHook) {
@@ -1575,7 +1532,7 @@ ${mdDigest(draftRefresh)}`))
1575
1532
  }
1576
1533
 
1577
1534
  async function gateStart(o: GateCtx): Promise<RunResult> {
1578
- const { root, ui, sess, cfg, rest, flag, slugArg } = o;
1535
+ const { root, sess, cfg, rest, flag, slugArg } = o;
1579
1536
  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 };
1580
1537
  if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
1581
1538
  // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
@@ -1589,14 +1546,12 @@ async function gateStart(o: GateCtx): Promise<RunResult> {
1589
1546
  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 };
1590
1547
  // --- preflight: is this session running the current build, and is the playbook complete? ---
1591
1548
  const notes: string[] = [];
1592
- const disk = checkoutBuild(root);
1593
- const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
1594
- if (behind) notes.push(`warning: this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version} — /reload rebinds session state; only restarting the host swaps the code it runs`);
1549
+ const skew = buildSkew(root);
1550
+ if (skew.line) notes.push(`warning: ${skew.line}`);
1595
1551
  const dupStart = copyWarning();
1596
1552
  if (dupStart) notes.push(dupStart);
1597
1553
  if (flag("check-upstream")) {
1598
- const pub = await sh("npm view pi-dev-flow version", root);
1599
- const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1554
+ const newest = await publishedVersion(root);
1600
1555
  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?)");
1601
1556
  }
1602
1557
  // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
@@ -1607,11 +1562,7 @@ async function gateStart(o: GateCtx): Promise<RunResult> {
1607
1562
  const styleArg = flagValue(rest, "merge");
1608
1563
  const style = styleArg === null ? null : parseMergeStyle(styleArg);
1609
1564
  if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
1610
- // with no playbook at all there is nothing to ask about: writing the playbook is `flow init`'s job, and
1611
- // a repo that never ran init must not be refused a feature by a merge-policy question
1612
- const hasPlaybook = existsSync(path.join(dfDir(root), "project.md"));
1613
- if (!hasPlaybook) notes.push("no .dev-flow/project.md yet — flow init writes the playbook (it now asks for the merge policy too)");
1614
- if (hasPlaybook && (!cfg.release.merge || (style && style !== cfg.release.merge))) {
1565
+ if (!cfg.release.merge || (style && style !== cfg.release.merge)) {
1615
1566
  if (!style) {
1616
1567
  const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
1617
1568
  return {
@@ -1650,7 +1601,6 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1650
1601
  const errs = approveGate(state!, cfg, listFiles(planDir), existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined);
1651
1602
  if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1652
1603
  const planItems = applicableItems(cfg, state!, "plan");
1653
- if (flag("yolo")) state!.yolo = true; // operator's word at Approve? — every later gate question is pre-confirmed; checks and guardrails stay
1654
1604
  const audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
1655
1605
  const askPending = !flag("confirmed");
1656
1606
  if (askPending) {
@@ -1659,8 +1609,14 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1659
1609
  return { text: needsOperator("plan approval needs the operator: approve interactively, or re-run with --confirmed once the operator answered in chat", "Approve?"), isError: true };
1660
1610
  }
1661
1611
  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." : ""}`);
1662
- if (!ok) return { text: "approval declined — keep iterating on the plan" };
1612
+ if (!ok) {
1613
+ delete state!.pendingAsk;
1614
+ writeState(root, state!);
1615
+ return { text: "approval declined — keep iterating on the plan" };
1616
+ }
1663
1617
  }
1618
+ // the operator's word at Approve?, recorded only once given: every later gate question is pre-confirmed; checks and guardrails stay
1619
+ if (flag("yolo")) state!.yolo = true;
1664
1620
  if (planItems.length) state!.confirmations = { ...state!.confirmations, plan: { hash: checklistHash(planItems), at: now() } };
1665
1621
  const branch = subst(cfg.branchPattern, state!.slug);
1666
1622
  const wtRel = subst(cfg.worktreeDir, state!.slug);
@@ -1688,26 +1644,25 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1688
1644
  state!.worktree = wtRel;
1689
1645
  state!.stage = "implement";
1690
1646
  state!.approvals.plan = now();
1691
- clearPendingAsk(state!);
1647
+ delete state!.pendingAsk;
1692
1648
  writeState(root, state!);
1693
1649
  return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${setupNote}\n${nextHint(state!, cfg)}` };
1694
1650
  }
1695
1651
 
1696
1652
  async function gateStatus(o: GateCtx): Promise<RunResult> {
1697
- const { root, ui, sess, cfg, flag, slugArg } = o;
1653
+ const { root, sess, cfg, flag, slugArg } = o;
1698
1654
  const df = dfDir(root);
1699
1655
  const { md } = loadProject(df);
1700
1656
  // cheap fs probes only (no git subprocesses) — status is a glance, `flow doctor` is the full list
1701
1657
  const findings = md ? doctorFindings(root, cfg, md) : [];
1702
1658
  // a session running an older build than the disk ships is the one thing a glance must say: every
1703
1659
  // gate proof printed since the drift began belongs to the older code.
1704
- const disk = checkoutBuild(root);
1705
- const staleBuild = sessionRunsOlderBuild(loadedVersion(), disk.version);
1706
- const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(staleBuild ? [`⚠ this session runs dev-flow ${staleBuild}, ${disk.label} ships ${disk.version} — /reload rebinds; restart swaps code`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
1660
+ const skew = buildSkew(root);
1661
+ const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(skew.line ? [`⚠ ${skew.line}`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
1707
1662
  // the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
1708
1663
  const rmap = roadmapOpenCount(readRoadmap(root));
1709
1664
  const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
1710
- const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
1665
+ const slugs = slugArg ? [slugArg] : unfinishedStates(root).map((s) => s.slug);
1711
1666
  const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
1712
1667
  if (flag("json")) {
1713
1668
  const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
@@ -1753,14 +1708,14 @@ async function gateReflect(o: GateCtx): Promise<RunResult> {
1753
1708
  if (words.length) return reflectNote(root, sess, words, forced);
1754
1709
  // upstream for the update probe: the manifest's repository field; the dev-flow checkout itself falls back to its origin
1755
1710
  const self = pluginVersion(import.meta.dirname);
1756
- const upstream = self.repo || (isSelfRepo(root) ? githubSlug((await sh("git remote get-url origin", root)).out) : "");
1711
+ const upstream = self.repo || (isSelfRepo(root) ? githubSlug((await originUrl(root)) ?? "") : "");
1757
1712
  const refl = readReflections(root);
1758
- const fold = await foldView(root, refl, isSelfRepo(root));
1713
+ const fold = await foldView(root, refl);
1759
1714
  return {
1760
1715
  text: reflectProtocol(refl, isSelfRepo(root), {
1761
1716
  version: self.version,
1762
1717
  upstream,
1763
- closed: closedReflectionCount(readReflectionsText(root)),
1718
+ closed: doneItemCount(readReflectionsText(root)),
1764
1719
  ghFold: fold.state === "ok" && fold.open ? { repo: fold.slug, open: fold.open, similar: fold.result.similar.length } : undefined,
1765
1720
  }).join("\n"),
1766
1721
  };
@@ -1773,7 +1728,7 @@ async function gateRoadmap(o: GateCtx): Promise<RunResult> {
1773
1728
  const [verb = "list", ...args] = words;
1774
1729
  const text = readRoadmap(root);
1775
1730
  const open = roadmapOpenCount(text);
1776
- const done = roadmapDoneCount(text);
1731
+ const done = doneItemCount(text);
1777
1732
  const save = (next: string) => writeFileSync(roadmapFile(root), next); // .dev-flow/ existence is runFlow's precondition
1778
1733
  const idx = Number(args[0]);
1779
1734
  const validIdx = Number.isInteger(idx) && idx >= 1 && idx <= open;
@@ -1811,14 +1766,14 @@ async function gateRoadmap(o: GateCtx): Promise<RunResult> {
1811
1766
  }
1812
1767
 
1813
1768
  async function gateDoctor(o: GateCtx): Promise<RunResult> {
1814
- const { root, cfg, rest } = o;
1769
+ const { root, rest } = o;
1815
1770
  // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
1816
1771
  const df = dfDir(root);
1817
1772
  const loaded = loadProject(df);
1818
1773
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
1819
1774
  findings.push(...(await gitConsistency(root, loaded.cfg)));
1820
1775
  const refl = readReflections(root);
1821
- const fold = await foldView(root, refl, isSelfRepo(root));
1776
+ const fold = await foldView(root, refl);
1822
1777
  if (refl.length) {
1823
1778
  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:`);
1824
1779
  // labelled from the heading each item sits under — the file is the record, re-guessing from the
@@ -1831,15 +1786,14 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
1831
1786
  findings.push(...foldRows(fold, isSelfRepo(root)));
1832
1787
  const unfiled = reflectUnfiledCount(readReflectionsText(root));
1833
1788
  if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## plugin — flow reflect list shows them, flow reflect move <n> --plugin|--playbook files them`);
1834
- const closedRefl = closedReflectionCount(readReflectionsText(root));
1789
+ const closedRefl = doneItemCount(readReflectionsText(root));
1835
1790
  if (closedRefl) findings.push(reflectionsTidyHint(closedRefl));
1836
1791
  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" };
1837
1792
  // flow doctor <note>: a fresh observation gets an investigation brief and a fix route
1838
1793
  return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
1839
1794
  }
1840
1795
 
1841
- /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
1842
- * their own names back, so the bodies needed zero edits. */
1796
+ /** What a gate handler needs from the runFlow preamble. */
1843
1797
  interface GateCtx {
1844
1798
  root: string;
1845
1799
  ui: Ui;
@@ -1854,16 +1808,14 @@ interface GateCtx {
1854
1808
  async function gateVersion(o: GateCtx): Promise<RunResult> {
1855
1809
  const { root, flag } = o;
1856
1810
  // the plugin's own version — separate from the project's versioning.file version the release gates use
1857
- const self = checkoutBuild(root);
1858
- const behind = sessionRunsOlderBuild(loadedVersion(), self.version);
1811
+ const { disk: self, behind } = buildSkew(root);
1859
1812
  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}`;
1860
1813
  // in the dev-flow repo head names the checkout, so name where the stale code actually lives
1861
1814
  const from = SELF_BUILD.dir !== self.dir ? ` (from ${SELF_BUILD.dir})` : "";
1862
1815
  const dupNote = copyWarning();
1863
1816
  // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
1864
1817
  if (flag("check-upstream")) {
1865
- const pub = await sh("npm view pi-dev-flow version", root);
1866
- const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1818
+ const newest = await publishedVersion(root);
1867
1819
  return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
1868
1820
  }
1869
1821
  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}` : ""}` };
@@ -1900,22 +1852,19 @@ async function gateHealth(o: GateCtx): Promise<RunResult> {
1900
1852
  const { root, sess, cfg, slugArg } = o;
1901
1853
  const { state, err } = needState(root, sess, slugArg);
1902
1854
  if (err) return err;
1903
- if (!cfg.commands.health) return { text: "no commands.health configured — add `health = <command>` (or a flow-check health block) under ## implement in .dev-flow/project.md", isError: true };
1904
- const seedFail = await seedStep(root, state!, cfg);
1905
- if (seedFail) return seedFail;
1906
- const res = await runHealthProbe(cfg.commands.health, gateCwd(root, state!), cfg.healthWait);
1907
- state!.checks.health = { ok: res.ok, at: now() };
1908
- await stampChecks(root, state!, ["health"]);
1909
- writeState(root, state!);
1910
- const tried = res.attempts > 1 ? `, ${res.attempts} attempts` : "";
1911
- return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.health}${tried})\n${tail(res.out)}` };
1855
+ // commands.health and a flow-check named health are the same probe (healthProbe reads both)
1856
+ const probe = healthProbe(cfg);
1857
+ 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 };
1858
+ const res = await probeHealth(root, state!, cfg, probe);
1859
+ if ("seedFail" in res) return res.seedFail;
1860
+ return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${probe}${triedNote(res.attempts)})\n${tail(res.out)}` };
1912
1861
  }
1913
1862
 
1914
1863
  async function gateUse(o: GateCtx): Promise<RunResult> {
1915
1864
  const { root, sess, slugArg } = o;
1916
1865
  if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
1917
1866
  const st = readState(root, slugArg);
1918
- if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
1867
+ if (!st) return { text: `no unfinished feature ${slugArg}`, isError: true };
1919
1868
  const prior = readClaim(root, slugArg);
1920
1869
  const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
1921
1870
  sess.bind(slugArg);
@@ -1923,14 +1872,14 @@ async function gateUse(o: GateCtx): Promise<RunResult> {
1923
1872
  // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
1924
1873
  // must not inherit a 💬 for a question it never posed
1925
1874
  if (st.pendingAsk) {
1926
- clearPendingAsk(st);
1875
+ delete st.pendingAsk;
1927
1876
  writeState(root, st);
1928
1877
  }
1929
1878
  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}` };
1930
1879
  }
1931
1880
 
1932
1881
  async function gateAbort(o: GateCtx): Promise<RunResult> {
1933
- const { root, sess, slugArg } = o;
1882
+ const { root, ui, sess, flag, slugArg } = o;
1934
1883
  // Unbinds the session only; state and worktree stay for manual recovery.
1935
1884
  const target = slugArg ?? sess.slug;
1936
1885
  if (!target) return { text: "nothing bound — pass a slug", isError: true };
@@ -1939,13 +1888,20 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
1939
1888
  // that works it erases the plan that session is still writing (same rule needState applies)
1940
1889
  const claim = readClaim(root, target);
1941
1890
  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 };
1942
- if (sess.slug === target) sess.bind(null);
1943
1891
  if (st && !st.worktree) {
1944
1892
  // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
1945
- // as a ghost the doctor flags (a plan/ whose state.json is gone)
1893
+ // as a ghost the doctor flags (a plan/ whose state.json is gone). A written plan is the
1894
+ // operator's work too — it is not dropped without their word.
1895
+ const written = listFiles(path.join(featDir(root, target), "plan"));
1896
+ if (written.length && !flag("confirmed")) {
1897
+ const ok = ui.hasUI && (await ui.confirm("Drop plan?", `Abort ${target}? Its plan/ (${written.join(", ")}) is deleted for good.`));
1898
+ 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 };
1899
+ }
1900
+ if (sess.slug === target) sess.bind(null);
1946
1901
  rmSync(featDir(root, target), { recursive: true, force: true });
1947
1902
  return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
1948
1903
  }
1904
+ if (sess.slug === target) sess.bind(null);
1949
1905
  if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
1950
1906
  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}` : "") };
1951
1907
  }
@@ -1958,14 +1914,58 @@ const workerSessions = new Set<string>();
1958
1914
  /** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
1959
1915
  const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"] };
1960
1916
 
1917
+ /** What makes a worker show up in pi-web's Agents menu: pi-web classifies a subagent from the
1918
+ * custom entries its own runtime writes into the child's session file (pi-web lib/subagents.ts
1919
+ * readSubagentRun, fed by lib/session-reader.ts). Two placement rules the reader enforces:
1920
+ * the meta entry must be the file's FIRST data entry (the scanner reads header + one line and
1921
+ * calls anything else a fork), and a persisted `running` the host cannot prove live displays as
1922
+ * `interrupted` — so the final result entry is what the menu really rests on.
1923
+ * Unknown entry types are inert in plain pi, so stamping is unconditional. */
1924
+ const PIWEB_SUBAGENT = { meta: "pi-web:subagent", status: "pi-web:subagent-status", result: "pi-web:subagent-result" } as const;
1925
+
1926
+ interface WorkerSubagentMeta {
1927
+ parentId: string;
1928
+ parentFile: string;
1929
+ toolCallId: string;
1930
+ profile: string;
1931
+ description: string;
1932
+ task: string;
1933
+ }
1934
+
1935
+ /** Only version 1 + the two lineage strings are hard-validated by pi-web's reader; the rest is
1936
+ * display. resourceSnapshot is deliberately absent: its presence pins the tool set strictly when
1937
+ * pi-web reopens the child, and these workers are never resumed by pi-web. */
1938
+ function piwebWorkerMeta(m: WorkerSubagentMeta): Record<string, unknown> {
1939
+ return {
1940
+ version: 1,
1941
+ parentSessionId: m.parentId,
1942
+ parentSessionPath: m.parentFile,
1943
+ parentToolCallId: m.toolCallId,
1944
+ profile: m.profile,
1945
+ description: m.description,
1946
+ task: m.task,
1947
+ runInBackground: false,
1948
+ createdAt: now(),
1949
+ };
1950
+ }
1951
+
1952
+ /** Best-effort by contract: a stamp that will not write must never break the worker run —
1953
+ * visibility, not function (same rule as the worker's setSessionName renames). */
1954
+ function piwebStamp(target: { appendCustomEntry?(customType: string, data?: unknown): unknown } | undefined, customType: string, data: unknown): void {
1955
+ try { target?.appendCustomEntry?.(customType, data); } catch { /* visibility only */ }
1956
+ }
1957
+
1961
1958
  /** Seam that spawns a worker as a real pi session — tests replace `.run`. With the driver's session
1962
1959
  * file and directory known, the worker's header links back to the driver (`parentSession`), so pi's
1963
- * picker nests it under the driver. */
1964
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<AgentSession> } = {
1965
- run: async ({ work, model, name, tools, parent, dir }) => {
1960
+ * picker nests it under the driver, and the pi-web meta lands as the file's first data entry. */
1961
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string; subagent?: WorkerSubagentMeta }) => Promise<AgentSession> } = {
1962
+ run: async ({ work, model, name, tools, parent, dir, subagent }) => {
1966
1963
  const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
1967
1964
  await loader.reload();
1968
1965
  const sessionManager = parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
1966
+ // The meta must be stamped here — before createAgentSession appends model_change/session_info,
1967
+ // because pi-web's scanner classifies the child only from the first data entry after the header.
1968
+ if (sessionManager && subagent) piwebStamp(sessionManager, PIWEB_SUBAGENT.meta, piwebWorkerMeta(subagent));
1969
1969
  const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
1970
1970
  try { workerSessions.add(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the default context */ }
1971
1971
  try { session.setSessionName(name); } catch { /* naming is visibility, not function */ }
@@ -1973,31 +1973,23 @@ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name:
1973
1973
  },
1974
1974
  };
1975
1975
 
1976
- async function isLinkedWorktree(root: string): Promise<boolean> {
1977
- const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", root);
1978
- if (!r.ok) return false;
1979
- const [gitDir, common] = r.out.split("\n").map((l) => l.trim());
1980
- return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
1981
- }
1982
-
1983
- /** Per-cwd cache for flowRoot — the tool_call hook consults it on every call. */
1984
- const flowRootCache = new Map<string, string>();
1976
+ /** Per-cwd cache of the main checkout a linked worktree belongs to (null = not a linked worktree) —
1977
+ * every hook resolves its root through flowRoot, so git is asked once per directory. */
1978
+ const mainCheckoutCache = new Map<string, string | null>();
1985
1979
 
1986
1980
  /** The root whose .dev-flow/ is the flow truth for a session cwd. A feature worktree is a linked git
1987
1981
  * worktree whose tracked .dev-flow/ holds only project.md — state, claims and plans live in the main
1988
1982
  * checkout. Judging a session by its own cwd found no features and every guard answered "no active
1989
1983
  * flow". So a linked worktree resolves to its main checkout when that checkout is initiated. */
1990
1984
  async function flowRoot(cwd: string): Promise<string> {
1991
- const hit = flowRootCache.get(cwd);
1992
- if (hit !== undefined) return hit;
1993
- let root = cwd;
1994
- if (await isLinkedWorktree(cwd)) {
1995
- const r = await sh("git rev-parse --path-format=absolute --git-common-dir", cwd);
1996
- const main = mainCheckoutRoot(cwd, r.ok ? r.out.trim() : null);
1997
- if (main && initiated(main)) root = main;
1985
+ if (!mainCheckoutCache.has(cwd)) {
1986
+ const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", cwd);
1987
+ const [gitDir, common] = r.ok ? r.out.split("\n").map((l) => l.trim()) : [];
1988
+ const linked = !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
1989
+ mainCheckoutCache.set(cwd, linked ? mainCheckoutRoot(cwd, common) : null);
1998
1990
  }
1999
- flowRootCache.set(cwd, root);
2000
- return root;
1991
+ const main = mainCheckoutCache.get(cwd);
1992
+ return main && initiated(main) ? main : cwd;
2001
1993
  }
2002
1994
 
2003
1995
  async function currentBranch(root: string): Promise<string> {
@@ -2024,11 +2016,6 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
2024
2016
  return { state };
2025
2017
  }
2026
2018
 
2027
- async function listDirs(dir: string): Promise<string[]> {
2028
- const { readdirSync } = await import("node:fs");
2029
- return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
2030
- }
2031
-
2032
2019
  function tail(out: string, n = 15): string {
2033
2020
  const lines = out.split("\n").filter(Boolean);
2034
2021
  return lines.length > n ? `…(${lines.length - n} lines)…\n${lines.slice(-n).join("\n")}` : out;
@@ -2039,13 +2026,13 @@ function tail(out: string, n = 15): string {
2039
2026
  /** Compact footer: bound flow = stage glyph, slug, mode markers, ⚠️ on its failing checks; unbound = the
2040
2027
  * unfinished-flow count, or `💬 no flows` — an initiated repo always carries the footer. An uninitiated
2041
2028
  * folder gets nothing: the status is cleared. Pure read — rendering never binds or claims anything. */
2042
- function refreshStatus(ctx: ExtensionContext): void {
2029
+ function refreshStatus(ctx: ExtensionContext, root: string): void {
2043
2030
  if (!ctx.hasUI) return;
2044
- if (!initiated(ctx.cwd)) {
2031
+ if (!initiated(root)) {
2045
2032
  ctx.ui.setStatus("dev-flow", undefined);
2046
2033
  return;
2047
2034
  }
2048
- const s = statusFor(boundFeature(ctx.cwd, sessionKey(ctx)), unfinishedStates(ctx.cwd).length);
2035
+ const s = statusFor(boundFeature(root, sessionKey(ctx)), unfinishedStates(root).length);
2049
2036
  ctx.ui.setStatus("dev-flow", s.text);
2050
2037
  }
2051
2038
 
@@ -2068,10 +2055,9 @@ export default function devFlow(pi: ExtensionAPI) {
2068
2055
  const uiFrom = (ctx: ExtensionContext): Ui => ({
2069
2056
  hasUI: ctx.hasUI,
2070
2057
  confirm: async (title, message) => (ctx.hasUI ? ctx.ui.confirm(title, message) : Promise.resolve(false)),
2071
- editor: ctx.mode === "tui" ? (title: string, prefill?: string) => ctx.ui.editor(title, prefill) : undefined,
2072
2058
  });
2073
2059
 
2074
- const sessFor = (ctx: ExtensionContext): Session => {
2060
+ const sessFor = (ctx: ExtensionContext, root: string): Session => {
2075
2061
  const key = sessionKey(ctx);
2076
2062
  return {
2077
2063
  key,
@@ -2081,8 +2067,8 @@ export default function devFlow(pi: ExtensionAPI) {
2081
2067
  bindings.set(key, slug);
2082
2068
  pi.appendEntry("dev-flow-bind", { slug });
2083
2069
  // claims track the binding: claim what you bind, release what you drop.
2084
- if (prev && prev !== slug && readClaim(ctx.cwd, prev)?.key === key) rmSync(claimFile(ctx.cwd, prev), { force: true });
2085
- if (slug) writeClaim(ctx.cwd, slug, key);
2070
+ if (prev && prev !== slug && readClaim(root, prev)?.key === key) rmSync(claimFile(root, prev), { force: true });
2071
+ if (slug) writeClaim(root, slug, key);
2086
2072
  },
2087
2073
  rename: (slug) => {
2088
2074
  // pi's public session-name API, kept defensive: an older host without it must not fail a gate.
@@ -2097,7 +2083,7 @@ export default function devFlow(pi: ExtensionAPI) {
2097
2083
  };
2098
2084
 
2099
2085
  /** Restore this session's binding from its branch history (survives resume/fork). */
2100
- const rebuildSession = (ctx: ExtensionContext) => {
2086
+ const rebuildSession = (ctx: ExtensionContext, root: string) => {
2101
2087
  let slug: string | null = null;
2102
2088
  let sawCore = false;
2103
2089
  let coreStaleHere = false;
@@ -2122,7 +2108,7 @@ export default function devFlow(pi: ExtensionAPI) {
2122
2108
  // A reload ends the old session, which released its claim; the restored one must reclaim what its own
2123
2109
  // branch says it holds, or the repo answers "claimed by another live session" to the session that
2124
2110
  // holds it. A foreign live claim wins — restoring is not a takeover.
2125
- if (slug && readState(ctx.cwd, slug) && !claimBlocks(readClaim(ctx.cwd, slug), key)) writeClaim(ctx.cwd, slug, key);
2111
+ if (slug && readState(root, slug) && !claimBlocks(readClaim(root, slug), key)) writeClaim(root, slug, key);
2126
2112
  };
2127
2113
 
2128
2114
  /** The run's playbook preamble: the skill's always-on core, once per session. Later runs come back
@@ -2143,13 +2129,14 @@ export default function devFlow(pi: ExtensionAPI) {
2143
2129
  description: `dev-flow gates: ${GATE_HELP}`,
2144
2130
  handler: async (args, ctx) => {
2145
2131
  const cmd = parse(args);
2146
- const res = await runFlow(cmd, ctx.cwd, uiFrom(ctx), sessFor(ctx));
2132
+ const root = await flowRoot(ctx.cwd);
2133
+ const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root));
2147
2134
  // gate output belongs to the conversation, not a toast: display:true renders a [flow] box (TUI + web), no triggerTurn so no model turn fires.
2148
2135
  // bare reflect is the exception: its whole output is instructions for the agent — displayed without a turn, they would never execute.
2149
2136
  const wake = cmd.length === 1 && cmd[0] === "reflect";
2150
2137
  pi.sendMessage({ customType: "flow", content: res.text, display: true }, wake ? { triggerTurn: true } : undefined);
2151
- refreshStatus(ctx);
2152
- if (!res.isError) maybeCompactNow(ctx);
2138
+ refreshStatus(ctx, root);
2139
+ if (!res.isError) maybeCompactNow(ctx, root);
2153
2140
  },
2154
2141
  });
2155
2142
 
@@ -2162,8 +2149,9 @@ export default function devFlow(pi: ExtensionAPI) {
2162
2149
  args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug"]' }),
2163
2150
  }),
2164
2151
  execute: async (_id, params, _signal, _onUpdate, ctx) => {
2165
- const res = await runFlow(params.args, ctx.cwd, uiFrom(ctx), sessFor(ctx));
2166
- if (!res.isError) maybeCompactNow(ctx);
2152
+ const root = await flowRoot(ctx.cwd);
2153
+ const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root));
2154
+ if (!res.isError) maybeCompactNow(ctx, root);
2167
2155
  return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
2168
2156
  },
2169
2157
  });
@@ -2176,29 +2164,30 @@ export default function devFlow(pi: ExtensionAPI) {
2176
2164
  name: "flow_stage",
2177
2165
  label: "Stage worker",
2178
2166
  description:
2179
- 'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (advisory: no gate depends on it). The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Small work and small fixes are fine to do inline.',
2180
- promptSnippet: 'flow_stage(op: "implement"|"review", note, label?) — optional fresh-session worker for a big implement slice, or an independent review; gates stay with you',
2167
+ 'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (advisory: no gate depends on it). The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Small work and small fixes are fine to do inline. In pi-web the worker appears in the session\'s Agents menu as a subagent; the row carries its final status, the opened transcript its report.',
2168
+ promptSnippet: 'flow_stage(op: "implement"|"review", note, label?) — optional fresh-session worker for a big implement slice, or an independent review; gates stay with you; in pi-web workers show up as subagents in the Agents menu',
2181
2169
  parameters: Type.Object({
2182
2170
  op: Type.String({ description: '"implement" (a worker edits + commits a slice) or "review" (read-only reviewer, findings + verdict)' }),
2183
2171
  note: Type.String({ description: "The slice: what to do and anything from this conversation the worker must know (operator answers, decisions). Facts (plan path, commits, checks) are added for you." }),
2184
2172
  label: Type.Optional(Type.String({ description: "A few words naming this delegation, shown in the worker's session name." })),
2185
2173
  budgetMin: Type.Optional(Type.Number({ description: "Wall-clock budget in minutes (5-180; default 60 implement, 30 review). Past it the worker is interrupted." })),
2186
2174
  }),
2187
- execute: async (_id, params, signal, onUpdate, ctx) => {
2175
+ execute: async (id, params, signal, onUpdate, ctx) => {
2188
2176
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2189
2177
  const op = String(params.op ?? "").trim().toLowerCase();
2190
- if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2178
+ const root = await flowRoot(ctx.cwd);
2179
+ if (!initiated(root)) return err("dev-flow is not initiated here — run flow init first");
2191
2180
  const key = sessionKey(ctx);
2192
- const st = boundFeature(ctx.cwd, key);
2181
+ const st = boundFeature(root, key);
2193
2182
  if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2194
2183
  const why = workerOpError(op, st.stage);
2195
2184
  if (why) return err(why);
2196
2185
  const wop = op as WorkerOp;
2197
- const work = worktreeAbs(ctx.cwd, st);
2186
+ const work = worktreeAbs(root, st);
2198
2187
  if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk — nothing for a worker to work in`);
2199
2188
  if (runningWorkers.has(key)) return err("a worker is already running for this session — wait for it to return");
2200
2189
  runningWorkers.add(key);
2201
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2190
+ const cfg = loadProject(dfDir(root)).cfg;
2202
2191
  const budgetMin = clampBudgetMin(params.budgetMin, wop);
2203
2192
  const label = String(params.label ?? "").replace(/[\r\n]+/g, " ").trim().slice(0, 40);
2204
2193
  const glyph = wop === "implement" ? "🔨" : "🔍";
@@ -2208,15 +2197,18 @@ export default function devFlow(pi: ExtensionAPI) {
2208
2197
  const headBefore = (await git("git rev-parse HEAD")).trim();
2209
2198
  const brief = buildWorkerBrief({
2210
2199
  op: wop, slug: st.slug, workDir: work,
2211
- planFile: path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md"),
2200
+ planFile: path.join(featDir(root, st.slug), "plan", "plan.md"),
2212
2201
  defaultBranch: cfg.defaultBranch,
2213
2202
  commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
2214
2203
  status: await git("git status --short"),
2215
2204
  checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
2216
2205
  note: String(params.note ?? ""),
2217
2206
  });
2218
- let lineage: { file?: string; dir?: string } = {};
2219
- try { lineage = { file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
2207
+ let lineage: { id?: string; file?: string; dir?: string } = {};
2208
+ try { lineage = { id: ctx.sessionManager.getSessionId(), file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
2209
+ // pi-web visibility needs both halves of the lineage: the id the Agents menu links the child
2210
+ // to, the file the parentSession header points at — without either the worker stays unlinked.
2211
+ const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
2220
2212
  let child: AgentSession | undefined;
2221
2213
  let timedOut = false;
2222
2214
  let crash: string | null = null;
@@ -2227,7 +2219,8 @@ export default function devFlow(pi: ExtensionAPI) {
2227
2219
  signal?.addEventListener("abort", abortChild);
2228
2220
  let unsub: (() => void) | undefined;
2229
2221
  try {
2230
- child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir });
2222
+ child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir, subagent });
2223
+ if (subagent) piwebStamp(child.sessionManager, PIWEB_SUBAGENT.status, { version: 1, status: "running" });
2231
2224
  unsub = child.subscribe((ev: unknown) => {
2232
2225
  const e = ev as { type?: string; toolName?: string };
2233
2226
  if (e.type === "tool_execution_start") {
@@ -2256,7 +2249,20 @@ export default function devFlow(pi: ExtensionAPI) {
2256
2249
  const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
2257
2250
  const dirty = (await git("git status --short")).trim();
2258
2251
  const outcome = crash ? `crashed: ${crash}` : timedOut ? `interrupted at the ${budgetMin}-min budget` : report.found ? "reported" : `ended without REPORT after ${nudges} nudge(s)`;
2259
- try { child?.setSessionName(`${report.found && !crash && !timedOut ? "✓" : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2252
+ // the terminal entry is what settles the Agents menu row (a persisted `running` the host
2253
+ // cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a ✓.
2254
+ if (subagent) {
2255
+ const doneAt = now();
2256
+ piwebStamp(child?.sessionManager, PIWEB_SUBAGENT.result, crash
2257
+ ? { version: 1, status: "failed", completedAt: doneAt, error: crash }
2258
+ : timedOut || signal?.aborted
2259
+ ? { version: 1, status: "aborted", completedAt: doneAt }
2260
+ : report.found
2261
+ ? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
2262
+ : { version: 1, status: "failed", completedAt: doneAt, error: `ended without REPORT after ${nudges} nudge(s)`, result: report.body });
2263
+ }
2264
+ try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
2265
+ try { child?.setSessionName(`${report.found && !crash && !timedOut && !signal?.aborted ? "✓" : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2260
2266
  const parts = [
2261
2267
  `${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`,
2262
2268
  report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : `no REPORT — last words:\n${report.body}`,
@@ -2264,7 +2270,7 @@ export default function devFlow(pi: ExtensionAPI) {
2264
2270
  `uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
2265
2271
  ];
2266
2272
  if (wop === "implement") {
2267
- const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
2273
+ const check = await runFlow(["check"], root, uiFrom(ctx), sessFor(ctx, root));
2268
2274
  parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
2269
2275
  } else if (newCommits.trim() || dirty) {
2270
2276
  parts.push("note: the reviewer changed the tree — treat its verdict with suspicion and inspect the change");
@@ -2279,30 +2285,33 @@ export default function devFlow(pi: ExtensionAPI) {
2279
2285
  // Agent-run gates refresh at turn_end (tool ctx lacks setStatus; turn_end catches them).
2280
2286
  pi.on("session_start", async (_event, ctx) => {
2281
2287
  if (!guardsAreMine()) return;
2282
- rebuildSession(ctx);
2283
- refreshStatus(ctx);
2288
+ const root = await flowRoot(ctx.cwd);
2289
+ rebuildSession(ctx, root);
2290
+ refreshStatus(ctx, root);
2284
2291
  });
2285
2292
  pi.on("session_tree", async (_event, ctx) => {
2286
2293
  if (!guardsAreMine()) return;
2287
- rebuildSession(ctx);
2294
+ rebuildSession(ctx, await flowRoot(ctx.cwd));
2288
2295
  });
2289
2296
  // The session, not the process, owns the binding and the claim: pi-web keeps serving other sessions
2290
2297
  // after one ends, and a stale claim there is a permanent lock (its pid is the server's, always alive).
2291
2298
  pi.on("session_shutdown", async (_event, ctx) => {
2292
2299
  if (!guardsAreMine()) return;
2293
- if (!existsSync(dfDir(ctx.cwd))) return;
2294
- releaseSession(ctx.cwd, sessionKey(ctx));
2300
+ const root = await flowRoot(ctx.cwd);
2301
+ if (!existsSync(dfDir(root))) return;
2302
+ releaseSession(root, sessionKey(ctx));
2295
2303
  });
2296
2304
  pi.on("turn_end", async (_event, ctx) => {
2297
2305
  if (!guardsAreMine()) return;
2298
- refreshStatus(ctx);
2306
+ const root = await flowRoot(ctx.cwd);
2307
+ refreshStatus(ctx, root);
2299
2308
  // pi checks its compaction threshold between every turn; our safe points must be as frequent.
2300
- maybeCompactNow(ctx);
2309
+ maybeCompactNow(ctx, root);
2301
2310
  });
2302
2311
  // Idle backstop: long between-gate runs compact here instead of letting pi hit the threshold mid-work.
2303
2312
  pi.on("agent_settled", async (_event, ctx) => {
2304
2313
  if (!guardsAreMine()) return;
2305
- maybeCompactNow(ctx);
2314
+ maybeCompactNow(ctx, await flowRoot(ctx.cwd));
2306
2315
  });
2307
2316
  // pi forcing a threshold compaction while a flow is bound means our safe-point pacing missed — rebuild the
2308
2317
  // summary here with flow-aware instructions and hand it back through the event's custom-compaction channel.
@@ -2312,9 +2321,10 @@ export default function devFlow(pi: ExtensionAPI) {
2312
2321
  // overflow is never taken over (cancelling it would drop pi's compact-and-retry); manual is the operator's or ours.
2313
2322
  pi.on("session_before_compact", async (event, ctx) => {
2314
2323
  if (!guardsAreMine()) return undefined;
2315
- if (!initiated(ctx.cwd)) return undefined;
2324
+ const root = await flowRoot(ctx.cwd);
2325
+ if (!initiated(root)) return undefined;
2316
2326
  const key = sessionKey(ctx);
2317
- const st = boundFeature(ctx.cwd, key);
2327
+ const st = boundFeature(root, key);
2318
2328
  if (!shouldTakeOverCompaction({ reason: event.reason, bound: !!st, inFlight: compacting.has(key) })) return undefined;
2319
2329
  const model = ctx.model;
2320
2330
  if (!model) return undefined;
@@ -2333,24 +2343,15 @@ export default function devFlow(pi: ExtensionAPI) {
2333
2343
  compacting.delete(key);
2334
2344
  }
2335
2345
  });
2336
- // pi forcing its own compaction while a flow is bound means the pacing was wrong — park a note for the operator.
2337
- pi.on("session_compact", async (event, ctx) => {
2346
+ // Whatever the reason, the summary replaced the transcript — the core the first run injected is gone
2347
+ // from context, so the next run pays it once more (manual compactions included: our own safe-point
2348
+ // compaction is the common one). Durable too: a branch whose newest skill entry is stale tells a
2349
+ // reloaded session to pay the core again.
2350
+ pi.on("session_compact", async (_event, ctx) => {
2338
2351
  if (!guardsAreMine()) return;
2339
- if (!initiated(ctx.cwd)) return;
2340
- // Whatever the reason, the summary replaced the transcript — the core the first run injected is
2341
- // gone from context, so the next run pays it once more (manual compactions included: our own
2342
- // safe-point compaction is the common one).
2352
+ if (!initiated(await flowRoot(ctx.cwd))) return;
2343
2353
  coreStale.add(sessionKey(ctx));
2344
- // Durable too: a compaction the session survives a reload outlives the in-memory flag, and a
2345
- // branch whose newest skill entry is stale tells the restored run to pay the core again.
2346
2354
  pi.appendEntry("dev-flow-skill", { core: true, stale: true });
2347
- if (event.reason === "manual") return;
2348
- const st = boundFeature(ctx.cwd, sessionKey(ctx));
2349
- if (!st) return;
2350
- const f = path.join(dfDir(ctx.cwd), "reflections.md");
2351
- const text = existsSync(f) ? readFileSync(f, "utf8") : "";
2352
- const line = compactionReflectionLine(st.slug, st.stage, event.reason, new Date().toISOString().slice(0, 10));
2353
- writeFileSync(f, appendReflection(text, ["plugin"], line));
2354
2355
  });
2355
2356
 
2356
2357
  pi.on("tool_call", async (event, ctx) => {
@@ -2389,15 +2390,8 @@ export default function devFlow(pi: ExtensionAPI) {
2389
2390
  if (why) return { block: true, reason: why };
2390
2391
  }
2391
2392
  const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd });
2392
- if (reason) return { block: true, reason };
2393
- // Editing a worktree invalidates that feature's tier-1 checks and tier-2 confirmation until they rerun.
2394
- const owner = feats.find((f) => f.worktreeAbs && abs.startsWith(f.worktreeAbs + path.sep));
2395
- if (owner && (owner.state.stage === "implement" || owner.state.stage === "pre-release") && (Object.keys(owner.state.checks).length || owner.state.confirmations?.implement)) {
2396
- owner.state.checks = {};
2397
- delete owner.state.confirmations?.implement;
2398
- writeState(guardRoot, owner.state);
2399
- }
2400
- return undefined;
2393
+ // a stale green is caught where it matters: verify and release fingerprint the worktree (freshenChecks)
2394
+ return reason ? { block: true, reason } : undefined;
2401
2395
  }
2402
2396
 
2403
2397
  if (isToolCallEventType("bash", event)) {
@@ -2480,15 +2474,13 @@ export default function devFlow(pi: ExtensionAPI) {
2480
2474
  if (reason) return { block: true, reason };
2481
2475
  // A feature worktree stays on its feature branch: a side branch cut inside it repurposes the
2482
2476
  // worktree (and leaves it off its branch for the next gate); out-of-flow fixes get their own flow.
2483
- const created = branchCreateTarget(g.seg);
2477
+ const co = checkoutInvocation(g.seg);
2478
+ if (!co) continue;
2484
2479
  const homeWt = worktrees.find((w) => gitDir === w || gitDir.startsWith(w + path.sep));
2485
- if (created && homeWt) return { block: true, reason: `a feature worktree stays on its own branch — not creating ${created} in ${homeWt}; an unrelated fix is its own flow (flow start <slug> --patch --confirmed)` };
2480
+ if (co.creates && homeWt) return { block: true, reason: `a feature worktree stays on its own branch — not creating ${co.target} in ${homeWt}; an unrelated fix is its own flow (flow start <slug> --patch --confirmed)` };
2486
2481
  // Branch discipline: feature branches live in their worktree — never checked out or created (-b) in the main checkout
2487
- const target = checkoutTarget(g.seg);
2488
- if (target && target.startsWith(featureBranchPrefix(cfg))) {
2489
- const inWorktree = worktrees.some((w) => gitDir === w || gitDir.startsWith(w + path.sep));
2490
- if (!inWorktree) return { block: true, reason: `branch ${target} belongs to a feature worktree, not the main checkout — flow use <slug> and run git inside ${featureBranchPrefix(cfg)}…'s worktree` };
2491
- }
2482
+ if (!homeWt && co.target.startsWith(featureBranchPrefix(cfg)))
2483
+ return { block: true, reason: `branch ${co.target} belongs to a feature worktree, not the main checkout — flow use <slug> and run git inside ${featureBranchPrefix(cfg)}…'s worktree` };
2492
2484
  }
2493
2485
  }
2494
2486
  return undefined;
@@ -2496,34 +2488,34 @@ export default function devFlow(pi: ExtensionAPI) {
2496
2488
 
2497
2489
  pi.on("before_agent_start", async (_event, ctx) => {
2498
2490
  if (!guardsAreMine()) return undefined;
2499
- // One [dev-flow] line per run, whatever number of copies of this package are installed.
2500
- // The same package reaches one runtime twice all the time (a project pin beside the npm install,
2501
- // or this checkout's .pi/extensions pointer beside it) and pi dedupes extensions by file path
2502
- // only, so both copies answer and the line lands twice in the prompt. pi hands every handler of
2503
- // a run the same ctx object, so the first pass claims the run and the rival stays silent.
2491
+ // One [dev-flow] line per run, whatever number of copies of this package are installed. The same
2492
+ // package can reach one runtime twice (a project pin beside the npm install) and pi dedupes
2493
+ // extensions by file path only; equal-version copies both pass the election, so the first pass
2494
+ // claims the run (pi hands every handler of a run the same ctx object) and the rival stays silent.
2504
2495
  const run = ctx as unknown as Record<symbol, boolean | undefined>;
2505
2496
  if (run[CONTEXT_EMITTED]) return undefined;
2506
2497
  run[CONTEXT_EMITTED] = true;
2507
2498
  // repaint the footer at the start of every run: the session_start push can land before a web
2508
2499
  // client attaches, and this is the earliest point the client is certainly listening
2509
- refreshStatus(ctx);
2510
- if (!initiated(ctx.cwd)) return undefined;
2500
+ const root = await flowRoot(ctx.cwd);
2501
+ refreshStatus(ctx, root);
2502
+ if (!initiated(root)) return undefined;
2511
2503
  try { if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined; } catch { /* not a worker */ }
2512
2504
  const key = sessionKey(ctx);
2513
2505
  // The playbook core rides along on the message this run writes anyway — once per session.
2514
2506
  const core = corePreamble(key);
2515
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2516
- const state = boundFeature(ctx.cwd, key);
2517
- if (!state || state.stage === "done") {
2507
+ const cfg = loadProject(dfDir(root)).cfg;
2508
+ const state = boundFeature(root, key);
2509
+ if (!state) {
2518
2510
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
2519
2511
  let content = "[dev-flow] no flow bound. Every request goes through flow. New work: flow start <slug>; unfinished feature: flow use <slug>.";
2520
- const cb = claimBlocker(ctx.cwd, key);
2512
+ const cb = claimBlocker(root, key);
2521
2513
  if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (pid ${cb.claim.pid}) — flow use ${cb.state.slug} takes it over explicitly.`;
2522
- const curBr = await currentBranch(ctx.cwd);
2514
+ const curBr = await currentBranch(root);
2523
2515
  if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
2524
- const refl0 = readReflections(ctx.cwd);
2516
+ const refl0 = readReflections(root);
2525
2517
  if (refl0.length) content += ` Also: ${refl0.length} reflection(s) open — run flow doctor.`;
2526
- const rmap0 = roadmapOpenCount(readRoadmap(ctx.cwd));
2518
+ const rmap0 = roadmapOpenCount(readRoadmap(root));
2527
2519
  if (rmap0) content += ` Also: ${rmap0} roadmap item(s) open — flow roadmap lists them, flow roadmap pick <n> <slug> hands one to flow start.`;
2528
2520
  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).`;
2529
2521
  return { message: { customType: "dev-flow-context", display: false, content: `${core}${content}` } };
@@ -2539,9 +2531,9 @@ export default function devFlow(pi: ExtensionAPI) {
2539
2531
  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.");
2540
2532
  const pend = checklistPending(cfg, state, state.stage);
2541
2533
  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" : ""}`);
2542
- const refl = readReflections(ctx.cwd);
2534
+ const refl = readReflections(root);
2543
2535
  if (refl.length) guidance.push(`↻ ${refl.length} reflection(s) open — mention to the operator; run flow doctor to review and route them (fold in only on request).`);
2544
- const rmap = roadmapOpenCount(readRoadmap(ctx.cwd));
2536
+ const rmap = roadmapOpenCount(readRoadmap(root));
2545
2537
  if (rmap) guidance.push(`◇ ${rmap} roadmap item(s) open — flow roadmap lists them (pick only on the operator's word).`);
2546
2538
  return {
2547
2539
  message: {