pi-dev-flow 0.72.0 → 0.74.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.
@@ -20,13 +20,10 @@
20
20
  * Inactive (fully pass-through) in repos without a .dev-flow/ directory.
21
21
  */
22
22
  import { exec } from "node:child_process";
23
- import { createHash } from "node:crypto";
24
- import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
25
- import { open as openFile, readdir as readdirAsync, readFile as readFileAsync, stat as statAsync } from "node:fs/promises";
23
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
26
24
  import path from "node:path";
27
25
  import { promisify } from "node:util";
28
26
  import { Type } from "@earendil-works/pi-ai";
29
- import { Container, Text } from "@earendil-works/pi-tui";
30
27
  import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
31
28
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32
29
  import {
@@ -36,33 +33,18 @@ import {
36
33
  appendReflection,
37
34
  appendRoadmapItem,
38
35
  bashFlowGuard,
39
- buildStageBrief,
40
36
  checkFingerprint,
41
37
  changelogVersionsBetween,
42
- familyFoldLine,
43
- familyHeading,
44
38
  normalizeReleaseBody,
45
39
  pendingEntryLines,
46
40
  pickReleaseNotes,
47
- parseStageReport,
48
- renderStageReport,
49
41
  checklistHash,
50
42
  checklistPending,
51
- DELEGATIONS_FILE,
52
- STAGE_SESSIONS_DIR,
53
- delegationErrors,
54
- delegationLine,
55
- parseDelegationLedger,
56
- mainCheckoutRoot,
57
- type DelegationWindow,
58
- checkoutTarget,
43
+ checkoutInvocation,
59
44
  claimBlocks,
60
- clampStageBudgetMin,
61
45
  classifyMergeHistory,
62
46
  cmpVersions,
63
- cleanupAssess,
64
- closedReflectionCount,
65
- compactionReflectionLine,
47
+ doneItemCount,
66
48
  detectForge,
67
49
  extractSkillCore,
68
50
  featureBranchPrefix,
@@ -73,8 +55,6 @@ import {
73
55
  gateHelpJson,
74
56
  gitInvocation,
75
57
  githubSlug,
76
- DELEGABLE_STAGES,
77
- isDelegableStage,
78
58
  guardBash,
79
59
  guardPath,
80
60
  healthProbe,
@@ -110,63 +90,16 @@ import {
110
90
  newState,
111
91
  nextHint,
112
92
  openChecklistItems,
113
- openReflections,
114
93
  releaseGate,
115
94
  parseVersion,
116
95
  roadmapDone,
117
- roadmapDoneCount,
118
96
  roadmapDoneForSlug,
119
97
  roadmapOpenCount,
120
98
  roadmapPick,
121
99
  roadmapTidy,
122
100
  shouldSelfCompact,
123
101
  shouldTakeOverCompaction,
124
- TRANSCRIPTS_FILE,
125
- stageCardLines,
126
- stageElapsedLabel,
127
102
  stageGuidance,
128
- stageInterruptSteer,
129
- stageLiveAssistantLine,
130
- stageLiveLine,
131
- stageLiveResultLine,
132
- stageUsageLine,
133
- summarizeToolArgs,
134
- VERIFY_STAMP,
135
- VERIFY_STAMP_REFUSAL,
136
- WORKER_OP_BUDGET_MIN,
137
- WORKER_OP_GLYPH,
138
- WORKER_OP_TOOLS,
139
- type StageUsage,
140
- type WorkerOp,
141
- buildReflectBrief,
142
- buildVerifyBrief,
143
- isWorkerOp,
144
- liveClip,
145
- liveTail,
146
- parseReflectFindings,
147
- parseVerifyReport,
148
- parseWorkerTranscripts,
149
- planFingerprint,
150
- recordVerifyPass,
151
- renderVerifyReport,
152
- verifyStampMissing,
153
- sessionPathKey,
154
- sessionHeaderParent,
155
- parseSessionSummary,
156
- markWorkerSession,
157
- isWorkerSession,
158
- orphanWorktreeBuckets,
159
- claimAge,
160
- processStart,
161
- type WorktreeBucketFeature,
162
- workerFamily,
163
- workerFamilyCount,
164
- WORKER_FAMILY_ITEMS,
165
- workerOpError,
166
- workerTranscriptLine,
167
- type WorkerSessionRow,
168
- workerName,
169
- sanitizeWorkerLabel,
170
103
  stateTamper,
171
104
  statusFor,
172
105
  statusJson,
@@ -177,6 +110,15 @@ import {
177
110
  verifyGate,
178
111
  versionTagGate,
179
112
  writeGuard,
113
+ mainCheckoutRoot,
114
+ buildWorkerBrief,
115
+ clampBudgetMin,
116
+ parseWorkerReport,
117
+ workerOpError,
118
+ WORKER_NUDGE,
119
+ WORKER_NUDGES,
120
+ type WorkerOp,
121
+ releaseOrderInvocation,
180
122
  type BranchState,
181
123
  type Config,
182
124
  type FeatureRef,
@@ -184,7 +126,6 @@ import {
184
126
  type StageCheck,
185
127
  type PushRef,
186
128
  type SessionClaim,
187
- type DelegableStage,
188
129
  } from "../src/core.ts";
189
130
  import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
190
131
  import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
@@ -215,6 +156,14 @@ function checkoutBuild(root: string): { version: string | null; dir: string; rep
215
156
  : { ...SELF_BUILD, label: "the dev-flow install" };
216
157
  }
217
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
+
218
167
  /** Cross-copy registry: one process can register dev-flow more than once (the documented
219
168
  * two-sources-at-once hazard: a project dogfood pointer plus an installed copy), and EVERY copy
220
169
  * evaluates every guard hook. The flow-tool binding belongs to whichever copy served the call,
@@ -257,19 +206,11 @@ function copyWarning(): string | null {
257
206
  }
258
207
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
259
208
  * entries and asserts the warnings the real duplicate would print. */
260
- export const testSeams = {
261
- copies: COPIES,
262
- skillCore: { value: undefined as string | null | undefined },
263
- /** Where `flow doctor` looks for pi's session buckets; tests point it at a scratch dir so the suite
264
- * never reads the operator's real session store. `undefined` = `<agent dir>/sessions`. */
265
- sessionsRoot: { value: undefined as string | null | undefined },
266
- };
209
+ export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined } };
267
210
 
268
211
  interface Ui {
269
212
  hasUI: boolean;
270
213
  confirm: (title: string, message: string) => Promise<boolean>;
271
- /** Multi-line review/edit dialog where the client has one (TUI); undefined elsewhere. */
272
- editor?: (title: string, prefill?: string) => Promise<string | undefined>;
273
214
  }
274
215
 
275
216
  const now = () => new Date().toISOString();
@@ -286,6 +227,27 @@ async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000): Promis
286
227
  }
287
228
  }
288
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
+
289
251
  const dfDir = (root: string) => path.join(root, ".dev-flow");
290
252
  /** dev-flow is initiated once the operator playbook exists: before flow init writes project.md the
291
253
  * extension is silent in that folder — no injections, no guards (not even the no-playbook bash-timeout
@@ -387,14 +349,14 @@ async function runHealthProbe(cmd: string, cwd: string, waitSec: number): Promis
387
349
  * decide what is already tagged (#52). Local tags only when there is no remote to ask; null when an
388
350
  * origin exists but could not be asked (offline, no ssh agent) — then local tags must not stand in. */
389
351
  async function releaseTags(root: string): Promise<string[] | null> {
390
- 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);
391
353
  const remote = await sh("git ls-remote --tags origin", root);
392
354
  if (!remote.ok) return null;
393
355
  return parseLsRemoteTags(remote.out);
394
356
  }
395
357
 
396
358
  const GATE_HELP =
397
- "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] [--force] [--patch|--docs --confirmed] [--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); --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)";
398
360
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
399
361
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
400
362
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -415,8 +377,7 @@ function writeState(root: string, state: FlowState): void {
415
377
  * truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
416
378
  * and every recorded check, with the folder gitignored so nothing else could restore it. */
417
379
  function atomicWrite(file: string, text: string): void {
418
- // per-process temp name: two sessions writing the same file must not rename each other's half-write
419
- const tmp = `${file}.${process.pid}.tmp`;
380
+ const tmp = `${file}.tmp`;
420
381
  writeFileSync(tmp, text);
421
382
  renameSync(tmp, file);
422
383
  }
@@ -440,9 +401,8 @@ const compacting = new Set<string>();
440
401
  const coreInjected = new Set<string>();
441
402
  /** Sessions whose last compaction dropped the core out of context — the next run pays it once more. */
442
403
  const coreStale = new Set<string>();
443
- /** The skill dir of THIS loaded copy. Since 0.57.1 dropped the `.pi/extensions` dogfood shim, the
444
- * copy a session runs and a development checkout are different installs, so playbook paths
445
- * 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. */
446
406
  const SKILL_DIR = path.join(import.meta.dirname, "..", "skills", "dev-flow");
447
407
  let skillCoreCache: string | null | undefined;
448
408
  /** The core block between SKILL.md's markers, read once per process (/reload reloads the module
@@ -464,192 +424,16 @@ function skillCore(): string | null {
464
424
  /** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
465
425
  export const compactionTakeover: { run: typeof compact } = { run: compact };
466
426
 
467
- /** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
468
- * `.run` with a stub, so the worker contract stays testable without spending a model and tests
469
- * never touch the real session directory. The real spawn stamps lineage: the worker's header
470
- * carries `parentSession` → the driver's own session file, and its transcript goes into the
471
- * driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
472
- * scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
473
- * as /handoff can do the same"). The live ⏳ name is written straight onto the session before its
474
- * first prompt: pi emits `session_start` only from `bindExtensions()`, which an SDK-created worker
475
- * never runs, so a name set from a `session_start` handler never lands — every worker used to run
476
- * under whatever an auto-namer derived from its brief ("you-are-a-dev"). Named before the prompt,
477
- * an auto-namer sees a name that is not its own and leaves it alone. The same channel carries the
478
- * ⏳ → ✓/✗ rename. The worker is also registered as a worker, so the dev-flow copy its loader runs
479
- * keeps its guards but injects none of the driver's context (see `isWorkerSession`). */
480
-
481
- export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
482
-
483
- /** The worker's session manager, built exactly as the real seam builds it — split out so a test can
484
- * drive the production composition (header link + driver's bucket) without spawning a model.
485
- * Both or neither: `dir` is the driver's own bucket read off the live manager, so a custom
486
- * PI_CODING_AGENT_DIR can never strand a worker in a different agent dir from its driver, and pi's
487
- * private `--<encoded cwd>--` directory encoding is never duplicated here. */
488
- export function workerSessionManager(work: string, parent?: string, dir?: string): SessionManager | undefined {
489
- return parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
490
- }
491
-
492
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
493
- run: async ({ work, model, name, tools, parent, dir }) => {
494
- const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
495
- await loader.reload();
496
- const sessionManager = workerSessionManager(work, parent, dir);
497
- const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
498
- // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
499
- // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
500
- // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
501
- try { markWorkerSession(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the driver context */ }
502
- const rename = (n: string) => { try { session.setSessionName(n); } catch { /* naming is visibility, not function */ } };
503
- rename(name);
504
- return { session, rename };
505
- },
506
- };
507
-
508
- /** Seam that reads the driver's session bucket the way the picker does — a stub in the smoke suite,
509
- * because a test must not scan the operator's real session directory. `listAll(dir)`, not
510
- * `list(cwd, dir)`: pi's `list` drops rows whose header cwd is not `cwd` whenever it is handed a
511
- * directory that is not that cwd's default — which is precisely a stage worker (header cwd = the
512
- * worktree, file in the driver's bucket), and precisely the layout a configured `sessionDir`
513
- * creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
514
- * the family list and the tree agree there; under a configured session dir the text view stays
515
- * complete even where that scope hides the worker, which is the cheaper direction to err in. */
516
- export const sessionRowsScan: { run: (o: { cwd: string; dir?: string; parent?: string }) => Promise<WorkerSessionRow[]> } = {
517
- run: async ({ dir, parent }) => {
518
- // no bucket or no driver file to match: the old full listing (a host that never reaches here in practice)
519
- if (!dir || !parent) return (await SessionManager.listAll(dir)).map((s) => ({ path: s.path, parent: s.parentSessionPath, name: s.name, messageCount: s.messageCount, modified: s.modified }));
520
- return scanFamilyRows(dir, parent);
521
- },
522
- };
523
-
524
- /** Header bytes read per transcript in the family scan's cheap pass — the same budget pi gives its own
525
- * header reads. A pi header line is a few hundred bytes. */
526
- const SESSION_HEADER_BYTES = 4096;
527
-
528
- /** The family read in two passes, so its cost follows the family, not the bucket: the first line of
529
- * every transcript (≤ 4 KB each) names its parent; only the files whose parent is `parent` are read
530
- * in full. `listAll(dir)` parsed every transcript in the bucket — ~15 ms per MB, and a driver bucket
531
- * only grows (the dev-flow checkout's was 55 MB, ~0.8 s for every idle status and settled card).
532
- * `fullReads` counts the second pass for the smoke suite. */
533
- export async function scanFamilyRows(dir: string, parent: string, fullReads?: { n: number }): Promise<WorkerSessionRow[]> {
534
- let names: string[];
535
- try { names = (await readdirAsync(dir)).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
536
- const want = sessionPathKey(parent);
537
- const rows: WorkerSessionRow[] = [];
538
- await Promise.all(names.map(async (n) => {
539
- const file = path.join(dir, n);
540
- let head = "";
541
- try {
542
- const fh = await openFile(file, "r");
543
- try {
544
- const buf = Buffer.alloc(SESSION_HEADER_BYTES);
545
- const { bytesRead } = await fh.read(buf, 0, SESSION_HEADER_BYTES, 0);
546
- head = buf.subarray(0, bytesRead).toString("utf8");
547
- } finally { await fh.close(); }
548
- } catch { return; }
549
- const p = sessionHeaderParent(head);
550
- if (!p || sessionPathKey(p) !== want) return;
551
- try {
552
- if (fullReads) fullReads.n++;
553
- const [text, st] = await Promise.all([readFileAsync(file, "utf8"), statAsync(file)]);
554
- const row = parseSessionSummary(text, file, st.mtimeMs);
555
- if (row) rows.push(row);
556
- } catch { /* a transcript deleted mid-scan is simply not in the family */ }
557
- }));
558
- return rows;
559
- }
560
-
561
- /** Where this session's own transcripts live, when it has any: the file the worker links to, and the
562
- * bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
563
- * which is a fact to print, never an error to raise. */
564
- function lineageOf(ctx: ExtensionContext): { file: string | null; dir: string | null } {
565
- try {
566
- return { file: ctx.sessionManager.getSessionFile() ?? null, dir: ctx.sessionManager.getSessionDir() ?? null };
567
- } catch { /* an in-memory or otherwise unbacked session says so here */ return { file: null, dir: null }; }
568
- }
569
-
570
- /** With no file-backed lineage to read — an unbacked host, or a driver pi never wrote a file for —
571
- * the ledger is what the flow knows: every worker it recorded, newest first. Coarser than the
572
- * picker's data (no message count, no rename), so the status heading names the source. */
573
- function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
574
- try {
575
- const drop = exclude ? sessionPathKey(exclude) : null;
576
- const mine = parseWorkerTranscripts(readFileSync(logPath, "utf8")).filter((r) => !drop || sessionPathKey(r.path) !== drop);
577
- const shown = mine.slice(-WORKER_FAMILY_ITEMS).reverse().map((r) => `${r.op} · ${r.at} · ${r.path}`);
578
- return mine.length > shown.length ? [...shown, familyFoldLine(mine.length - shown.length)] : shown;
579
- } catch { return []; }
580
- }
581
-
582
- /** Bucket reads are the one IO-bound thing the family view does: one header read per transcript in
583
- * the driver's bucket, plus a full read of each worker (`scanFamilyRows`). A host renders a running
584
- * worker by calling status repeatedly, so that path is allowed a slightly stale read; the places the
585
- * operator draws a conclusion from — idle status, the settled card — always re-read. */
586
- const BUCKET_FRESH_MS = 2000;
587
- const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
588
-
589
- async function bucketRows(ctx: ExtensionContext, dir: string | null, parent: string, staleMs = 0) {
590
- const key = `${dir ?? "(default bucket)"}\0${parent}`;
591
- const hit = bucketCache.get(key);
592
- // staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
593
- // and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
594
- // condition also holds inside the caller's own millisecond, and a fast host got the previous read back
595
- // as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
596
- // as the call before it printed the family that had just gone empty).
597
- if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
598
- const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined, parent });
599
- if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
600
- bucketCache.set(key, { at: Date.now(), rows });
601
- return rows;
602
- }
603
-
604
- /** The flow's workers as lines, newest first — `null` when this session has no file to be a parent of,
605
- * which is when the caller reaches for `ledgerFamilyLines` instead.
606
- * Deliberately read from the picker's own data, not from a dev-flow index: renames, deletions and
607
- * workers an older session already delegated all read back correctly for free. `exclude` drops one
608
- * transcript: the caller already shows that run, and meeting it again as an anonymous row under
609
- * "other workers" reads like somebody else's work belongs to this flow. */
610
- async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleMs = 0): Promise<string[] | null> {
611
- const { file, dir } = lineageOf(ctx);
612
- if (!file) return null;
613
- try {
614
- return workerFamily(await bucketRows(ctx, dir, file, staleMs), file, { exclude });
615
- } catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
616
- }
617
-
618
- /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
619
- export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
620
-
621
-
622
- /** What a live worker run knows about itself — the one-worker-per-session guard and the ledger the
623
- * `op: "status"` verb reads. `lastLines` mirrors the live log (bounded); usage and turns accumulate
624
- * per run so the card and the result can say what the worker cost. */
625
- interface StageRun {
626
- startedAt: number;
627
- budgetMin: number;
628
- softFired: boolean;
629
- work: string;
630
- lastLines: string[];
631
- op: WorkerOp;
632
- /** "🔨 implement" / "🔍 verify" (+ ` · label`) — how the card and the beats name the run; session names use workerName instead. */
633
- kind: string;
634
- slug: string;
635
- usage: StageUsage;
636
- turns: number;
637
- /** the live worker's own session file, once spawned — a family listing leaves it out rather than
638
- * meeting the run twice: once as the run, once as an unlabeled row under "other workers". */
639
- transcript?: string;
640
- }
641
-
642
- const stageRuns = new Map<string, StageRun>();
643
-
644
427
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
645
428
  const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
646
429
 
430
+ /** Every feature with a state file — finish deletes the state, so whatever is on disk is unfinished. */
647
431
  function unfinishedStates(root: string): FlowState[] {
648
432
  if (!existsSync(dfDir(root))) return [];
649
433
  return readdirSync(dfDir(root), { withFileTypes: true })
650
434
  .filter((d) => d.isDirectory())
651
435
  .map((d) => readState(root, d.name))
652
- .filter((s): s is FlowState => !!s && s.stage !== "done");
436
+ .filter((s): s is FlowState => !!s);
653
437
  }
654
438
 
655
439
  /** Open items of the agent's suggestion queue (.dev-flow/reflections.md), each with its section. */
@@ -680,7 +464,7 @@ function boundFeature(root: string, key: string): FlowState | null {
680
464
  const bound = bindings.get(key);
681
465
  if (bound) {
682
466
  const s = readState(root, bound);
683
- if (s && s.stage !== "done") return s;
467
+ if (s) return s;
684
468
  }
685
469
  return unfinishedStates(root).find((s) => readClaim(root, s.slug)?.key === key) ?? null;
686
470
  }
@@ -694,13 +478,7 @@ function readClaim(root: string, slug: string): SessionClaim | null {
694
478
  }
695
479
 
696
480
  const writeClaim = (root: string, slug: string, key: string) =>
697
- atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now(), start: processStart(process.pid) })}\n`);
698
-
699
- /** "pid 854, claim 3 days old" — the age is what tells a live session from a recycled pid. */
700
- const claimWho = (claim: SessionClaim): string => {
701
- const age = claimAge(claim);
702
- return `pid ${claim.pid}${age ? `, claim ${age}` : ""}`;
703
- };
481
+ atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
704
482
 
705
483
  /** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
706
484
  * never dies, so a claim left behind by a finished session keeps refusing every later session with
@@ -736,12 +514,12 @@ const flowCompactInstructions = (st: FlowState) =>
736
514
  * (computed with the *effective* reserveTokens — settings + model overrides, like pi does) and
737
515
  * never while chat-only state is pending (open dialog, undigested plan) — see shouldSelfCompact.
738
516
  */
739
- function maybeCompactNow(ctx: ExtensionContext): void {
740
- if (!initiated(ctx.cwd)) return;
517
+ function maybeCompactNow(ctx: ExtensionContext, root: string): void {
518
+ if (!initiated(root)) return;
741
519
  const u = ctx.getContextUsage?.(); // minimal/fake contexts may lack usage info — treat as unknown
742
520
  if (!u || u.tokens === null) return;
743
521
  const key = sessionKey(ctx);
744
- const st = boundFeature(ctx.cwd, key);
522
+ const st = boundFeature(root, key);
745
523
  if (!st) return;
746
524
  let reserve: number;
747
525
  try {
@@ -751,27 +529,23 @@ function maybeCompactNow(ctx: ExtensionContext): void {
751
529
  } catch {
752
530
  return;
753
531
  }
754
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
532
+ const cfg = loadProject(dfDir(root)).cfg;
755
533
  const decision = {
756
534
  tokens: u.tokens,
757
535
  contextWindow: u.contextWindow,
758
536
  stage: st.stage,
759
- planFiles: listFiles(path.join(featDir(ctx.cwd, st.slug), "plan")).length,
537
+ planFiles: listFiles(path.join(featDir(root, st.slug), "plan")).length,
760
538
  checklistPending: checklistPending(cfg, st, st.stage),
761
539
  compacting: compacting.has(key),
762
540
  };
763
541
  if (!shouldSelfCompact(decision, reserve)) return;
764
- compacting.add(key);
765
- const done = () => compacting.delete(key);
766
- try {
767
- ctx.compact({
768
- customInstructions: flowCompactInstructions(st),
769
- onComplete: done,
770
- onError: done,
771
- });
772
- } catch {
773
- 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
774
- }
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
+ }
775
549
  }
776
550
 
777
551
  function featureRefs(root: string): FeatureRef[] {
@@ -813,13 +587,6 @@ async function gitConsistency(root: string, cfg: Config): Promise<string[]> {
813
587
 
814
588
  /** Where feature commands run: the feature worktree once it exists (that is where the
815
589
  * code under test lives), else the main checkout. Keeps gates off the main branch. */
816
-
817
- /** Lines the current project.md has that a regenerated draft cannot reproduce. */
818
- function droppableLines(current: string, draft: string): string[] {
819
- const keep = new Set(draft.split("\n").map((l) => l.trim()).filter(Boolean));
820
- return current.split("\n").map((l) => l.trim()).filter((l) => l && !keep.has(l));
821
- }
822
-
823
590
  function gateCwd(root: string, state: FlowState): string {
824
591
  const wt = worktreeAbs(root, state);
825
592
  return wt && existsSync(wt) ? wt : root;
@@ -839,18 +606,17 @@ async function runChecks(root: string, state: FlowState, cfg: Config, checks: St
839
606
  let failed = false;
840
607
  const ran: string[] = [];
841
608
  for (const c of checks) {
842
- if (c.name === "health" && cfg.commands.seedData) {
843
- const seed = await sh(cfg.commands.seedData, gateCwd(root, state));
844
- if (!seed.ok) {
845
- lines.push(`seedData FAILED:\n${tail(seed.out)}`);
846
- failed = true;
847
- break;
848
- }
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;
849
615
  }
850
- const res = await sh(c.cmd, gateCwd(root, state));
851
616
  state.checks[c.name] = { ok: res.ok, at: now() };
852
617
  ran.push(c.name);
853
- 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)}`}`);
854
620
  if (!res.ok) failed = true;
855
621
  }
856
622
  await stampChecks(root, state, ran);
@@ -872,6 +638,27 @@ async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{
872
638
  return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
873
639
  }
874
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
+
875
662
  /** Fingerprint of the working-tree state the checks ran against: paths (`status --porcelain`),
876
663
  * tracked content (a hash of the uncommitted diff) and HEAD. Null when git cannot answer — a
877
664
  * measurement failure must never mark a green record stale (see freshenChecks). */
@@ -884,26 +671,6 @@ async function worktreeFingerprint(cwd: string): Promise<string | null> {
884
671
  return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
885
672
  }
886
673
 
887
- /** The fingerprint a verify PASS belongs to: the worktree's, hashed TOGETHER WITH the feature's plan/
888
- * dir — the checker read the plan too, so a mid-stage plan edit voids its verdict exactly like a code
889
- * edit. null = git could not answer (same fingerprintless-stamp rule as tier-1 records). */
890
- async function verifyStampFingerprint(root: string, st: FlowState): Promise<string | null> {
891
- const base = await worktreeFingerprint(gateCwd(root, st));
892
- if (!base) return null;
893
- return createHash("sha256").update(`${base}\n${planFingerprint(path.join(root, ".dev-flow", st.slug, "plan"))}`).digest("hex").slice(0, 16);
894
- }
895
-
896
- /** Drop a PASS whose worktree-or-plan fingerprint no longer matches; true if one was dropped. Every
897
- * reader of the stamp (the verify gate, and the check/status views that must not keep advertising a
898
- * dead PASS) runs this before trusting the record. */
899
- async function voidStaleVerifyStamp(root: string, st: FlowState): Promise<boolean> {
900
- if (!st.checks[VERIFY_STAMP]) return false;
901
- const vfp = await verifyStampFingerprint(root, st);
902
- if (!vfp || st.checks[VERIFY_STAMP]!.wt === vfp) return false;
903
- delete st.checks[VERIFY_STAMP];
904
- return true;
905
- }
906
-
907
674
  /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
908
675
  * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
909
676
  async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
@@ -928,54 +695,6 @@ async function branchState(cwd: string, defaultBranch: string): Promise<BranchSt
928
695
  };
929
696
  }
930
697
 
931
- /** The branch's merge base with the default branch, or "" when git cannot answer (no such ref, a
932
- * shallow clone). Callers read "" as "unprovable", never as "nothing ahead". Local refs only —
933
- * the same offline-safe stance as the changelog proof. */
934
- async function mergeBase(cwd: string, defaultBranch: string): Promise<string> {
935
- 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);
936
- return mb.ok ? mb.out.trim() : "";
937
- }
938
-
939
- /** What the branch proves about *who* worked it: the flow's delegation ledger, the commits the branch
940
- * holds over the default branch, and the sha set each recorded **implement** window covers. Returns null for a
941
- * --docs or --patch flow — those modes are exempt, so nothing is measured and no git call is spent.
942
- * A window whose shas git cannot resolve covers nothing rather than excusing itself: a hand-written
943
- * line must not be able to exempt the commits lying next to it. */
944
- async function delegationProof(root: string, state: FlowState, defaultBranch: string): Promise<{ ledger: DelegationWindow[]; branchCommits: string[] | null; windowCommits: (w: DelegationWindow) => string[]; covered: number; windows: number } | null> {
945
- if (state.docs || state.patch) return null;
946
- const work = gateCwd(root, state);
947
- let ledger: DelegationWindow[] = [];
948
- try {
949
- ledger = parseDelegationLedger(readFileSync(path.join(featDir(root, state.slug), STAGE_SESSIONS_DIR, DELEGATIONS_FILE), "utf8"));
950
- } catch { /* no ledger yet: nobody delegated, which the gate reports rather than throwing on */ }
951
- const shas = async (cmd: string) => {
952
- const r = await sh(cmd, work);
953
- return r.ok ? r.out.split("\n").map((l) => l.trim()).filter(Boolean) : null;
954
- };
955
- const base = await mergeBase(work, defaultBranch);
956
- let branchCommits = base ? await shas(`git rev-list ${sq(base)}..HEAD`) : null;
957
- // Only implement windows are ever consulted (delegationErrors filters the same way), so a pre-release
958
- // or release worker's line resolves to nothing instead of costing a `git rev-list` per line — the
959
- // ledger grows with every worker the feature runs, and the gate reads it on every verify.
960
- // The `?? []` stays: a window whose objects git cannot resolve covers nothing, it does not excuse
961
- // itself — otherwise a hand-written line about a garbage range would exempt the commits beside it.
962
- const impl = ledger.filter((w) => w.stage === "implement");
963
- const ranges = new Map<string, string[]>();
964
- const key = (w: DelegationWindow) => `${w.start}..${w.end}`;
965
- for (const w of impl) ranges.set(key(w), (await shas(`git rev-list ${sq(w.start)}..${sq(w.end)}`)) ?? []);
966
- const windowCommits = (w: DelegationWindow) => ranges.get(key(w)) ?? [];
967
- // What the gate prints as proven is what the operator is approving, so the count is intersected with
968
- // the branch: a reset or an amend leaves the window's shas resolvable as loose objects while they are
969
- // no longer on the branch, and "delegation proven: 2 worker commit(s)" over a branch of one is a
970
- // claim about commits nobody is verifying. Coverage itself is delegationErrors' business — it reads
971
- // the branch, so nothing here can widen it.
972
- const onBranch = branchCommits ? new Set(branchCommits) : null;
973
- const proves = (w: DelegationWindow) => windowCommits(w).some((sha) => !onBranch || onBranch.has(sha));
974
- const covered = new Set<string>();
975
- for (const w of impl) for (const sha of windowCommits(w)) if (!onBranch || onBranch.has(sha)) covered.add(sha);
976
- return { ledger, branchCommits, windowCommits, covered: covered.size, windows: impl.filter(proves).length };
977
- }
978
-
979
698
  function describeBranchState(b: BranchState, defaultBranch: string): string {
980
699
  return b.commitsAhead === null
981
700
  ? `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`
@@ -1036,7 +755,7 @@ function reflectNote(root: string, sess: Session, note: string[], forced: Reflec
1036
755
  if (next === text) return { text: `already reflected (duplicate): ${line}` };
1037
756
  writeFileSync(file, next);
1038
757
  // queueing is exactly when the operator hears about the checked-off pile — nudge instead of letting it grow
1039
- const closed = closedReflectionCount(next);
758
+ const closed = doneItemCount(next);
1040
759
  const why = forced ? "as told" : guess.why;
1041
760
  return { text: `reflected (${sections.join(" + ")} — ${why}): ${line}` + (closed ? `\n${reflectionsTidyHint(closed)}` : "") };
1042
761
  }
@@ -1051,8 +770,7 @@ const GH_FOLD_TTL_MS = 5 * 60_000;
1051
770
  * with the reason, never a guess), ok (the parsed list). */
1052
771
  async function fetchUpstream(root: string): Promise<{ slug: string; issues: GhIssue[] } | { skipped: string } | { absent: true }> {
1053
772
  if (process.env.DEV_FLOW_NO_ISSUES) return { skipped: "disabled (DEV_FLOW_NO_ISSUES)" };
1054
- const origin = await sh("git remote get-url origin", root, 10_000);
1055
- const slug = origin.ok ? githubSlug(origin.out) : "";
773
+ const slug = githubSlug((await originUrl(root)) ?? "");
1056
774
  if (!slug) return { absent: true };
1057
775
  const hit = ghFoldCache.get(slug);
1058
776
  if (hit && Date.now() - hit.at < GH_FOLD_TTL_MS) return { slug, issues: hit.issues };
@@ -1066,7 +784,7 @@ async function fetchUpstream(root: string): Promise<{ slug: string; issues: GhIs
1066
784
 
1067
785
  type FoldView = { state: "absent" } | { state: "skipped"; why: string } | { state: "ok"; slug: string; result: FoldResult; open: number };
1068
786
 
1069
- async function foldView(root: string, items: ReflectItem[], selfRepo: boolean): Promise<FoldView> {
787
+ async function foldView(root: string, items: ReflectItem[]): Promise<FoldView> {
1070
788
  const up = await fetchUpstream(root);
1071
789
  if ("absent" in up) return { state: "absent" };
1072
790
  if ("skipped" in up) return { state: "skipped", why: up.skipped };
@@ -1091,7 +809,7 @@ function foldRows(fold: FoldView, selfRepo: boolean): string[] {
1091
809
  * addressable by move: each item keeps the home it is resolved in. */
1092
810
  async function reflectList(root: string): Promise<RunResult> {
1093
811
  const items = readReflections(root);
1094
- const fold = await foldView(root, items, isSelfRepo(root));
812
+ const fold = await foldView(root, items);
1095
813
  const local = items.length
1096
814
  ? [
1097
815
  `reflections — ${items.length} open:`,
@@ -1130,8 +848,8 @@ function reflectTidy(root: string): RunResult {
1130
848
  const file = path.join(dfDir(root), "reflections.md");
1131
849
  if (!existsSync(file)) return { text: "reflections: nothing to tidy (no queue yet)" };
1132
850
  const text = readFileSync(file, "utf8");
1133
- const closed = closedReflectionCount(text);
1134
- const open = openReflections(text).length;
851
+ const closed = doneItemCount(text);
852
+ const open = openChecklistItems(text).length;
1135
853
  if (!closed) return { text: `reflections: nothing to tidy (${open} open, 0 closed)` };
1136
854
  writeFileSync(file, reflectionsTidy(text));
1137
855
  return { text: `reflections: dropped ${closed} closed item(s) — ${open} open` };
@@ -1221,11 +939,6 @@ function markPendingAsk(root: string, state: FlowState, word: string): void {
1221
939
  writeState(root, state);
1222
940
  }
1223
941
 
1224
- /** The pending checkpoint is answered either way — the 💬 leaves the footer with it. */
1225
- function clearPendingAsk(state: FlowState): void {
1226
- delete state.pendingAsk;
1227
- }
1228
-
1229
942
  async function gateVerify(o: GateCtx): Promise<RunResult> {
1230
943
  const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
1231
944
  const { state, err } = needState(root, sess, slugArg);
@@ -1236,32 +949,8 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1236
949
  // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
1237
950
  // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
1238
951
  // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
1239
- const fpAtGate = await worktreeFingerprint(gateCwd(root, state!));
1240
- const staleAtGate = freshenChecks(state!, fpAtGate, (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1241
- // The stamp is judged by its own wider fingerprint (see verifyStampFingerprint): a change to the
1242
- // plan the verdict was written against demotes it exactly like a worktree change would.
1243
- const stampVoided = await voidStaleVerifyStamp(root, state!);
1244
- if (staleAtGate.length || stampVoided) writeState(root, state!);
1245
- // An independent checker has to have looked at THIS tree before the operator is asked to approve it:
1246
- // the verify worker's PASS is a precondition of the gate, refused before any command runs so a long
1247
- // suite is never spent on a run that cannot pass. The stamp lives in state.checks, so a worktree edit
1248
- // or a moved fingerprint drops it exactly like a tier-1 record — one fresh verify worker per change,
1249
- // precise friction rather than a sticky lock. docs mode is exempt (nothing there to check).
1250
- if (verifyStampMissing(state!)) {
1251
- writeState(root, state!);
1252
- return { text: `verify gate FAILED:\n- ${VERIFY_STAMP_REFUSAL}${staleAtGate.includes(VERIFY_STAMP) || stampVoided ? " (a PASS was recorded, but the tree or its plan moved since — that is why it no longer counts)" : ""}\n${branchLine}`, isError: true };
1253
- }
1254
- // The implement stage has to have been *worked*, not just driven: every commit the branch holds
1255
- // must fall inside a worker's run window, as recorded in stage-sessions/delegations.log. Refused
1256
- // before any command runs, like the stamp — and judged only here, because the driver's own commits
1257
- // after this gate (changelog, bump) are pre-release work and belong to the session by design.
1258
- // Coverage is an implement-stage claim. The stage check is verifyGate's and it sits AFTER this one,
1259
- // so a re-run at pre-release would otherwise answer "verify only applies to implement" with a
1260
- // delegation accusation about the driver's own changelog and bump commits — commits that are
1261
- // in-session work by design. Measuring only at implement keeps the refusal honest.
1262
- const deleg = state!.stage === "implement" ? await delegationProof(root, state!, cfg.defaultBranch) : null;
1263
- const delegErrs = deleg ? delegationErrors(state!, deleg.ledger, deleg.branchCommits, deleg.windowCommits) : [];
1264
- if (delegErrs.length) return { text: `verify gate FAILED:\n- ${delegErrs.join("\n- ")}\n${branchLine}`, isError: true };
952
+ const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
953
+ if (staleAtGate.length) writeState(root, state!);
1265
954
  const pending = pendingChecks(state!, cfg);
1266
955
  const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
1267
956
  if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
@@ -1273,12 +962,10 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1273
962
  const did: string[] = [];
1274
963
  if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
1275
964
  if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
1276
- if (deleg) did.push(`delegation proven: ${deleg.covered} worker commit(s) in ${deleg.windows} window(s)`);
1277
965
  if (state!.docs) {
1278
966
  // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
1279
967
  did.push("docs mode: project commands skipped (build/dev/health)");
1280
968
  } else {
1281
- did.push(`verify worker PASS over this tree (${state!.checks[VERIFY_STAMP]?.at ?? "recorded"})`);
1282
969
  if (cfg.commands.build) {
1283
970
  const res = await sh(cfg.commands.build, gateCwd(root, state!));
1284
971
  state!.checks.build = { ok: res.ok, at: now() };
@@ -1300,32 +987,21 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1300
987
  // the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
1301
988
  if (!probe) did.push("health: none configured");
1302
989
  else {
1303
- const seedFail = await seedStep(root, state!, cfg);
1304
- if (seedFail) return seedFail;
1305
- const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
1306
- state!.checks.health = { ok: probed.ok, at: now() };
1307
- await stampChecks(root, state!, ["health"]);
1308
- writeState(root, state!);
1309
- // a probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42)
1310
- 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;
1311
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 };
1312
- did.push(`health: PASS (${probe}${tried})`);
993
+ did.push(`health: PASS (${probe}${triedNote(probed.attempts)})`);
1313
994
  }
1314
995
  } else if (!probe) did.push("dev: none configured");
1315
996
  else {
1316
997
  // no deploy to prove, but the operator still reviews a live app — and a green health record
1317
998
  // survives a killed server (process death dirties no worktree fingerprint), so the record
1318
999
  // cannot stand for liveness: re-probe, before anyone is asked.
1319
- const seedFail = await seedStep(root, state!, cfg);
1320
- if (seedFail) return seedFail;
1321
- const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
1322
- state!.checks.health = { ok: probed.ok, at: now() };
1323
- await stampChecks(root, state!, ["health"]);
1324
- writeState(root, state!);
1325
- 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;
1326
1002
  if (!probed.ok)
1327
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 };
1328
- did.push(`health: live re-probe PASS (${probe}${tried})`);
1004
+ did.push(`health: live re-probe PASS (${probe}${triedNote(probed.attempts)})`);
1329
1005
  }
1330
1006
  }
1331
1007
  const ran = [branchLine, ...did].join("; ");
@@ -1342,7 +1018,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1342
1018
  }
1343
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?`);
1344
1020
  if (!ok) {
1345
- clearPendingAsk(state!);
1021
+ delete state!.pendingAsk;
1346
1022
  writeState(root, state!);
1347
1023
  return { text: "verification declined — stay in implement and fix what failed" };
1348
1024
  }
@@ -1352,7 +1028,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1352
1028
  if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
1353
1029
  state!.approvals.verify = now();
1354
1030
  state!.stage = "pre-release";
1355
- clearPendingAsk(state!);
1031
+ delete state!.pendingAsk;
1356
1032
  writeState(root, state!);
1357
1033
  return { text: `verified${audit} — entering pre-release stage.\n${ran}\n${nextHint(state!, cfg)}` };
1358
1034
  }
@@ -1362,7 +1038,8 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1362
1038
  const { state, err } = needState(root, sess, slugArg);
1363
1039
  if (err) return err;
1364
1040
  const items = applicableItems(cfg, state!, "pre-release");
1365
- 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;
1366
1043
  // yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
1367
1044
  const yoloWord = takeYoloWord(state!);
1368
1045
  if (yoloWord) return { text: yoloWord, isError: true };
@@ -1381,7 +1058,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1381
1058
  ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
1382
1059
  : null;
1383
1060
  // tags are only needed on the versioned path; a project without versioning must not be held up by an offline origin
1384
- const remoteTags = cfg.versioning.file && !state!.noVersion ? await releaseTags(root) : [];
1061
+ const remoteTags = cfg.versioning.file && !noVersion ? await releaseTags(root) : [];
1385
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 };
1386
1063
  const changelog =
1387
1064
  cfg.release.changelog && existsSync(path.join(wtCwd, cfg.release.changelog))
@@ -1394,14 +1071,13 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1394
1071
  const changelogBase: { pending: string[]; source: "tag" | "merge-base" | "none" } = { pending: [], source: "none" };
1395
1072
  if (changelog) {
1396
1073
  const p = sq(cfg.release.changelog!);
1397
- 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);
1398
- const mbRef = mb.ok ? mb.out.trim() : "";
1074
+ const mbRef = await mergeBase(wtCwd, cfg.defaultBranch);
1399
1075
  // proof the branch touched the changelog: local refs only, so the check stays offline-safe
1400
1076
  if (mbRef) {
1401
1077
  const changes = await sh(`git diff --name-only ${sq(mbRef)} -- ${p} 2>/dev/null; git ls-files --others --exclude-standard -- ${p}`, wtCwd);
1402
1078
  changelogChanged = changes.out.split("\n").some((l) => l.trim());
1403
1079
  }
1404
- 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;
1405
1081
  // tag first, merge base as the understudy: `releaseTags` asks origin, so a clone that has not
1406
1082
  // fetched the tag yet must still get a baseline instead of losing the fold proof
1407
1083
  const bases: { ref: string; source: "tag" | "merge-base" }[] = [];
@@ -1419,17 +1095,20 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1419
1095
  const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1420
1096
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1421
1097
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1422
- // a PASS whose worktree-or-plan moved is dead here too — no gate may act on a verdict it cannot prove current
1423
- if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1424
1098
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1425
- 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);
1426
1100
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
1101
+ // the build the tag will trigger, proven before anything ships: a broken artifact build found after the
1102
+ // tag costs follow-up PRs and a re-cut tag
1103
+ if (cfg.release.preflight) {
1104
+ const pf = await sh(cfg.release.preflight, wtCwd);
1105
+ if (!pf.ok) return { text: `release gate FAILED:\n- release.preflight failed in ${state!.worktree} (${cfg.release.preflight}) — fix it on the branch before anything ships:\n${tail(pf.out)}`, isError: true };
1106
+ }
1427
1107
  // a stale session build is the operator's decision, never a block: publishing under an older gate is a
1428
1108
  // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1429
1109
  // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
1430
1110
  // update-or-proceed question into the Release? checkpoint — the operator's word, recorded in state.
1431
- const selfBuild = checkoutBuild(root);
1432
- const behind = sessionRunsOlderBuild(loadedVersion(), selfBuild.version);
1111
+ const { disk: selfBuild, behind } = buildSkew(root);
1433
1112
  // truly behind, not merely different: a session whose loaded build is NEWER than the checkout's manifest
1434
1113
  // has every proof the checkout would run, and asking about it would be noise.
1435
1114
  const stale = !!behind && !!selfBuild.version && cmpVersions(behind, selfBuild.version) < 0;
@@ -1453,13 +1132,14 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1453
1132
  if (!ui.hasUI) {
1454
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 };
1455
1134
  }
1456
- 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}` : ""}`);
1457
1136
  if (!ok) {
1458
- clearPendingAsk(state!);
1137
+ delete state!.pendingAsk;
1459
1138
  writeState(root, state!);
1460
1139
  return { text: "release declined — keep preparing in pre-release" };
1461
1140
  }
1462
1141
  }
1142
+ if (noVersion) state!.noVersion = true;
1463
1143
  state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
1464
1144
  state!.approvals["pre-release"] = now();
1465
1145
  state!.stage = "release";
@@ -1475,7 +1155,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1475
1155
  // re-read a checkout that may still be behind (#52)
1476
1156
  if (!state!.noVersion && manifestVer) state!.releaseVersion = manifestVer;
1477
1157
  if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1478
- clearPendingAsk(state!);
1158
+ delete state!.pendingAsk;
1479
1159
  writeState(root, state!);
1480
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)}` };
1481
1161
  }
@@ -1485,20 +1165,13 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1485
1165
  const { state, err } = needState(root, sess, slugArg);
1486
1166
  if (err) return err;
1487
1167
  const errs = releaseGate(state!);
1488
- let manifestVer: string | null = state!.releaseVersion ?? null;
1489
- if (cfg.versioning.file && !state!.noVersion && !manifestVer) {
1490
- // a flow approved before releaseVersion existed: the worktree copy is what the release gate
1491
- // validated, the main checkout is the last resort (#52)
1492
- for (const dir of [gateCwd(root, state!), root]) {
1493
- const p = path.join(dir, cfg.versioning.file);
1494
- if (!existsSync(p)) continue;
1495
- manifestVer = parseVersion(cfg.versioning.file, readFileSync(p, "utf8"));
1496
- if (manifestVer) break;
1497
- }
1498
- if (!manifestVer) errs.push(`versioning.file "${cfg.versioning.file}" has no parsable version — fix the playbook`);
1499
- }
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`);
1500
1171
  const expectedTag = manifestVer ? cfg.versioning.pattern.replace("{version}", manifestVer) : null;
1501
- 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);
1502
1175
  // one round-trip answers both questions about the tag: is it there, and did it leave this laptop (#52)
1503
1176
  const tags = expectedTag ? await releaseTags(root) : [];
1504
1177
  if (tags === null) errs.push("cannot list tags on origin (offline?) — retry: local tags must not decide what is already released");
@@ -1540,25 +1213,23 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1540
1213
  // ancestry proves "not squashed, not rebased"; a squash and a rebase look identical here, so when it
1541
1214
  // fails the forge itself is asked which one it was (gh/glab; self-hosted stays an advisory)
1542
1215
  const ancestor = refsOk ? (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok : null;
1543
- const forgeProof = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1544
- 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 });
1545
1217
  if (proof.errors.length) errs.push(...proof.errors);
1546
1218
  else mergeNote = proof.note;
1547
1219
  }
1548
1220
  if (errs.length) return { text: `release gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1549
1221
  // no checkpoint here — the operator's Release? answer covered the whole publication; everything left is objective checks
1550
- 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 = "";
1551
1224
  let bodyOfRecord: string | null = null; // the changelog entry the forge body must match (#97)
1552
1225
  let bodyNote = "";
1553
- const forgeName = cfg.forge || detectForge((await sh("git remote get-url origin", root)).out);
1554
1226
  if (manifestVer && flag("no-release-create")) ghNote = "Forge release skipped (--no-release-create).";
1555
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).";
1556
1228
  else if (manifestVer && releasesWanted) {
1557
1229
  // forge release for the verified tag — gh for GitHub, glab for GitLab. A failed create is no
1558
1230
  // longer the end of the story: the proof below asks the forge whether anything is there (#63, #85)
1559
1231
  const tag = expectedTag!;
1560
- const forge = forgeName;
1561
- 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).";
1562
1233
  else {
1563
1234
  // the body is the changelog entry for this version (#97); the tag annotation only stands in
1564
1235
  // when the changelog has no entry for it — and never the output of a failed command, which
@@ -1579,18 +1250,17 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1579
1250
  else if (!notesRes.ok) notesNote = `no release notes (the tag command failed: ${tail(notesRes.out)}). `;
1580
1251
  else if (annotation && looksLikeShellError(annotation)) notesNote = "no release notes (the tag command returned a shell error, not a body). ";
1581
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). `;
1582
- const cmd = forge === "gitlab"
1253
+ const cmd = forgeName === "gitlab"
1583
1254
  ? `glab release create ${sq(tag)} --name ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`
1584
1255
  : `gh release create ${sq(tag)} --title ${sq(tag)}${notes ? ` --notes ${sq(notes)}` : ""}`;
1585
1256
  const gr = await sh(cmd, root);
1586
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)
1587
1258
  if (gr.ok) delete state!.forgeReleaseSkipped; // a successful retry lifts the stamp
1588
1259
  else state!.forgeReleaseSkipped = tail(gr.out);
1589
- 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)}`;
1590
1261
  }
1591
1262
  }
1592
- const diskBuild = checkoutBuild(root);
1593
- const behind = sessionRunsOlderBuild(loadedVersion(), diskBuild.version);
1263
+ const skew = buildSkew(root);
1594
1264
  const openRelease = checklistPending(cfg, state!, "release");
1595
1265
  // release-stage items have no gate of their own: the operator's Finish? answer is what closes them, so
1596
1266
  // name them at the last objective gate — on the way out too, or the refusal hides half the story
@@ -1626,10 +1296,10 @@ async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
1626
1296
  // a session that shipped from behind: the code it runs is not the code the checkout just released
1627
1297
  state!.staleBuild
1628
1298
  ? `stale build acknowledged at release gate: this session ran dev-flow ${state!.staleBuild} — proofs newer than it did not run.`
1629
- : behind
1299
+ : skew.behind
1630
1300
  // #117: the pair (session vs what the disk ships) makes the warning actionable where it prints;
1631
1301
  // a second registered copy is what made the skew confusing on the report — name it too
1632
- ? `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()}` : ""}`
1633
1303
  : "",
1634
1304
  mergeNote,
1635
1305
  openNote,
@@ -1650,7 +1320,8 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1650
1320
  // after this the flow state is gone: nothing may sit uncommitted or unpushed
1651
1321
  const dirty = await sh("git status --porcelain", root);
1652
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 };
1653
- const hasOriginF = (await sh("git remote get-url origin", root)).ok;
1323
+ const origin = await originUrl(root);
1324
+ const hasOriginF = origin !== null;
1654
1325
  if (hasOriginF) {
1655
1326
  const pushed = await sh(`git merge-base --is-ancestor HEAD ${sq(`origin/${cfg.defaultBranch}`)}`, root);
1656
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 };
@@ -1678,25 +1349,25 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1678
1349
  if (wt && existsSync(wt)) {
1679
1350
  const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
1680
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);
1681
- const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1352
+ const unmergedLines = unmerged.out.split("\n").filter(Boolean);
1682
1353
  // the refusal names the paths, not just the count — same proof verify and release print (gh#131)
1683
- if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}${status.out.trim() ? `:\n${tail(status.out)}` : ""}`, isError: true };
1684
- 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) {
1685
1356
  const policy = cfg.release.merge;
1686
1357
  // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
1687
1358
  // or a branch that was never pushed, the same count describes a local-only repo, not a squash
1688
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;
1689
1360
  unmergedNote =
1690
1361
  policy && policy !== "merge" && policy !== "any"
1691
- ? ` ${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}.`
1692
1363
  : policy === "merge" && measurable
1693
- ? ` ${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`
1694
- : ` ${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?)`;
1695
1366
  // under a merge-commit policy this is a violation, not a routine cleanup note: yolo does not
1696
1367
  // answer it, only the operator does
1697
1368
  if (policy === "merge" && measurable && !flag("confirmed")) {
1698
1369
  markPendingAsk(root, state!, "Merge policy violation?");
1699
- 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 };
1700
1371
  }
1701
1372
  }
1702
1373
  }
@@ -1714,7 +1385,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1714
1385
  }
1715
1386
  const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1716
1387
  if (!ok) {
1717
- clearPendingAsk(state!);
1388
+ delete state!.pendingAsk;
1718
1389
  writeState(root, state!);
1719
1390
  return { text: "finish declined" };
1720
1391
  }
@@ -1734,24 +1405,14 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1734
1405
  // remote cleanup: origin/<branch> is deleted only on proof it was released — being an ancestor of
1735
1406
  // origin/<default> (merge-commit merges) or a merged PR via gh (squash merges); else it stays.
1736
1407
  let remoteNote = "";
1737
- if (state!.branch && (await sh("git remote get-url origin", root)).ok) {
1408
+ if (state!.branch && hasOriginF) {
1738
1409
  const br = state!.branch;
1739
1410
  const onRemote = await sh("git ls-remote --heads origin", root);
1740
1411
  if (onRemote.out.split("\n").some((l) => l.endsWith(`\trefs/heads/${br}`))) {
1741
1412
  await sh(`git fetch -q origin ${sq(br)}`, root);
1742
1413
  let merged = (await sh(`git merge-base --is-ancestor origin/${sq(br)} origin/${sq(cfg.defaultBranch)}`, root)).ok;
1743
- if (!merged) {
1744
- // squash merges leave no ancestry — ask the forge: gh pr list, or the GitLab API via glab; self-hosted stays on ancestry proof
1745
- const originUrl = await sh("git remote get-url origin", root);
1746
- const forge = cfg.forge || detectForge(originUrl.out);
1747
- if (forge === "gitlab") {
1748
- const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${br}&state=merged&per_page=1`)}`, root);
1749
- merged = mr.ok && mr.out.trim() !== "[]";
1750
- } else if (forge === "github") {
1751
- const pr = await sh(`gh pr list --state merged --head ${sq(br)} --json number --jq length`, root);
1752
- merged = pr.ok && pr.out.trim() !== "0";
1753
- }
1754
- }
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;
1755
1416
  if (merged) remoteNote = (await sh(`git push origin --delete ${sq(`refs/heads/${br}`)}`, root)).ok
1756
1417
  ? ` origin/${br} deleted (verified merged)`
1757
1418
  : ` origin/${br} delete failed — git push origin --delete ${br}`;
@@ -1773,7 +1434,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1773
1434
  }
1774
1435
 
1775
1436
  async function gateInit(o: GateCtx): Promise<RunResult> {
1776
- const { root, ui, cfg, rest, flag } = o;
1437
+ const { root, ui, rest, flag } = o;
1777
1438
  // a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
1778
1439
  // only sanctioned agent path to the playbook: claiming "created" when the folder was already
1779
1440
  // there sends the agent diffing its own config for damage that never happened (#39).
@@ -1782,20 +1443,16 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1782
1443
  const notes: string[] = dfExisted ? [] : [`.dev-flow/ created in ${root}`];
1783
1444
  // self-ignoring folder with one exception: the playbook is the only file under .dev-flow/ that lives in git
1784
1445
  writeFileSync(path.join(dfDir(root), ".gitignore"), "*\n!project.md\n");
1785
- rmSync(path.join(dfDir(root), ".current"), { force: true }); // migrate away the legacy repo-global pointer
1786
1446
  const mdFile = path.join(dfDir(root), "project.md");
1787
1447
  const head = await sh("git symbolic-ref refs/remotes/origin/HEAD", root);
1788
1448
  const curBr = await currentBranch(root);
1789
1449
  // never propose a feature branch (contains "/") as the default branch
1790
1450
  const branch = (head.ok ? head.out.match(/refs\/remotes\/origin\/(.+)/)?.[1] : undefined) || (curBr.includes("/") ? undefined : curBr) || "main";
1791
1451
  const det = detectProject(root, branch);
1792
- const origin = await sh("git remote get-url origin", root);
1793
- 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
1794
1454
  det.partial.merge = (await mergeHistoryEvidence(root, branch))?.note; // "what do you actually do when a PR merges", read off the log
1795
- const loaded = loadProject(dfDir(root));
1796
1455
  const draftFresh = buildDraft(det);
1797
- const draftRefresh = buildDraft(det, loaded.cfg);
1798
- 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";
1799
1456
  if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
1800
1457
  // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
1801
1458
  const ghosts = ghostFeatureDirs(root);
@@ -1806,22 +1463,21 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1806
1463
  notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
1807
1464
  } else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
1808
1465
  }
1809
- 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[] } => {
1810
1468
  const parsed = parseProjectMd(text);
1811
- if (parsed.hard.length) return { text: `project.md REJECTED:\n- ${parsed.hard.join("\n- ")}`, isError: true };
1812
- // 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 } };
1813
1470
  if (existsSync(mdFile)) copyFileSync(mdFile, `${mdFile}.bak`);
1814
1471
  writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
1815
- return null;
1472
+ return { warn: parsed.warn };
1816
1473
  };
1817
1474
  if (flag("write")) {
1818
1475
  const content = rest[rest.indexOf("--write") + 1];
1819
1476
  if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>"', isError: true };
1820
- const parsed = parseProjectMd(content);
1821
- const rej = writeMd(content);
1822
- if (rej) return rej;
1477
+ const w = writeMd(content);
1478
+ if ("rej" in w) return w.rej;
1823
1479
  notes.push("project.md written (operator-owned playbook)", GIT_TRACK_NOTE);
1824
- 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}`));
1825
1481
  } else if (!existsSync(mdFile)) {
1826
1482
  // first init: never write silently. The setup brief lists what detection could not decide;
1827
1483
  // the agent relays the questions to the operator and applies the answers via flow init --write
@@ -1837,8 +1493,8 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1837
1493
  if (ui.hasUI) {
1838
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.`);
1839
1495
  if (ok) {
1840
- const rej = writeMd(draftFresh);
1841
- if (rej) return rej;
1496
+ const w = writeMd(draftFresh);
1497
+ if ("rej" in w) return w.rej;
1842
1498
  notes.push("wrote .dev-flow/project.md from detection — review it and adjust as needed", GIT_TRACK_NOTE);
1843
1499
  } else notes.push("draft not written — answer the setup questions, then flow init --write");
1844
1500
  }
@@ -1850,44 +1506,12 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
1850
1506
  copyFileSync(mdFile, `${mdFile}.bak`);
1851
1507
  writeFileSync(mdFile, draftFresh);
1852
1508
  notes.push("project.md OVERWRITTEN (--force; previous copy kept as project.md.bak):", ...det.report.map((r) => ` ${r}`), GIT_TRACK_NOTE);
1853
- } else if (!ui.hasUI) {
1854
- // the CI/agent path: the doctor's findings have to be printed, not just promised
1855
- const findings = doctorFindings(root, loaded.cfg, loaded.md);
1856
- 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}`));
1857
- } else if (existsSync(mdFile)) {
1858
- // 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));
1859
1513
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
1860
- findings.push(...(await gitConsistency(root, loaded.cfg)));
1861
- // 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
1862
- if (!loaded.cfg.release.merge) {
1863
- const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
1864
- 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)`);
1865
- }
1866
- for (const it of readReflections(root)) findings.push(`open reflection [${it.section}]: ${it.line.slice(6)}`);
1867
- if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
1868
- else {
1869
- // a refresh is regenerated from detection + config: lines it cannot reproduce are
1870
- // hand-written (prose, checklist items, hand-set keys) and would vanish silently.
1871
- const dropped = droppableLines(readFileSync(mdFile, "utf8"), draftRefresh);
1872
- let edited: string | undefined;
1873
- if (dropped.length)
1874
- 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)`] : []));
1875
- else
1876
- edited = ui.editor
1877
- ? await ui.editor(`flow init — doctor: ${findings.length} finding(s) — edit & save to apply, Esc skips`, draftRefresh)
1878
- : (await ui.confirm(`flow init — doctor: ${findings.length} finding(s)`, `${findings.join("\n")}
1879
-
1880
- Write refreshed project.md? Your file; cancel writes nothing.
1881
- ${mdDigest(draftRefresh)}`))
1882
- ? draftRefresh
1883
- : undefined;
1884
- if (edited === undefined) notes.push(dropped.length ? "findings — fix them by editing the file:" : "declined — project.md unchanged", ...findings.map((f) => ` ${f}`));
1885
- else {
1886
- const rej = writeMd(edited);
1887
- if (rej) return rej;
1888
- notes.push("project.md refreshed — findings addressed:", ...findings.map((f) => ` ${f}`), editHint);
1889
- }
1890
- }
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}`));
1891
1515
  }
1892
1516
  const initCfg = loadProject(dfDir(root)).cfg;
1893
1517
  if (initCfg.mainHook) {
@@ -1908,26 +1532,26 @@ ${mdDigest(draftRefresh)}`))
1908
1532
  }
1909
1533
 
1910
1534
  async function gateStart(o: GateCtx): Promise<RunResult> {
1911
- const { root, ui, sess, cfg, rest, flag, slugArg } = o;
1912
- if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs are operator-granted modes — ask the operator in chat, then add --confirmed", isError: true };
1535
+ const { root, sess, cfg, rest, flag, slugArg } = o;
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 };
1913
1537
  if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
1914
1538
  // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
1915
1539
  if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
1916
1540
  const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
1917
1541
  if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — the operator must grant it in chat, then re-run with --confirmed`, isError: true };
1542
+ // --ui adds the rendered-mockup gate to plan: worth it only when screens change, and the operator says so
1543
+ if (flag("ui") && !flag("confirmed")) return { text: "--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate, so use it only when the feature changes screens; ask the operator, then re-run with --confirmed", isError: true };
1918
1544
  // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
1919
1545
  const curBr = await currentBranch(root);
1920
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 };
1921
1547
  // --- preflight: is this session running the current build, and is the playbook complete? ---
1922
1548
  const notes: string[] = [];
1923
- const disk = checkoutBuild(root);
1924
- const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
1925
- 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}`);
1926
1551
  const dupStart = copyWarning();
1927
1552
  if (dupStart) notes.push(dupStart);
1928
1553
  if (flag("check-upstream")) {
1929
- const pub = await sh("npm view pi-dev-flow version", root);
1930
- const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1554
+ const newest = await publishedVersion(root);
1931
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?)");
1932
1556
  }
1933
1557
  // missing playbook parameters are printed at the moment they start to matter, not promised to a later doctor run
@@ -1938,11 +1562,7 @@ async function gateStart(o: GateCtx): Promise<RunResult> {
1938
1562
  const styleArg = flagValue(rest, "merge");
1939
1563
  const style = styleArg === null ? null : parseMergeStyle(styleArg);
1940
1564
  if (styleArg !== null && !style) return { text: `--merge=${styleArg} is not a policy — use squash, merge, rebase or any`, isError: true };
1941
- // with no playbook at all there is nothing to ask about: writing the playbook is `flow init`'s job, and
1942
- // a repo that never ran init must not be refused a feature by a merge-policy question
1943
- const hasPlaybook = existsSync(path.join(dfDir(root), "project.md"));
1944
- if (!hasPlaybook) notes.push("no .dev-flow/project.md yet — flow init writes the playbook (it now asks for the merge policy too)");
1945
- if (hasPlaybook && (!cfg.release.merge || (style && style !== cfg.release.merge))) {
1565
+ if (!cfg.release.merge || (style && style !== cfg.release.merge)) {
1946
1566
  if (!style) {
1947
1567
  const ev = await mergeHistoryEvidence(root, cfg.defaultBranch);
1948
1568
  return {
@@ -1981,7 +1601,6 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1981
1601
  const errs = approveGate(state!, cfg, listFiles(planDir), existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined);
1982
1602
  if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
1983
1603
  const planItems = applicableItems(cfg, state!, "plan");
1984
- if (flag("yolo")) state!.yolo = true; // operator's word at Approve? — every later gate question is pre-confirmed; checks and guardrails stay
1985
1604
  const audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
1986
1605
  const askPending = !flag("confirmed");
1987
1606
  if (askPending) {
@@ -1990,8 +1609,14 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
1990
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 };
1991
1610
  }
1992
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." : ""}`);
1993
- 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
+ }
1994
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;
1995
1620
  if (planItems.length) state!.confirmations = { ...state!.confirmations, plan: { hash: checklistHash(planItems), at: now() } };
1996
1621
  const branch = subst(cfg.branchPattern, state!.slug);
1997
1622
  const wtRel = subst(cfg.worktreeDir, state!.slug);
@@ -2019,44 +1644,33 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
2019
1644
  state!.worktree = wtRel;
2020
1645
  state!.stage = "implement";
2021
1646
  state!.approvals.plan = now();
2022
- clearPendingAsk(state!);
1647
+ delete state!.pendingAsk;
2023
1648
  writeState(root, state!);
2024
1649
  return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${setupNote}\n${nextHint(state!, cfg)}` };
2025
1650
  }
2026
1651
 
2027
1652
  async function gateStatus(o: GateCtx): Promise<RunResult> {
2028
- const { root, ui, sess, cfg, flag, slugArg } = o;
1653
+ const { root, sess, cfg, flag, slugArg } = o;
2029
1654
  const df = dfDir(root);
2030
1655
  const { md } = loadProject(df);
2031
1656
  // cheap fs probes only (no git subprocesses) — status is a glance, `flow doctor` is the full list
2032
1657
  const findings = md ? doctorFindings(root, cfg, md) : [];
2033
1658
  // a session running an older build than the disk ships is the one thing a glance must say: every
2034
1659
  // gate proof printed since the drift began belongs to the older code.
2035
- const disk = checkoutBuild(root);
2036
- const staleBuild = sessionRunsOlderBuild(loadedVersion(), disk.version);
2037
- 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()!] : [])];
2038
1662
  // the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
2039
1663
  const rmap = roadmapOpenCount(readRoadmap(root));
2040
1664
  const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
2041
- 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);
2042
1666
  const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
2043
- // status (and --json, which feeds worker briefs) must never advertise a PASS the gates would refuse:
2044
- // reap dead stamps in the copies being rendered — and persist only THIS session's own feature, since
2045
- // a foreign state.json belongs to its own session (a listing must not write another session's file).
2046
- const states = new Map<string, FlowState>();
2047
- for (const s of slugs) {
2048
- const stV = readState(root, s);
2049
- if (!stV) continue;
2050
- if (await voidStaleVerifyStamp(root, stV) && s === sess.slug) writeState(root, stV);
2051
- states.set(s, stV);
2052
- }
2053
1667
  if (flag("json")) {
2054
- const sts = slugs.map((s) => states.get(s)).filter((s): s is FlowState => s !== undefined);
1668
+ const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
2055
1669
  return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
2056
1670
  }
2057
1671
  if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
2058
1672
  const lines = slugs.flatMap((s) => {
2059
- const st = states.get(s);
1673
+ const st = readState(root, s);
2060
1674
  if (!st) return [];
2061
1675
  return [
2062
1676
  `${s === cur ? "→" : " "} ${s}: stage=${st.stage}${st.ui ? " [ui]" : ""}${st.yolo ? " [yolo]" : ""}${st.noVersion ? " [no-version]" : ""}${st.pendingAsk ? ` 💬 ${st.pendingAsk}` : ""} branch=${st.branch || "-"} worktree=${st.worktree || "-"}${st.flowVersion ? ` flow=${st.flowVersion}` : ""}`,
@@ -2094,14 +1708,14 @@ async function gateReflect(o: GateCtx): Promise<RunResult> {
2094
1708
  if (words.length) return reflectNote(root, sess, words, forced);
2095
1709
  // upstream for the update probe: the manifest's repository field; the dev-flow checkout itself falls back to its origin
2096
1710
  const self = pluginVersion(import.meta.dirname);
2097
- 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)) ?? "") : "");
2098
1712
  const refl = readReflections(root);
2099
- const fold = await foldView(root, refl, isSelfRepo(root));
1713
+ const fold = await foldView(root, refl);
2100
1714
  return {
2101
1715
  text: reflectProtocol(refl, isSelfRepo(root), {
2102
1716
  version: self.version,
2103
1717
  upstream,
2104
- closed: closedReflectionCount(readReflectionsText(root)),
1718
+ closed: doneItemCount(readReflectionsText(root)),
2105
1719
  ghFold: fold.state === "ok" && fold.open ? { repo: fold.slug, open: fold.open, similar: fold.result.similar.length } : undefined,
2106
1720
  }).join("\n"),
2107
1721
  };
@@ -2114,7 +1728,7 @@ async function gateRoadmap(o: GateCtx): Promise<RunResult> {
2114
1728
  const [verb = "list", ...args] = words;
2115
1729
  const text = readRoadmap(root);
2116
1730
  const open = roadmapOpenCount(text);
2117
- const done = roadmapDoneCount(text);
1731
+ const done = doneItemCount(text);
2118
1732
  const save = (next: string) => writeFileSync(roadmapFile(root), next); // .dev-flow/ existence is runFlow's precondition
2119
1733
  const idx = Number(args[0]);
2120
1734
  const validIdx = Number.isInteger(idx) && idx >= 1 && idx <= open;
@@ -2152,15 +1766,14 @@ async function gateRoadmap(o: GateCtx): Promise<RunResult> {
2152
1766
  }
2153
1767
 
2154
1768
  async function gateDoctor(o: GateCtx): Promise<RunResult> {
2155
- const { root, cfg, rest } = o;
1769
+ const { root, rest } = o;
2156
1770
  // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
2157
1771
  const df = dfDir(root);
2158
1772
  const loaded = loadProject(df);
2159
1773
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
2160
1774
  findings.push(...(await gitConsistency(root, loaded.cfg)));
2161
- findings.push(...orphanBucketFindings(root));
2162
1775
  const refl = readReflections(root);
2163
- const fold = await foldView(root, refl, isSelfRepo(root));
1776
+ const fold = await foldView(root, refl);
2164
1777
  if (refl.length) {
2165
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:`);
2166
1779
  // labelled from the heading each item sits under — the file is the record, re-guessing from the
@@ -2173,44 +1786,14 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2173
1786
  findings.push(...foldRows(fold, isSelfRepo(root)));
2174
1787
  const unfiled = reflectUnfiledCount(readReflectionsText(root));
2175
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`);
2176
- const closedRefl = closedReflectionCount(readReflectionsText(root));
1789
+ const closedRefl = doneItemCount(readReflectionsText(root));
2177
1790
  if (closedRefl) findings.push(reflectionsTidyHint(closedRefl));
2178
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" };
2179
1792
  // flow doctor <note>: a fresh observation gets an investigation brief and a fix route
2180
1793
  return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
2181
1794
  }
2182
1795
 
2183
- /** Session buckets stage workers left under finished or vanished worktrees (see `orphanWorktreeBuckets`).
2184
- * Information only: the doctor names them and the command that removes them; deleting transcripts is
2185
- * the operator's call, never the doctor's. Silent when there is no session store to read. */
2186
- function orphanBucketFindings(root: string): string[] {
2187
- const sessionsRoot = testSeams.sessionsRoot.value === undefined ? path.join(getAgentDir(), "sessions") : testSeams.sessionsRoot.value;
2188
- if (!sessionsRoot || !existsSync(sessionsRoot)) return [];
2189
- let buckets: string[];
2190
- try { buckets = readdirSync(sessionsRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { return []; }
2191
- const features = new Map<string, WorktreeBucketFeature>();
2192
- try {
2193
- for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
2194
- if (!d.isDirectory()) continue;
2195
- const st = readState(root, d.name);
2196
- if (!st) continue;
2197
- const wt = st.worktree ? path.resolve(root, st.worktree) : null;
2198
- features.set(d.name, { finished: st.stage === "done" || !!st.aborted, worktreeExists: !!wt && existsSync(wt) });
2199
- }
2200
- } catch { /* no .dev-flow dir: every matching bucket is an orphan */ }
2201
- const orphans = orphanWorktreeBuckets(buckets, root, features);
2202
- if (!orphans.length) return [];
2203
- const rows = orphans.map((o) => {
2204
- const dir = path.join(sessionsRoot, o.bucket);
2205
- let n = 0;
2206
- try { n = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).length; } catch { /* count is cosmetic */ }
2207
- return ` ${o.slug}: ${n} transcript(s) — rm -r ${sq(dir)}`;
2208
- });
2209
- return [`worker session buckets left by finished or removed worktrees (${orphans.length}) — stage workers before 0.70 filed under their worktree, where no picker scope opened from this checkout shows them; keep them for the record or remove:\n${rows.join("\n")}`];
2210
- }
2211
-
2212
- /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
2213
- * their own names back, so the bodies needed zero edits. */
1796
+ /** What a gate handler needs from the runFlow preamble. */
2214
1797
  interface GateCtx {
2215
1798
  root: string;
2216
1799
  ui: Ui;
@@ -2225,16 +1808,14 @@ interface GateCtx {
2225
1808
  async function gateVersion(o: GateCtx): Promise<RunResult> {
2226
1809
  const { root, flag } = o;
2227
1810
  // the plugin's own version — separate from the project's versioning.file version the release gates use
2228
- const self = checkoutBuild(root);
2229
- const behind = sessionRunsOlderBuild(loadedVersion(), self.version);
1811
+ const { disk: self, behind } = buildSkew(root);
2230
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}`;
2231
1813
  // in the dev-flow repo head names the checkout, so name where the stale code actually lives
2232
1814
  const from = SELF_BUILD.dir !== self.dir ? ` (from ${SELF_BUILD.dir})` : "";
2233
1815
  const dupNote = copyWarning();
2234
1816
  // --check-upstream is the one that asks the registry; plain flow version stays offline and instant
2235
1817
  if (flag("check-upstream")) {
2236
- const pub = await sh("npm view pi-dev-flow version", root);
2237
- const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
1818
+ const newest = await publishedVersion(root);
2238
1819
  return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
2239
1820
  }
2240
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}` : ""}` };
@@ -2263,7 +1844,6 @@ async function gateCheck(o: GateCtx): Promise<RunResult> {
2263
1844
  // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
2264
1845
  if (state!.docs) return { text: "docs mode: project commands skipped — a docs flow runs no tier-1 checks (CI on the tag and the artifact proof still do)" };
2265
1846
  if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
2266
- if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
2267
1847
  const ran = await runChecks(root, state!, cfg, cfg.checkList);
2268
1848
  return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
2269
1849
  }
@@ -2272,37 +1852,34 @@ async function gateHealth(o: GateCtx): Promise<RunResult> {
2272
1852
  const { root, sess, cfg, slugArg } = o;
2273
1853
  const { state, err } = needState(root, sess, slugArg);
2274
1854
  if (err) return err;
2275
- 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 };
2276
- const seedFail = await seedStep(root, state!, cfg);
2277
- if (seedFail) return seedFail;
2278
- const res = await runHealthProbe(cfg.commands.health, gateCwd(root, state!), cfg.healthWait);
2279
- state!.checks.health = { ok: res.ok, at: now() };
2280
- await stampChecks(root, state!, ["health"]);
2281
- writeState(root, state!);
2282
- const tried = res.attempts > 1 ? `, ${res.attempts} attempts` : "";
2283
- 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)}` };
2284
1861
  }
2285
1862
 
2286
1863
  async function gateUse(o: GateCtx): Promise<RunResult> {
2287
1864
  const { root, sess, slugArg } = o;
2288
1865
  if (!slugArg) return { text: "usage: flow use <slug>", isError: true };
2289
1866
  const st = readState(root, slugArg);
2290
- if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
1867
+ if (!st) return { text: `no unfinished feature ${slugArg}`, isError: true };
2291
1868
  const prior = readClaim(root, slugArg);
2292
- const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (${claimWho(prior!)})` : "";
1869
+ const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
2293
1870
  sess.bind(slugArg);
2294
1871
  sess.rename(slugArg);
2295
1872
  // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
2296
1873
  // must not inherit a 💬 for a question it never posed
2297
1874
  if (st.pendingAsk) {
2298
- clearPendingAsk(st);
1875
+ delete st.pendingAsk;
2299
1876
  writeState(root, st);
2300
1877
  }
2301
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}` };
2302
1879
  }
2303
1880
 
2304
1881
  async function gateAbort(o: GateCtx): Promise<RunResult> {
2305
- const { root, sess, slugArg } = o;
1882
+ const { root, ui, sess, flag, slugArg } = o;
2306
1883
  // Unbinds the session only; state and worktree stay for manual recovery.
2307
1884
  const target = slugArg ?? sess.slug;
2308
1885
  if (!target) return { text: "nothing bound — pass a slug", isError: true };
@@ -2310,55 +1887,65 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2310
1887
  // a live claim locks the whole feature, not only its gates: aborting it out from under the session
2311
1888
  // that works it erases the plan that session is still writing (same rule needState applies)
2312
1889
  const claim = readClaim(root, target);
2313
- if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (${claimWho(claim!)}) — flow use ${target} takes it over explicitly`, isError: true };
2314
- if (sess.slug === target) sess.bind(null);
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 };
2315
1891
  if (st && !st.worktree) {
2316
1892
  // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
2317
- // 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);
2318
1901
  rmSync(featDir(root, target), { recursive: true, force: true });
2319
1902
  return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
2320
1903
  }
1904
+ if (sess.slug === target) sess.bind(null);
2321
1905
  if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
2322
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}` : "") };
2323
1907
  }
2324
1908
 
2325
1909
 
2326
- /** True inside a linked worktree (its git dir is not the common dir), false in a main checkout or on error. */
2327
- async function isLinkedWorktree(root: string): Promise<boolean> {
2328
- const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", root);
2329
- if (!r.ok) return false;
2330
- const [gitDir, common] = r.out.split("\n").map((l) => l.trim());
2331
- return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
2332
- }
1910
+ /** Sessions spawned by flow_stage in this process: they get no [dev-flow] driver context injected
1911
+ * (their brief is their whole context) — the guards still judge them like any session. */
1912
+ const workerSessions = new Set<string>();
2333
1913
 
2334
- /** Per-cwd cache for flowRoot: consulted on every tool call of every session, and a git probe per call
2335
- * is not acceptable there. A cwd's answer never changes while the process lives (a worktree that gets
2336
- * removed stops being anyone's cwd; a plain clone does not become one). */
2337
- const flowRootCache = new Map<string, string>();
1914
+ /** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
1915
+ const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"] };
2338
1916
 
2339
- /** The root whose .dev-flow/ is the flow truth for a session cwd.
2340
- *
2341
- * A feature worktree is a **linked git worktree**, and the default worktreeDir (.dev-flow/<slug>/worktree)
2342
- * makes its own tracked .dev-flow/ hold one file: project.md. The state, the claims, the plans and the
2343
- * delegation ledger all live in the main checkout, so judging a worker by its own cwd found zero features
2344
- * and every guard answered "no active flow" — the write-guard's worker half never fired, because byWorker
2345
- * was only ever consulted after owner attribution, and owner attribution had nothing to attribute. A
2346
- * worker fell back to bash authoring, which is the half the guard was never meant to police.
2347
- *
2348
- * So: a linked worktree resolves to its main checkout (git's common dir is <main>/.git), and only when
2349
- * that checkout is actually initiated — otherwise the cwd answer stands, which keeps plain clones, scratch
2350
- * repos and every test fixture behaving exactly as before. */
1917
+ /** Seam that spawns a worker as a real pi session — tests replace `.run`. With the driver's session
1918
+ * file and directory known, the worker's header links back to the driver (`parentSession`), so pi's
1919
+ * picker nests it under the driver. */
1920
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<AgentSession> } = {
1921
+ run: async ({ work, model, name, tools, parent, dir }) => {
1922
+ const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
1923
+ await loader.reload();
1924
+ const sessionManager = parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
1925
+ const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
1926
+ try { workerSessions.add(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the default context */ }
1927
+ try { session.setSessionName(name); } catch { /* naming is visibility, not function */ }
1928
+ return session;
1929
+ },
1930
+ };
1931
+
1932
+ /** Per-cwd cache of the main checkout a linked worktree belongs to (null = not a linked worktree) —
1933
+ * every hook resolves its root through flowRoot, so git is asked once per directory. */
1934
+ const mainCheckoutCache = new Map<string, string | null>();
1935
+
1936
+ /** The root whose .dev-flow/ is the flow truth for a session cwd. A feature worktree is a linked git
1937
+ * worktree whose tracked .dev-flow/ holds only project.md — state, claims and plans live in the main
1938
+ * checkout. Judging a session by its own cwd found no features and every guard answered "no active
1939
+ * flow". So a linked worktree resolves to its main checkout when that checkout is initiated. */
2351
1940
  async function flowRoot(cwd: string): Promise<string> {
2352
- const hit = flowRootCache.get(cwd);
2353
- if (hit !== undefined) return hit;
2354
- let root = cwd;
2355
- if (await isLinkedWorktree(cwd)) {
2356
- const r = await sh("git rev-parse --path-format=absolute --git-common-dir", cwd);
2357
- const main = mainCheckoutRoot(cwd, r.ok ? r.out.trim() : null);
2358
- if (main && initiated(main)) root = main;
1941
+ if (!mainCheckoutCache.has(cwd)) {
1942
+ const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", cwd);
1943
+ const [gitDir, common] = r.ok ? r.out.split("\n").map((l) => l.trim()) : [];
1944
+ const linked = !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
1945
+ mainCheckoutCache.set(cwd, linked ? mainCheckoutRoot(cwd, common) : null);
2359
1946
  }
2360
- flowRootCache.set(cwd, root);
2361
- return root;
1947
+ const main = mainCheckoutCache.get(cwd);
1948
+ return main && initiated(main) ? main : cwd;
2362
1949
  }
2363
1950
 
2364
1951
  async function currentBranch(root: string): Promise<string> {
@@ -2381,15 +1968,10 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
2381
1968
  // sessions overwrite one state file (last write wins) while both believe they own the stage.
2382
1969
  const claim = readClaim(root, slug);
2383
1970
  if (sess.slug !== slug && claimBlocks(claim, sess.key))
2384
- return { state: null, err: { text: `${slug} is claimed by another live session (${claimWho(claim!)}) — flow use ${slug} takes it over explicitly`, isError: true } };
1971
+ return { state: null, err: { text: `${slug} is claimed by another live session (pid ${claim!.pid}) — flow use ${slug} takes it over explicitly`, isError: true } };
2385
1972
  return { state };
2386
1973
  }
2387
1974
 
2388
- async function listDirs(dir: string): Promise<string[]> {
2389
- const { readdirSync } = await import("node:fs");
2390
- return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
2391
- }
2392
-
2393
1975
  function tail(out: string, n = 15): string {
2394
1976
  const lines = out.split("\n").filter(Boolean);
2395
1977
  return lines.length > n ? `…(${lines.length - n} lines)…\n${lines.slice(-n).join("\n")}` : out;
@@ -2400,13 +1982,13 @@ function tail(out: string, n = 15): string {
2400
1982
  /** Compact footer: bound flow = stage glyph, slug, mode markers, ⚠️ on its failing checks; unbound = the
2401
1983
  * unfinished-flow count, or `💬 no flows` — an initiated repo always carries the footer. An uninitiated
2402
1984
  * folder gets nothing: the status is cleared. Pure read — rendering never binds or claims anything. */
2403
- function refreshStatus(ctx: ExtensionContext): void {
1985
+ function refreshStatus(ctx: ExtensionContext, root: string): void {
2404
1986
  if (!ctx.hasUI) return;
2405
- if (!initiated(ctx.cwd)) {
1987
+ if (!initiated(root)) {
2406
1988
  ctx.ui.setStatus("dev-flow", undefined);
2407
1989
  return;
2408
1990
  }
2409
- const s = statusFor(boundFeature(ctx.cwd, sessionKey(ctx)), unfinishedStates(ctx.cwd).length);
1991
+ const s = statusFor(boundFeature(root, sessionKey(ctx)), unfinishedStates(root).length);
2410
1992
  ctx.ui.setStatus("dev-flow", s.text);
2411
1993
  }
2412
1994
 
@@ -2429,10 +2011,9 @@ export default function devFlow(pi: ExtensionAPI) {
2429
2011
  const uiFrom = (ctx: ExtensionContext): Ui => ({
2430
2012
  hasUI: ctx.hasUI,
2431
2013
  confirm: async (title, message) => (ctx.hasUI ? ctx.ui.confirm(title, message) : Promise.resolve(false)),
2432
- editor: ctx.mode === "tui" ? (title: string, prefill?: string) => ctx.ui.editor(title, prefill) : undefined,
2433
2014
  });
2434
2015
 
2435
- const sessFor = (ctx: ExtensionContext): Session => {
2016
+ const sessFor = (ctx: ExtensionContext, root: string): Session => {
2436
2017
  const key = sessionKey(ctx);
2437
2018
  return {
2438
2019
  key,
@@ -2442,8 +2023,8 @@ export default function devFlow(pi: ExtensionAPI) {
2442
2023
  bindings.set(key, slug);
2443
2024
  pi.appendEntry("dev-flow-bind", { slug });
2444
2025
  // claims track the binding: claim what you bind, release what you drop.
2445
- if (prev && prev !== slug && readClaim(ctx.cwd, prev)?.key === key) rmSync(claimFile(ctx.cwd, prev), { force: true });
2446
- if (slug) writeClaim(ctx.cwd, slug, key);
2026
+ if (prev && prev !== slug && readClaim(root, prev)?.key === key) rmSync(claimFile(root, prev), { force: true });
2027
+ if (slug) writeClaim(root, slug, key);
2447
2028
  },
2448
2029
  rename: (slug) => {
2449
2030
  // pi's public session-name API, kept defensive: an older host without it must not fail a gate.
@@ -2458,7 +2039,7 @@ export default function devFlow(pi: ExtensionAPI) {
2458
2039
  };
2459
2040
 
2460
2041
  /** Restore this session's binding from its branch history (survives resume/fork). */
2461
- const rebuildSession = (ctx: ExtensionContext) => {
2042
+ const rebuildSession = (ctx: ExtensionContext, root: string) => {
2462
2043
  let slug: string | null = null;
2463
2044
  let sawCore = false;
2464
2045
  let coreStaleHere = false;
@@ -2483,7 +2064,7 @@ export default function devFlow(pi: ExtensionAPI) {
2483
2064
  // A reload ends the old session, which released its claim; the restored one must reclaim what its own
2484
2065
  // branch says it holds, or the repo answers "claimed by another live session" to the session that
2485
2066
  // holds it. A foreign live claim wins — restoring is not a takeover.
2486
- if (slug && readState(ctx.cwd, slug) && !claimBlocks(readClaim(ctx.cwd, slug), key)) writeClaim(ctx.cwd, slug, key);
2067
+ if (slug && readState(root, slug) && !claimBlocks(readClaim(root, slug), key)) writeClaim(root, slug, key);
2487
2068
  };
2488
2069
 
2489
2070
  /** The run's playbook preamble: the skill's always-on core, once per session. Later runs come back
@@ -2504,13 +2085,14 @@ export default function devFlow(pi: ExtensionAPI) {
2504
2085
  description: `dev-flow gates: ${GATE_HELP}`,
2505
2086
  handler: async (args, ctx) => {
2506
2087
  const cmd = parse(args);
2507
- const res = await runFlow(cmd, ctx.cwd, uiFrom(ctx), sessFor(ctx));
2088
+ const root = await flowRoot(ctx.cwd);
2089
+ const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root));
2508
2090
  // gate output belongs to the conversation, not a toast: display:true renders a [flow] box (TUI + web), no triggerTurn so no model turn fires.
2509
2091
  // bare reflect is the exception: its whole output is instructions for the agent — displayed without a turn, they would never execute.
2510
2092
  const wake = cmd.length === 1 && cmd[0] === "reflect";
2511
2093
  pi.sendMessage({ customType: "flow", content: res.text, display: true }, wake ? { triggerTurn: true } : undefined);
2512
- refreshStatus(ctx);
2513
- if (!res.isError) maybeCompactNow(ctx);
2094
+ refreshStatus(ctx, root);
2095
+ if (!res.isError) maybeCompactNow(ctx, root);
2514
2096
  },
2515
2097
  });
2516
2098
 
@@ -2520,409 +2102,122 @@ export default function devFlow(pi: ExtensionAPI) {
2520
2102
  description:
2521
2103
  "Drive the dev-flow stage gates for the active feature (plan → implement → pre-release → release → done). Never edit .dev-flow state directly; gates enforce plan/mockup/test/verification criteria and confirm with the operator.",
2522
2104
  parameters: Type.Object({
2523
- args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug", "--ui"]' }),
2105
+ args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug"]' }),
2524
2106
  }),
2525
2107
  execute: async (_id, params, _signal, _onUpdate, ctx) => {
2526
- const res = await runFlow(params.args, ctx.cwd, uiFrom(ctx), sessFor(ctx));
2527
- if (!res.isError) maybeCompactNow(ctx);
2108
+ const root = await flowRoot(ctx.cwd);
2109
+ const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root));
2110
+ if (!res.isError) maybeCompactNow(ctx, root);
2528
2111
  return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
2529
2112
  },
2530
2113
  });
2531
2114
  pi.registerTool(flowTool);
2532
2115
 
2533
- /** The text a worker's finished tool call carried (first text part, else an error string) — the live
2534
- * ✓/✗ line is built from it, so a worker that gets an error back shows it, not just the tool name. */
2535
- function resultText(result: unknown): string {
2536
- const r = result as { content?: unknown; text?: string; errorMessage?: string } | undefined;
2537
- const parts = Array.isArray(r?.content) ? (r!.content as { type?: string; text?: string }[]) : [];
2538
- return parts.find((p) => p?.type === "text")?.text ?? r?.text ?? r?.errorMessage ?? "";
2539
- }
2540
-
2541
- /** The assistant prose of a worker turn — text parts only, thinking and tool calls have their own lines. */
2542
- function assistantText(content: unknown): string {
2543
- if (typeof content === "string") return content;
2544
- if (!Array.isArray(content)) return "";
2545
- return (content as { type?: string; text?: string }[]).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n");
2546
- }
2547
-
2548
- /** Last non-empty line: the end of a tool dump is the verdict-bearing part ("251 pass", "exit 1",
2549
- * the error), its head is almost never the news. */
2550
- function lastLineOf(text: string): string {
2551
- return (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
2552
- }
2116
+ /** Driver sessions with a worker running right now — one worker per session at a time. */
2117
+ const runningWorkers = new Set<string>();
2553
2118
 
2554
- // ---- stage worker (flow_stage): one stage's work, its check and its review in a disposable sub-session --
2555
- // The child stays UNBOUND on purpose: writeGuard attributes worktree writes to the owning
2556
- // feature's stage and bashFlowGuard stops only default-branch git ops, so an implement worker may
2557
- // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and the
2558
- // parent holds the live claim) — and its tool list holds no flow tool at all. The claim, every gate
2559
- // and every checkpoint stay with the driving session; the worker owes one report.
2560
- // Three ops share this one mechanism on purpose: `run` (a stage's work), `verify` (an independent
2561
- // read-only checker whose PASS the verify gate demands) and `reflect` (an independent review of the
2562
- // whole finished flow). Only the brief, the toolset, the budget default and the closing contract
2563
- // differ — the unbound-worker safety story is identical, and a second mechanism would drift.
2564
2119
  const stageWorkerTool = defineTool({
2565
2120
  name: "flow_stage",
2566
2121
  label: "Stage worker",
2567
2122
  description:
2568
- 'Delegate to a disposable dev-flow worker session with a fresh context. op "run" (default) does the current stage\'s work (implement | pre-release) and edits + commits on the feature branch; op "verify" is an independent read-only checker of the implement work (read + bash, standing order "check, don\'t fix", closes with a VERIFY REPORT verdict — flow verify refuses until a PASS exists over the current tree); op "reflect" reviews the finished flow — the driver transcript plus every worker transcript — at the release stage after release-done. Everything the worker must know — operator answers not yet recorded by a gate, decisions, warnings, the exact next action — travels in `note`; otherwise it sees only plan, git and flow status. Give each delegation a short `label` (a few words of purpose) — session names then read `⏳ 🔍 #1 · <label>` while running and `✓ 🔍 #1 · PASS · <label>` (or `✗ … · hard-cut`, `✓ 🔨 #2 · 3 commits · <label>`) when done, so the picker is never a column of identical rows. A worker holds no flow tool: gates, checkpoints and the claim stay with you. At 75% of its budget (budgetMin: default 45 for run, 30 for verify/reflect) the worker is steered to commit and report instead of being cut. The tool card streams the live tail (current tool, last assistant line, ✓/✗ results, elapsed/budget, usage) and op "status" mirrors it on any host. When a worker returns: read its report, run flow check yourself, then ask the checkpoint — a stage report is a handoff, never a verification.',
2569
- promptSnippet:
2570
- 'flow_stage(op: "run"|"verify"|"reflect", note, budgetMin?) — delegate stage work, an independent read-only check, or the finish review to a fresh worker session; op: "status" reads the live run; gates and checkpoints stay with you',
2123
+ '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.',
2124
+ 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',
2571
2125
  parameters: Type.Object({
2572
- op: Type.Optional(Type.String({ description: '"run" (default) delegates the stage work; "verify" = independent check-only review of the implement work (legal only while the feature is at implement); "reflect" = independent review of the finished flow (legal at release, after release-done); "status" reports the live worker run in this session' })),
2573
- stage: Type.Optional(Type.String({ description: 'With op "run": the stage to delegate the work for — must match the bound feature\'s current stage. "verify" and "reflect" belong to a fixed stage and ignore this.' })),
2574
- note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
2575
- budgetMin: Type.Optional(Type.Number({ description: "Worker budget in minutes (5-120; default 45 for run, 30 for verify/reflect). At 75% the worker is steered to commit and report; past the budget it is interrupted and the tree snapshotted." })),
2576
- label: Type.Optional(Type.String({ description: 'Short purpose for this delegation (≤\u007e32 chars) shown in the session name and card, so a re-delegation reads `🔨 #2 · <purpose>` instead of a clone row. Sanitized and clipped.' })),
2126
+ op: Type.String({ description: '"implement" (a worker edits + commits a slice) or "review" (read-only reviewer, findings + verdict)' }),
2127
+ 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." }),
2128
+ label: Type.Optional(Type.String({ description: "A few words naming this delegation, shown in the worker's session name." })),
2129
+ budgetMin: Type.Optional(Type.Number({ description: "Wall-clock budget in minutes (5-180; default 60 implement, 30 review). Past it the worker is interrupted." })),
2577
2130
  }),
2578
- // The card is the guaranteed worker-visibility surface: it renders inside the driver's own
2579
- // transcript, in TUI and in pi-web alike, because every line also travels as the update's text.
2580
- renderCall: (args, theme) => {
2581
- const op = String(args.op ?? "run");
2582
- const what = op === "run" ? `run ${args.stage ?? "?"}` : op;
2583
- return new Text(theme.fg("toolTitle", `flow_stage ${what}`) + (args.note ? ` ${theme.fg("muted", liveClip(String(args.note), 70))}` : ""), 0, 0);
2584
- },
2585
- renderResult: (result, options, theme) => {
2586
- const d = result.details as { card?: string[]; cardFull?: string[]; verdict?: string | null } | undefined;
2587
- const lines = (options.expanded ? d?.cardFull ?? d?.card : d?.card) ?? [];
2588
- if (!lines.length) return new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n") || "(no output)", 0, 0);
2589
- const box = new Container();
2590
- for (const line of lines) {
2591
- const text = options.expanded ? line : liveClip(line, 120);
2592
- box.addChild(new Text(line.startsWith("✗") || line.startsWith("verdict: FAIL") ? theme.fg("error", text) : line.startsWith("✓") || line.startsWith("verdict: PASS") ? theme.fg("success", text) : theme.fg("muted", text), 0, 0));
2593
- }
2594
- if (options.expanded) {
2595
- box.addChild(new Text(theme.fg("dim", "─── report ───"), 0, 0));
2596
- box.addChild(new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n"), 0, 0));
2597
- }
2598
- return box;
2599
- },
2600
2131
  execute: async (_id, params, signal, onUpdate, ctx) => {
2601
2132
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2602
- const opRaw = String(params.op ?? "run").trim().toLowerCase();
2603
- if (!isWorkerOp(opRaw)) return err(`unknown op "${opRaw}" — flow_stage ops: run (delegate the stage work), verify (independent check), reflect (finish review), status (the live run)`);
2604
- const op: WorkerOp = opRaw;
2605
- if (op === "status") {
2606
- const run = stageRuns.get(sessionKey(ctx));
2607
- // The family is the question op:"status" gets when nothing is running — "what has this flow
2608
- // spawned, and how did each end?". pi's picker threads the same rows into a tree; this is
2609
- // that fact for a host with no tree, and for the moment between runs. A worker that is live
2610
- // right now is the section above, not one of "the others" — so it is left out here. The whole
2611
- // section is gated on a bound feature: an unbound session has never spawned a stage worker,
2612
- // so there it would be noise paid for with a directory scan.
2613
- const boundState = (() => { try { return initiated(ctx.cwd) ? boundFeature(ctx.cwd, sessionKey(ctx)) : null; } catch { return null; } })();
2614
- const inFlow = !!boundState;
2615
- const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
2616
- // the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
2617
- const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE), run?.transcript) : null);
2618
- const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
2619
- if (!run) {
2620
- return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
2621
- }
2622
- const elapsed = Date.now() - run.startedAt;
2623
- const dirtyNow = await sh("git status --porcelain", run.work);
2624
- const logNow = await sh("git log --oneline -5", run.work);
2625
- const text = [
2626
- `stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
2627
- ...liveTail(run.lastLines),
2628
- stageUsageLine(run.usage, run.turns),
2629
- `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2630
- `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2631
- ...(inFlow ? ["", ...familySection] : []),
2632
- ].join("\n");
2633
- return { content: [{ type: "text", text }], details: { running: true, op: run.op, slug: run.slug, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired, usage: run.usage, turns: run.turns, workers: workerFamilyCount(familyLines) } };
2634
- }
2635
- if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2636
- const st = boundFeature(ctx.cwd, sessionKey(ctx));
2637
- if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2638
- const stageArg = String(params.stage ?? "");
2639
- if (op === "run") {
2640
- if (!isDelegableStage(stageArg)) return err(`flow_stage delegates the work of: ${DELEGABLE_STAGES.join(" or ")} — "${stageArg}" is not delegable (plan is the operator dialogue; release/finish carry the checkpoint words; op "status" needs no stage)`);
2641
- if (st.stage !== stageArg) return err(`feature ${st.slug} is at stage "${st.stage}", not "${stageArg}" — flow_stage runs the work of the stage you are in`);
2642
- } else {
2643
- const why = workerOpError(op, st);
2644
- if (why) return err(why);
2645
- if (stageArg && stageArg !== st.stage) return err(`op "${op}" belongs to the stage the flow is in ("${st.stage}"), not "${stageArg}" — the op names its own stage`);
2646
- }
2133
+ const op = String(params.op ?? "").trim().toLowerCase();
2134
+ const root = await flowRoot(ctx.cwd);
2135
+ if (!initiated(root)) return err("dev-flow is not initiated here — run flow init first");
2647
2136
  const key = sessionKey(ctx);
2648
- if (stageRuns.has(key)) return err(`a stage worker for ${st.slug} is already running in this session — one worker per session; flow_stage {op: "status"} reads the live one`);
2649
- const budgetMin = clampStageBudgetMin(params.budgetMin ?? WORKER_OP_BUDGET_MIN[op]);
2650
- const budgetMs = budgetMin * 60_000;
2651
- const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
2652
- const hardMs = stageTimingOverride.hardMs ?? budgetMs;
2653
- const glyph = WORKER_OP_GLYPH[op];
2654
- const label = typeof params.label === "string" ? sanitizeWorkerLabel(params.label) : "";
2655
- // the card/beats keep the descriptive kind (the card line has no other stage context); the
2656
- // session NAMES are compact — glyph, ordinal, purpose (see workerName)
2657
- const kind = op === "run" ? `${glyph} ${st.stage}` : `${glyph} ${op}`;
2658
- const kindCard = label ? `${kind} · ${label}` : kind;
2659
- const work = gateCwd(ctx.cwd, st);
2660
- const run: StageRun = {
2661
- startedAt: Date.now(), budgetMin, softFired: false, work, lastLines: [],
2662
- op, kind, slug: st.slug, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, turns: 0,
2663
- };
2664
- stageRuns.set(key, run);
2665
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2666
- const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2667
- const transcriptLog = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE);
2668
- const delegationLog = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR, DELEGATIONS_FILE);
2669
- // read once, used twice: the worker's header links to this file and lands in this bucket,
2670
- // and the reflect brief names this session's own transcript to the reviewer
2671
- const lineage = lineageOf(ctx);
2137
+ const st = boundFeature(root, key);
2138
+ if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2139
+ const why = workerOpError(op, st.stage);
2140
+ if (why) return err(why);
2141
+ const wop = op as WorkerOp;
2142
+ const work = worktreeAbs(root, st);
2143
+ if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk — nothing for a worker to work in`);
2144
+ if (runningWorkers.has(key)) return err("a worker is already running for this session — wait for it to return");
2145
+ runningWorkers.add(key);
2146
+ const cfg = loadProject(dfDir(root)).cfg;
2147
+ const budgetMin = clampBudgetMin(params.budgetMin, wop);
2148
+ const label = String(params.label ?? "").replace(/[\r\n]+/g, " ").trim().slice(0, 40);
2149
+ const glyph = wop === "implement" ? "🔨" : "🔍";
2150
+ const name = `${glyph} ${st.slug}${label ? ` · ${label}` : ""}`;
2151
+ const started = Date.now();
2152
+ const git = async (cmd: string) => { const r = await sh(cmd, work); return r.ok ? r.out : ""; };
2153
+ const headBefore = (await git("git rev-parse HEAD")).trim();
2154
+ const brief = buildWorkerBrief({
2155
+ op: wop, slug: st.slug, workDir: work,
2156
+ planFile: path.join(featDir(root, st.slug), "plan", "plan.md"),
2157
+ defaultBranch: cfg.defaultBranch,
2158
+ commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
2159
+ status: await git("git status --short"),
2160
+ checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
2161
+ note: String(params.note ?? ""),
2162
+ });
2163
+ let lineage: { file?: string; dir?: string } = {};
2164
+ try { lineage = { file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
2672
2165
  let child: AgentSession | undefined;
2673
- let crash: string | null = null;
2674
2166
  let timedOut = false;
2675
- /** The card frame for this instant — one place so the streamed text, the TUI card and
2676
- * op:"status" can never disagree about what the worker is doing. */
2677
- const cardView = (state: "running" | "done" | "failed", extra: { verdict?: "pass" | "fail" | null; transcript?: string } = {}) =>
2678
- stageCardLines({ kind: kindCard, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state, ...extra });
2679
- const emit = (event: string, data: Record<string, unknown>) => {
2680
- try { pi.events.emit(event, { slug: st.slug, op, stage: st.stage, ...data }); } catch { /* the bus is visibility, never function */ }
2681
- };
2167
+ let crash: string | null = null;
2168
+ let nudges = 0;
2169
+ let report = parseWorkerReport("");
2170
+ const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2171
+ const timer = setTimeout(() => { timedOut = true; abortChild(); }, budgetMin * 60_000);
2172
+ signal?.addEventListener("abort", abortChild);
2173
+ let unsub: (() => void) | undefined;
2682
2174
  try {
2683
- writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2684
- const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2685
- // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2686
- // read #2, #3 in the list instead of identical rows. A verify is numbered too: a feature that
2687
- // takes six rounds to PASS reads as a sequence, not as six free-text labels. A reflect is one per flow.
2688
- const seq = op !== "reflect" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2689
- const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2690
- const git = await sh("git status --porcelain -b", work);
2691
- const note = typeof params.note === "string" ? params.note : undefined;
2692
- const planFile = path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md");
2693
- let brief: string;
2694
- if (op === "verify") {
2695
- // the reviewer reads the full diff itself; the stat is only the shape of what it is in for
2696
- const stat = await sh(`git diff --shortstat ${sq(`origin/${cfg.defaultBranch}`)}...HEAD 2>/dev/null || git diff --shortstat ${sq(cfg.defaultBranch)}...HEAD`, work);
2697
- const tier1 = [...cfg.checkList];
2698
- if (cfg.commands.test && !tier1.some((c) => c.name === "test")) tier1.push({ name: "test", cmd: cfg.commands.test });
2699
- brief = buildVerifyBrief({
2700
- slug: st.slug, workDir: work, planFile, statusJson: statusJsonText,
2701
- gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2702
- diffStat: stat.ok ? stat.out.trim() : "(no diff stat)",
2703
- defaultBranch: cfg.defaultBranch, checks: tier1, note,
2704
- });
2705
- } else if (op === "reflect") {
2706
- const transcripts = existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")) : [];
2707
- brief = buildReflectBrief({
2708
- slug: st.slug, planFile, statusJson: statusJsonText, driverSession: lineage.file, transcripts,
2709
- openReflections: readReflections(ctx.cwd).map((r) => r.line), note,
2710
- });
2711
- } else {
2712
- const refRel = stageReference(st.stage);
2713
- let refText = "";
2714
- if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2715
- brief = buildStageBrief({ slug: st.slug, stage: st.stage as DelegableStage, workDir: work, planFile, referenceText: refText, statusJson: statusJsonText, gitSummary: git.ok ? git.out.trim() : "(git status failed)", note });
2716
- }
2717
- // the tree identity a verify verdict belongs to, before anything runs: the same comparison
2718
- // the tier-1 fingerprint makes, done here because a reviewer must not be the one who edited.
2719
- // HEAD is captured too: a reviewer that commits or moves a ref leaves `git status` clean while
2720
- // reading a different tree, so a porcelain-only diff would stamp a PASS for a HEAD it never saw.
2721
- const statusBefore = await sh("git status --porcelain", work);
2722
- const headBefore = await sh("git rev-parse HEAD", work);
2723
- const refBefore = await sh("git symbolic-ref -q HEAD || true", work);
2724
- // the plan is an input the reviewer reads from OUTSIDE the worktree — it belongs in the
2725
- // before/after proof too, or a reviewer could rewrite the ground it is judging mid-run
2726
- const planDir = path.join(ctx.cwd, ".dev-flow", st.slug, "plan");
2727
- const planBefore = planFingerprint(planDir);
2728
- // the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
2729
- // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2730
- // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2731
- const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: workerName("⏳", glyph, seq, label), tools: [...WORKER_OP_TOOLS[op]], parent: lineage.file ?? undefined, dir: lineage.dir ?? undefined });
2732
- child = worker.session;
2733
- try { run.transcript = child.sessionManager.getSessionFile() ?? undefined; } catch { /* the family listing just won't know which row is this run */ }
2734
- emit("dev-flow:worker-started", { budgetMin, startedAt: new Date().toISOString() });
2735
- let lastBeat = 0;
2736
- /** One live line: ledger, durable log, and the streamed card — same text on every host. */
2737
- const pushLine = (line: string) => {
2738
- if (!line) return;
2739
- run.lastLines.push(line);
2740
- if (run.lastLines.length > 50) run.lastLines.shift();
2741
- try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2742
- const card = cardView("running");
2743
- onUpdate?.({ content: [{ type: "text", text: card.join("\n") }], details: { running: true, op, slug: st.slug, stage: st.stage, card, cardFull: stageCardLines({ kind, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state: "running" }, true) } });
2744
- };
2745
- const unsub = child.subscribe((ev: unknown) => {
2746
- const e = ev as { type?: string; toolName?: string; args?: unknown; isError?: boolean; result?: unknown; message?: { role?: string; content?: unknown; usage?: Record<string, number> & { cost?: Record<string, number> } } };
2747
- const elapsed = () => Date.now() - run.startedAt;
2175
+ child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir });
2176
+ unsub = child.subscribe((ev: unknown) => {
2177
+ const e = ev as { type?: string; toolName?: string };
2748
2178
  if (e.type === "tool_execution_start") {
2749
- pushLine(stageLiveLine(elapsed(), e.toolName ?? "?", summarizeToolArgs(e.args)));
2750
- const now = Date.now();
2751
- if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
2752
- }
2753
- if (e.type === "tool_execution_end") {
2754
- // the last line of the result is the verdict-bearing one ("251 pass", "exit 1",
2755
- // the error) — the head of a tool dump is almost never the news
2756
- pushLine(stageLiveResultLine(elapsed(), e.toolName ?? "?", !e.isError, lastLineOf(resultText(e.result))));
2757
- }
2758
- if (e.type === "message_end" && e.message?.role === "assistant") {
2759
- run.turns++;
2760
- const u = e.message.usage;
2761
- if (u) {
2762
- for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) run.usage[f] += Number(u[f] ?? 0);
2763
- if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) run.usage.cost[f] += Number(u.cost[f] ?? 0);
2764
- }
2765
- pushLine(stageLiveAssistantLine(elapsed(), assistantText(e.message.content)));
2179
+ const min = Math.floor((Date.now() - started) / 60_000);
2180
+ onUpdate?.({ content: [{ type: "text", text: `⏳ ${name} — ${min}/${budgetMin} min · ${e.toolName ?? "?"}` }], details: { running: true } });
2766
2181
  }
2767
2182
  });
2768
- const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2769
- // grace before the cliff: at 75% the worker is told to commit and report — an honest handoff
2770
- // beats an abort; the hard timer stays the backstop for a worker that ignores the steer
2771
- const softTimer = setTimeout(() => {
2772
- run.softFired = true;
2773
- try { void Promise.resolve(child?.steer(stageInterruptSteer(budgetMin))).catch(() => {}); } catch { /* hard cut follows */ }
2774
- }, softMs);
2775
- const hardTimer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2776
- signal?.addEventListener("abort", abortChild);
2777
- try {
2778
- await child.prompt(brief);
2779
- } catch (e) {
2780
- crash = e instanceof Error ? e.message : String(e);
2781
- } finally {
2782
- clearTimeout(softTimer);
2783
- clearTimeout(hardTimer);
2784
- unsub();
2183
+ await child.prompt(brief);
2184
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2185
+ // a turn that ends in prose ("now let me write D4…") ends the session: tell it to keep going
2186
+ while (!report.found && !timedOut && !signal?.aborted && nudges < WORKER_NUDGES) {
2187
+ nudges++;
2188
+ await child.prompt(WORKER_NUDGE);
2189
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2785
2190
  }
2786
- const clean = !crash && !timedOut;
2787
- const transcript = child.sessionManager.getSessionFile() ?? "";
2788
- // the durable worker index: until now a transcript path lived only in this call's result,
2789
- // i.e. only as long as the driver kept it in context — the reflect worker needs the list
2790
- if (transcript) {
2791
- try {
2792
- mkdirSync(path.dirname(transcriptLog), { recursive: true });
2793
- appendFileSync(transcriptLog, `${workerTranscriptLine(now(), op, transcript)}\n`);
2794
- } catch { /* an index that failed to append is never a reason to lose the run */ }
2795
- }
2796
- const report = op === "run" ? parseStageReport(child.getLastAssistantText() ?? "") : null;
2797
- const verify = op === "verify" ? parseVerifyReport(child.getLastAssistantText() ?? "") : null;
2798
- const findings = op === "reflect" ? parseReflectFindings(child.getLastAssistantText() ?? "") : null;
2799
- // A check-only worker must leave the tree exactly as it found it: the verdict is a claim
2800
- // about THIS tree, so a reviewer that touched anything voids its own report. Computed before
2801
- // the rename and the stamp so both readers agree on one verdict of "did the ground move".
2802
- // (The gate's own uncommitted-path policy stays unchanged — a tree already dirty is not the
2803
- // worker's fault; only movement counts.)
2804
- const statusAfter = await sh("git status --porcelain", work);
2805
- const headAfter = await sh("git rev-parse HEAD", work);
2806
- const refAfter = await sh("git symbolic-ref -q HEAD || true", work);
2807
- // four legs, because each alone has a clean-tree bypass: porcelain misses ref moves,
2808
- // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2809
- // and all three miss the plan the verdict was written against living outside the worktree
2810
- const moved = op !== "run" && ((statusBefore.ok && statusAfter.ok && statusAfter.out !== statusBefore.out) || (headBefore.ok && headAfter.ok && headAfter.out !== headBefore.out) || (refBefore.ok && refAfter.ok && refAfter.out !== refBefore.out) || planFingerprint(planDir) !== planBefore);
2811
- // the outcome goes INTO the final name — a picker row like `✓ 🔍 #3 · PASS · stamp attack` or
2812
- // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2813
- let outcome: string | null = null;
2814
- // The delegation ledger: this run's commit window, recorded however it ended — a
2815
- // hard-cut worker's commits still sit on the branch, and a window the gate never learned
2816
- // about reads as driver-authored work at flow verify. One count serves both: the picker row and the ledger.
2817
- let runCommits = 0;
2818
- if (op === "run" && headBefore.ok && headAfter.ok) {
2819
- const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
2820
- runCommits = c.ok ? Number.parseInt(c.out.trim(), 10) || 0 : 0;
2821
- try {
2822
- mkdirSync(path.dirname(delegationLog), { recursive: true });
2823
- appendFileSync(delegationLog, `${delegationLine(now(), st.stage, headBefore.out.trim(), headAfter.out.trim(), runCommits)}\n`);
2824
- } catch { /* an index that failed to append is never a reason to lose the run */ }
2825
- }
2826
- if (clean) {
2827
- if (runCommits > 0) outcome = `${runCommits} commit${runCommits === 1 ? "" : "s"}`;
2828
- if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
2829
- if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
2830
- } else {
2831
- outcome = timedOut ? "hard-cut" : "crashed";
2832
- }
2833
- worker.rename(workerName(clean ? "✓" : "✗", glyph, seq, label, outcome));
2834
- // never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
2835
- // via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
2836
- let snapshot: string | null = null;
2837
- const dirty = await sh("git status --porcelain", work);
2838
- if (dirty.ok && dirty.out.trim()) {
2839
- const snapDir = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR);
2840
- mkdirSync(snapDir, { recursive: true });
2841
- const stamp = Date.now();
2842
- const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
2843
- const idx = path.join(snapDir, `.snap-index-${stamp}`);
2844
- const snapRun = await sh(`GIT_INDEX_FILE=${sq(idx)} git read-tree HEAD && GIT_INDEX_FILE=${sq(idx)} git add -A && T=$(GIT_INDEX_FILE=${sq(idx)} git write-tree) && git diff HEAD "$T" > ${sq(diffFile)}; rm -f ${sq(idx)}`, work);
2845
- if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
2846
- }
2847
- // An implement worker dirtied tier-1 records through the same hooks any edit dirties them, so
2848
- // the check reruns here: it runs on the driver's binding and its verdict rides along in the
2849
- // digest. A check-only op touched nothing (proved below), so its records still stand — and
2850
- // re-running a whole suite here would spend it twice and hide the gate's own re-run.
2851
- const check = op === "run" ? await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx)) : null;
2852
- // the PASS is stamped AFTER the rerun so it belongs to the settled tree, and only over a tree
2853
- // the reviewer actually left untouched — this stamp is what flow verify demands at the gate
2854
- let stamped = false;
2855
- let cleared = false;
2856
- if (verify?.verdict === "pass" && clean && !moved) {
2857
- const fresh = readState(ctx.cwd, st.slug);
2858
- if (fresh) {
2859
- recordVerifyPass(fresh, now(), await verifyStampFingerprint(ctx.cwd, fresh));
2860
- writeState(ctx.cwd, fresh);
2861
- stamped = true;
2862
- }
2863
- } else if (verify?.verdict === "fail" && !moved) {
2864
- // a FAIL over an unmoved tree contradicts any earlier PASS — the gate may not ask
2865
- // Verified? against a tree its newest checker rejected
2866
- const fresh = readState(ctx.cwd, st.slug);
2867
- if (fresh?.checks[VERIFY_STAMP]) {
2868
- delete fresh.checks[VERIFY_STAMP];
2869
- writeState(ctx.cwd, fresh);
2870
- cleared = true;
2871
- }
2872
- }
2873
- const parts: string[] = [];
2874
- if (report) parts.push(renderStageReport(report));
2875
- if (verify) {
2876
- parts.push(renderVerifyReport(verify));
2877
- if (stamped) parts.push(`PASS stamped on this tree — flow verify will accept it until the tree moves (any edit drops it like a tier-1 record, then a fresh verify worker is owed).`);
2878
- if (cleared) parts.push("an earlier PASS over this tree was DROPPED — this FAIL contradicts it; fix the findings, then a fresh verify worker is owed.");
2879
- else if (moved) parts.push(`VERDICT VOID: the verify worker moved the tree, HEAD, branch pointer or plan (the before/after proof differs from before its run) — a reviewer that edits invalidates its own report.${snapshot ? ` Snapshot: ${snapshot}` : ""}`);
2880
- else if (!clean) parts.push("no verdict recorded from a crashed or interrupted run — rerun the verify worker.");
2881
- else parts.push(`the verify gate will refuse Verified? until a verify worker returns verdict: pass over the current tree${verify.verdict === "fail" ? " (this one returned FAIL — fix the findings, then rerun)" : ""}.`);
2882
- }
2883
- if (findings) {
2884
- if (findings.missing) parts.push("reflect worker ended WITHOUT tagged findings — nothing parsed as [playbook]/[plugin]; its tail is below, read it before concluding the review found nothing:", "```", findings.rawTail, "```");
2885
- else {
2886
- parts.push(
2887
- `playbook findings (${findings.playbook.length}):`, ...(findings.playbook.length ? findings.playbook.map((x) => `[playbook] ${x}`) : ["- none"]),
2888
- `plugin findings (${findings.plugin.length}):`, ...(findings.plugin.length ? findings.plugin.map((x) => `[plugin] ${x}`) : ["- none"]),
2889
- ...(findings.other.length ? ["other:", ...findings.other.map((x) => `[neither] ${x}`)] : []),
2890
- "put the findings to the operator (Fold? Fix? Drop?) — queue what they fold with flow reflect --playbook|--plugin; the worker queued nothing.",
2891
- );
2892
- }
2893
- }
2894
- if (run.softFired) parts.push(`worker was steered to close out at its ${budgetMin}-min budget${timedOut ? " and still needed the hard cut — treat the report as mid-stage" : " — committed and reported by choice"}`);
2895
- if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
2896
- if (crash) parts.push(`worker run ended with an error: ${crash}`);
2897
- if (snapshot && !verify) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2898
- parts.push(check ? `tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}` : "tier-1 untouched: a check-only worker leaves the tree (and the records) as it found them — flow check / flow verify rerun what the tree still owes.");
2899
- parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}\nindexed in: ${transcriptLog}${lineage.file && transcript ? `\nlineage: nested under ${lineage.file} in pi's picker (Threaded, Current Folder)` : ""}`);
2900
- const failed = !!crash || timedOut || moved;
2901
- // the family belongs on the settled card and the result only: a live frame redraws on every
2902
- // worker tool call, and reading a session bucket is IO. This run is excluded — the card names
2903
- // its transcript already, and repeating it as a bare row reads like a different worker.
2904
- const famFromPicker = await workerFamilyLines(ctx, transcript || undefined);
2905
- const fam = famFromPicker ?? ledgerFamilyLines(transcriptLog, transcript || undefined);
2906
- emit(failed ? "dev-flow:worker-failed" : "dev-flow:worker-completed", {
2907
- elapsedMs: Date.now() - run.startedAt, usage: run.usage, turns: run.turns, budgetMin, softFired: run.softFired, timedOut, crash,
2908
- verdict: verify?.verdict ?? null, reportMissing: report?.missing ?? findings?.missing ?? false, transcript, snapshot,
2909
- });
2910
- const card = cardView(failed ? "failed" : "done", { verdict: verify?.verdict ?? null, transcript });
2911
- return {
2912
- content: [{ type: "text" as const, text: parts.join("\n\n") }],
2913
- details: {
2914
- op, slug: st.slug, stage: st.stage, card, cardFull: stageCardLines({ kind, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state: failed ? "failed" : "done", verdict: verify?.verdict ?? null, transcript, family: fam?.length ? fam : undefined, familyHeading: famFromPicker === null ? familyHeading({ ledger: true }) : undefined }, true),
2915
- done: report?.done, files: report?.files, notes: report?.notes, blockers: report?.blockers, reportMissing: report?.missing ?? findings?.missing ?? false,
2916
- verdict: verify?.verdict ?? null, stamped, clearedStamp: cleared, verdictVoided: moved, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot,
2917
- },
2918
- usage: run.usage,
2919
- isError: failed,
2920
- };
2191
+ } catch (e) {
2192
+ crash = e instanceof Error ? e.message : String(e);
2921
2193
  } finally {
2922
- stageRuns.delete(key);
2923
- if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", undefined);
2924
- try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
2194
+ clearTimeout(timer);
2195
+ signal?.removeEventListener("abort", abortChild);
2196
+ unsub?.();
2197
+ runningWorkers.delete(key);
2198
+ }
2199
+ const transcript = (() => { try { return child?.sessionManager.getSessionFile() ?? ""; } catch { return ""; } })();
2200
+ const headAfter = (await git("git rev-parse HEAD")).trim();
2201
+ const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
2202
+ const dirty = (await git("git status --short")).trim();
2203
+ const outcome = crash ? `crashed: ${crash}` : timedOut ? `interrupted at the ${budgetMin}-min budget` : report.found ? "reported" : `ended without REPORT after ${nudges} nudge(s)`;
2204
+ try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
2205
+ try { child?.setSessionName(`${report.found && !crash && !timedOut ? "✓" : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2206
+ const parts = [
2207
+ `${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`,
2208
+ report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : `no REPORT — last words:\n${report.body}`,
2209
+ `new commits:\n${newCommits.trim() || "(none)"}`,
2210
+ `uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
2211
+ ];
2212
+ if (wop === "implement") {
2213
+ const check = await runFlow(["check"], root, uiFrom(ctx), sessFor(ctx, root));
2214
+ parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
2215
+ } else if (newCommits.trim() || dirty) {
2216
+ parts.push("note: the reviewer changed the tree — treat its verdict with suspicion and inspect the change");
2925
2217
  }
2218
+ parts.push(`transcript: ${transcript || "(unknown)"}`);
2219
+ parts.push(wop === "implement" ? "Next: read the report, decide what is left, and drive the gates yourself." : "Advisory review: fix what is real (inline is fine for small things), then carry on — no gate waits on this verdict.");
2220
+ return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
2926
2221
  },
2927
2222
  });
2928
2223
  pi.registerTool(stageWorkerTool);
@@ -2930,30 +2225,33 @@ export default function devFlow(pi: ExtensionAPI) {
2930
2225
  // Agent-run gates refresh at turn_end (tool ctx lacks setStatus; turn_end catches them).
2931
2226
  pi.on("session_start", async (_event, ctx) => {
2932
2227
  if (!guardsAreMine()) return;
2933
- rebuildSession(ctx);
2934
- refreshStatus(ctx);
2228
+ const root = await flowRoot(ctx.cwd);
2229
+ rebuildSession(ctx, root);
2230
+ refreshStatus(ctx, root);
2935
2231
  });
2936
2232
  pi.on("session_tree", async (_event, ctx) => {
2937
2233
  if (!guardsAreMine()) return;
2938
- rebuildSession(ctx);
2234
+ rebuildSession(ctx, await flowRoot(ctx.cwd));
2939
2235
  });
2940
2236
  // The session, not the process, owns the binding and the claim: pi-web keeps serving other sessions
2941
2237
  // after one ends, and a stale claim there is a permanent lock (its pid is the server's, always alive).
2942
2238
  pi.on("session_shutdown", async (_event, ctx) => {
2943
2239
  if (!guardsAreMine()) return;
2944
- if (!existsSync(dfDir(ctx.cwd))) return;
2945
- releaseSession(ctx.cwd, sessionKey(ctx));
2240
+ const root = await flowRoot(ctx.cwd);
2241
+ if (!existsSync(dfDir(root))) return;
2242
+ releaseSession(root, sessionKey(ctx));
2946
2243
  });
2947
2244
  pi.on("turn_end", async (_event, ctx) => {
2948
2245
  if (!guardsAreMine()) return;
2949
- refreshStatus(ctx);
2246
+ const root = await flowRoot(ctx.cwd);
2247
+ refreshStatus(ctx, root);
2950
2248
  // pi checks its compaction threshold between every turn; our safe points must be as frequent.
2951
- maybeCompactNow(ctx);
2249
+ maybeCompactNow(ctx, root);
2952
2250
  });
2953
2251
  // Idle backstop: long between-gate runs compact here instead of letting pi hit the threshold mid-work.
2954
2252
  pi.on("agent_settled", async (_event, ctx) => {
2955
2253
  if (!guardsAreMine()) return;
2956
- maybeCompactNow(ctx);
2254
+ maybeCompactNow(ctx, await flowRoot(ctx.cwd));
2957
2255
  });
2958
2256
  // pi forcing a threshold compaction while a flow is bound means our safe-point pacing missed — rebuild the
2959
2257
  // summary here with flow-aware instructions and hand it back through the event's custom-compaction channel.
@@ -2963,9 +2261,10 @@ export default function devFlow(pi: ExtensionAPI) {
2963
2261
  // overflow is never taken over (cancelling it would drop pi's compact-and-retry); manual is the operator's or ours.
2964
2262
  pi.on("session_before_compact", async (event, ctx) => {
2965
2263
  if (!guardsAreMine()) return undefined;
2966
- if (!initiated(ctx.cwd)) return undefined;
2264
+ const root = await flowRoot(ctx.cwd);
2265
+ if (!initiated(root)) return undefined;
2967
2266
  const key = sessionKey(ctx);
2968
- const st = boundFeature(ctx.cwd, key);
2267
+ const st = boundFeature(root, key);
2969
2268
  if (!shouldTakeOverCompaction({ reason: event.reason, bound: !!st, inFlight: compacting.has(key) })) return undefined;
2970
2269
  const model = ctx.model;
2971
2270
  if (!model) return undefined;
@@ -2984,24 +2283,15 @@ export default function devFlow(pi: ExtensionAPI) {
2984
2283
  compacting.delete(key);
2985
2284
  }
2986
2285
  });
2987
- // pi forcing its own compaction while a flow is bound means the pacing was wrong — park a note for the operator.
2988
- pi.on("session_compact", async (event, ctx) => {
2286
+ // Whatever the reason, the summary replaced the transcript — the core the first run injected is gone
2287
+ // from context, so the next run pays it once more (manual compactions included: our own safe-point
2288
+ // compaction is the common one). Durable too: a branch whose newest skill entry is stale tells a
2289
+ // reloaded session to pay the core again.
2290
+ pi.on("session_compact", async (_event, ctx) => {
2989
2291
  if (!guardsAreMine()) return;
2990
- if (!initiated(ctx.cwd)) return;
2991
- // Whatever the reason, the summary replaced the transcript — the core the first run injected is
2992
- // gone from context, so the next run pays it once more (manual compactions included: our own
2993
- // safe-point compaction is the common one).
2292
+ if (!initiated(await flowRoot(ctx.cwd))) return;
2994
2293
  coreStale.add(sessionKey(ctx));
2995
- // Durable too: a compaction the session survives a reload outlives the in-memory flag, and a
2996
- // branch whose newest skill entry is stale tells the restored run to pay the core again.
2997
2294
  pi.appendEntry("dev-flow-skill", { core: true, stale: true });
2998
- if (event.reason === "manual") return;
2999
- const st = boundFeature(ctx.cwd, sessionKey(ctx));
3000
- if (!st) return;
3001
- const f = path.join(dfDir(ctx.cwd), "reflections.md");
3002
- const text = existsSync(f) ? readFileSync(f, "utf8") : "";
3003
- const line = compactionReflectionLine(st.slug, st.stage, event.reason, new Date().toISOString().slice(0, 10));
3004
- writeFileSync(f, appendReflection(text, ["plugin"], line));
3005
2295
  });
3006
2296
 
3007
2297
  pi.on("tool_call", async (event, ctx) => {
@@ -3019,9 +2309,7 @@ export default function devFlow(pi: ExtensionAPI) {
3019
2309
  // an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
3020
2310
  // the guards, the no-playbook bash-timeout default included
3021
2311
  if (noDf) return undefined;
3022
- // Everything below that reads flow truth reads it from here: in a feature worktree that is the main
3023
- // checkout (see flowRoot), which is what makes owner attribution — and the worker half of the
3024
- // implement guard — reachable for the session that was actually sent to do the work.
2312
+ // flow truth lives in the main checkout even when the session runs inside a feature worktree
3025
2313
  const guardRoot = await flowRoot(ctx.cwd);
3026
2314
  const cfg = loadProject(dfDir(guardRoot)).cfg;
3027
2315
  const mustStateTimeout = shellCmd !== "" && explicitTimeout === undefined && cfg.bashTimeout === "require";
@@ -3041,22 +2329,9 @@ export default function devFlow(pi: ExtensionAPI) {
3041
2329
  const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
3042
2330
  if (why) return { block: true, reason: why };
3043
2331
  }
3044
- // A registered worker session is the one allowed to write a normal feature's worktree at
3045
- // implement — that is what it was sent to do (see writeGuard's byWorker).
3046
- // repoRoot stays the session's own checkout: the scratch rule asks where the BYTES land, and a
3047
- // project that parks its worktrees outside the checkout (or under the temp dir) must not have
3048
- // those writes read as a throwaway because the flow truth was resolved elsewhere.
3049
- const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd, byWorker: isWorkerSession(ctx.sessionManager?.getSessionId?.()) });
3050
- if (reason) return { block: true, reason };
3051
- // Editing a worktree invalidates that feature's tier-1 checks and tier-2 confirmation until they rerun.
3052
- const owner = feats.find((f) => f.worktreeAbs && abs.startsWith(f.worktreeAbs + path.sep));
3053
- if (owner && (owner.state.stage === "implement" || owner.state.stage === "pre-release") && (Object.keys(owner.state.checks).length || owner.state.confirmations?.implement)) {
3054
- owner.state.checks = {};
3055
- delete owner.state.confirmations?.implement;
3056
- // the owner's state lives in the flow-truth root, not in the worktree's own .dev-flow/ copy
3057
- writeState(guardRoot, owner.state);
3058
- }
3059
- return undefined;
2332
+ const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd });
2333
+ // a stale green is caught where it matters: verify and release fingerprint the worktree (freshenChecks)
2334
+ return reason ? { block: true, reason } : undefined;
3060
2335
  }
3061
2336
 
3062
2337
  if (isToolCallEventType("bash", event)) {
@@ -3090,6 +2365,11 @@ export default function devFlow(pi: ExtensionAPI) {
3090
2365
  const why = await askOperator(ctx, command, mv.confirm);
3091
2366
  if (why) return { block: true, reason: why };
3092
2367
  }
2368
+ // shipping on the forge (PR merge, release page) is release-stage work for a bound feature
2369
+ if (/\b(?:gh|glab)\b/.test(command)) {
2370
+ const ro = releaseOrderInvocation(command, boundFeature(guardRoot, key)?.stage ?? null);
2371
+ if (ro) return { block: true, reason: ro };
2372
+ }
3093
2373
  const inv = gitInvocation(command);
3094
2374
  if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
3095
2375
  const bound = boundFeature(guardRoot, key);
@@ -3132,12 +2412,15 @@ export default function devFlow(pi: ExtensionAPI) {
3132
2412
  }
3133
2413
  const reason = bashFlowGuard({ command: g.seg, branch, stage: bound?.stage ?? null, defaultBranch: cfg.defaultBranch, pushRefs, playbookChore, dir: gitDir, attribution: bound ? undefined : `not attributed to a bound feature (session ${key}; dev-flow ${loadedVersion() ?? "?"} at ${SELF_BUILD.dir}) — run flow use <slug> here if a binding is missing` });
3134
2414
  if (reason) return { block: true, reason };
2415
+ // A feature worktree stays on its feature branch: a side branch cut inside it repurposes the
2416
+ // worktree (and leaves it off its branch for the next gate); out-of-flow fixes get their own flow.
2417
+ const co = checkoutInvocation(g.seg);
2418
+ if (!co) continue;
2419
+ const homeWt = worktrees.find((w) => gitDir === w || gitDir.startsWith(w + path.sep));
2420
+ 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)` };
3135
2421
  // Branch discipline: feature branches live in their worktree — never checked out or created (-b) in the main checkout
3136
- const target = checkoutTarget(g.seg);
3137
- if (target && target.startsWith(featureBranchPrefix(cfg))) {
3138
- const inWorktree = worktrees.some((w) => gitDir === w || gitDir.startsWith(w + path.sep));
3139
- 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` };
3140
- }
2422
+ if (!homeWt && co.target.startsWith(featureBranchPrefix(cfg)))
2423
+ 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` };
3141
2424
  }
3142
2425
  }
3143
2426
  return undefined;
@@ -3145,39 +2428,34 @@ export default function devFlow(pi: ExtensionAPI) {
3145
2428
 
3146
2429
  pi.on("before_agent_start", async (_event, ctx) => {
3147
2430
  if (!guardsAreMine()) return undefined;
3148
- // One [dev-flow] line per run, whatever number of copies of this package are installed.
3149
- // The same package reaches one runtime twice all the time (a project pin beside the npm install,
3150
- // or this checkout's .pi/extensions pointer beside it) and pi dedupes extensions by file path
3151
- // only, so both copies answer and the line lands twice in the prompt. pi hands every handler of
3152
- // a run the same ctx object, so the first pass claims the run and the rival stays silent.
2431
+ // One [dev-flow] line per run, whatever number of copies of this package are installed. The same
2432
+ // package can reach one runtime twice (a project pin beside the npm install) and pi dedupes
2433
+ // extensions by file path only; equal-version copies both pass the election, so the first pass
2434
+ // claims the run (pi hands every handler of a run the same ctx object) and the rival stays silent.
3153
2435
  const run = ctx as unknown as Record<symbol, boolean | undefined>;
3154
2436
  if (run[CONTEXT_EMITTED]) return undefined;
3155
2437
  run[CONTEXT_EMITTED] = true;
3156
2438
  // repaint the footer at the start of every run: the session_start push can land before a web
3157
2439
  // client attaches, and this is the earliest point the client is certainly listening
3158
- refreshStatus(ctx);
3159
- if (!initiated(ctx.cwd)) return undefined;
3160
- // A stage worker's whole instruction is its brief. The driver's context is wrong there twice over:
3161
- // the unbound posture tells it to pre-plan and `flow start`, and the branch check reads its
3162
- // worktree as a main checkout on the wrong branch. Guards still run — they hang off tool_call.
3163
- if (isWorkerSession(ctx.sessionManager?.getSessionId?.())) return undefined;
2440
+ const root = await flowRoot(ctx.cwd);
2441
+ refreshStatus(ctx, root);
2442
+ if (!initiated(root)) return undefined;
2443
+ try { if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined; } catch { /* not a worker */ }
3164
2444
  const key = sessionKey(ctx);
3165
2445
  // The playbook core rides along on the message this run writes anyway — once per session.
3166
2446
  const core = corePreamble(key);
3167
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
3168
- const state = boundFeature(ctx.cwd, key);
3169
- if (!state || state.stage === "done") {
2447
+ const cfg = loadProject(dfDir(root)).cfg;
2448
+ const state = boundFeature(root, key);
2449
+ if (!state) {
3170
2450
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
3171
- let content = "[dev-flow] no flow bound. Every request goes through flow. New work — pre-plan first (see the skill): analyze read-only, bring findings + questions + a direction with a proposed slug/mode to the operator, and flow start <slug> only once they say start; unfinished feature: flow use <slug>.";
3172
- const cb = claimBlocker(ctx.cwd, key);
3173
- if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (${claimWho(cb.claim)}) — flow use ${cb.state.slug} takes it over explicitly.`;
3174
- // only the main checkout has a "main checkout branch": a session opened in a linked worktree is
3175
- // on its feature branch by construction, and calling that a drift misleads it
3176
- const curBr = (await isLinkedWorktree(ctx.cwd)) ? "" : await currentBranch(ctx.cwd);
2451
+ let content = "[dev-flow] no flow bound. Every request goes through flow. New work: flow start <slug>; unfinished feature: flow use <slug>.";
2452
+ const cb = claimBlocker(root, key);
2453
+ 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.`;
2454
+ const curBr = await currentBranch(root);
3177
2455
  if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
3178
- const refl0 = readReflections(ctx.cwd);
2456
+ const refl0 = readReflections(root);
3179
2457
  if (refl0.length) content += ` Also: ${refl0.length} reflection(s) open — run flow doctor.`;
3180
- const rmap0 = roadmapOpenCount(readRoadmap(ctx.cwd));
2458
+ const rmap0 = roadmapOpenCount(readRoadmap(root));
3181
2459
  if (rmap0) content += ` Also: ${rmap0} roadmap item(s) open — flow roadmap lists them, flow roadmap pick <n> <slug> hands one to flow start.`;
3182
2460
  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).`;
3183
2461
  return { message: { customType: "dev-flow-context", display: false, content: `${core}${content}` } };
@@ -3193,9 +2471,9 @@ export default function devFlow(pi: ExtensionAPI) {
3193
2471
  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.");
3194
2472
  const pend = checklistPending(cfg, state, state.stage);
3195
2473
  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" : ""}`);
3196
- const refl = readReflections(ctx.cwd);
2474
+ const refl = readReflections(root);
3197
2475
  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).`);
3198
- const rmap = roadmapOpenCount(readRoadmap(ctx.cwd));
2476
+ const rmap = roadmapOpenCount(readRoadmap(root));
3199
2477
  if (rmap) guidance.push(`◇ ${rmap} roadmap item(s) open — flow roadmap lists them (pick only on the operator's word).`);
3200
2478
  return {
3201
2479
  message: {