pi-dev-flow 0.71.0 → 0.73.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,21 +33,15 @@ 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
43
  checkoutTarget,
52
44
  claimBlocks,
53
- clampStageBudgetMin,
54
45
  classifyMergeHistory,
55
46
  cmpVersions,
56
47
  cleanupAssess,
@@ -66,8 +57,6 @@ import {
66
57
  gateHelpJson,
67
58
  gitInvocation,
68
59
  githubSlug,
69
- DELEGABLE_STAGES,
70
- isDelegableStage,
71
60
  guardBash,
72
61
  guardPath,
73
62
  healthProbe,
@@ -114,52 +103,7 @@ import {
114
103
  roadmapTidy,
115
104
  shouldSelfCompact,
116
105
  shouldTakeOverCompaction,
117
- TRANSCRIPTS_FILE,
118
- stageCardLines,
119
- stageElapsedLabel,
120
106
  stageGuidance,
121
- stageInterruptSteer,
122
- stageLiveAssistantLine,
123
- stageLiveLine,
124
- stageLiveResultLine,
125
- stageUsageLine,
126
- summarizeToolArgs,
127
- VERIFY_STAMP,
128
- VERIFY_STAMP_REFUSAL,
129
- WORKER_OP_BUDGET_MIN,
130
- WORKER_OP_GLYPH,
131
- WORKER_OP_TOOLS,
132
- type StageUsage,
133
- type WorkerOp,
134
- buildReflectBrief,
135
- buildVerifyBrief,
136
- isWorkerOp,
137
- liveClip,
138
- liveTail,
139
- parseReflectFindings,
140
- parseVerifyReport,
141
- parseWorkerTranscripts,
142
- planFingerprint,
143
- recordVerifyPass,
144
- renderVerifyReport,
145
- verifyStampMissing,
146
- sessionPathKey,
147
- sessionHeaderParent,
148
- parseSessionSummary,
149
- markWorkerSession,
150
- isWorkerSession,
151
- orphanWorktreeBuckets,
152
- claimAge,
153
- processStart,
154
- type WorktreeBucketFeature,
155
- workerFamily,
156
- workerFamilyCount,
157
- WORKER_FAMILY_ITEMS,
158
- workerOpError,
159
- workerTranscriptLine,
160
- type WorkerSessionRow,
161
- workerName,
162
- sanitizeWorkerLabel,
163
107
  stateTamper,
164
108
  statusFor,
165
109
  statusJson,
@@ -170,6 +114,16 @@ import {
170
114
  verifyGate,
171
115
  versionTagGate,
172
116
  writeGuard,
117
+ mainCheckoutRoot,
118
+ buildWorkerBrief,
119
+ clampBudgetMin,
120
+ parseWorkerReport,
121
+ workerOpError,
122
+ WORKER_NUDGE,
123
+ WORKER_NUDGES,
124
+ type WorkerOp,
125
+ releaseOrderInvocation,
126
+ branchCreateTarget,
173
127
  type BranchState,
174
128
  type Config,
175
129
  type FeatureRef,
@@ -177,7 +131,6 @@ import {
177
131
  type StageCheck,
178
132
  type PushRef,
179
133
  type SessionClaim,
180
- type DelegableStage,
181
134
  } from "../src/core.ts";
182
135
  import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
183
136
  import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
@@ -250,13 +203,7 @@ function copyWarning(): string | null {
250
203
  }
251
204
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
252
205
  * entries and asserts the warnings the real duplicate would print. */
253
- export const testSeams = {
254
- copies: COPIES,
255
- skillCore: { value: undefined as string | null | undefined },
256
- /** Where `flow doctor` looks for pi's session buckets; tests point it at a scratch dir so the suite
257
- * never reads the operator's real session store. `undefined` = `<agent dir>/sessions`. */
258
- sessionsRoot: { value: undefined as string | null | undefined },
259
- };
206
+ export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined } };
260
207
 
261
208
  interface Ui {
262
209
  hasUI: boolean;
@@ -387,7 +334,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
387
334
  }
388
335
 
389
336
  const GATE_HELP =
390
- "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";
337
+ "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|list|tidy|move <n> --plugin|--playbook] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — start preflights the playbook before creating anything: it prints playbook gaps and warns when the session runs an older dev-flow build than the disk ships (in the dev-flow repo, an older build than this checkout's own manifest), and it refuses until a merge policy is set (ask the operator squash / merge / rebase / any in chat, then re-run with --merge=<style> --confirmed — the answer is written into project.md and enforced from then on: gh/glab merges that contradict it are blocked, and release-done proves what actually landed); version prints the build the disk says to run (this checkout's own manifest in the dev-flow repo, the installed package's elsewhere) and names any other dev-flow copies registered in the same process (--check-upstream also asks the registry for the published one) — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there; --plugin / --playbook / --both state the section instead of leaving it to the wording, and the echo prints why the note landed where it did); reflect list numbers the open items with their section; reflect move <n> --plugin|--playbook re-files one of them; reflect tidy drops the closed (`- [x]`) items from reflections.md — every surface that queues or reviews reflections nudges when the checked-off pile grows; bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --ui/--patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned); when the session runs an older dev-flow build than the checkout, release names both builds, lists what the running code can no longer prove, and asks the operator update (/reload) or proceed with the old release — an operator decision recorded in state and repeated by release-done, never a block";
391
338
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
392
339
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
393
340
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -408,8 +355,7 @@ function writeState(root: string, state: FlowState): void {
408
355
  * truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
409
356
  * and every recorded check, with the folder gitignored so nothing else could restore it. */
410
357
  function atomicWrite(file: string, text: string): void {
411
- // per-process temp name: two sessions writing the same file must not rename each other's half-write
412
- const tmp = `${file}.${process.pid}.tmp`;
358
+ const tmp = `${file}.tmp`;
413
359
  writeFileSync(tmp, text);
414
360
  renameSync(tmp, file);
415
361
  }
@@ -457,183 +403,6 @@ function skillCore(): string | null {
457
403
  /** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
458
404
  export const compactionTakeover: { run: typeof compact } = { run: compact };
459
405
 
460
- /** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
461
- * `.run` with a stub, so the worker contract stays testable without spending a model and tests
462
- * never touch the real session directory. The real spawn stamps lineage: the worker's header
463
- * carries `parentSession` → the driver's own session file, and its transcript goes into the
464
- * driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
465
- * scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
466
- * as /handoff can do the same"). The live ⏳ name is written straight onto the session before its
467
- * first prompt: pi emits `session_start` only from `bindExtensions()`, which an SDK-created worker
468
- * never runs, so a name set from a `session_start` handler never lands — every worker used to run
469
- * under whatever an auto-namer derived from its brief ("you-are-a-dev"). Named before the prompt,
470
- * an auto-namer sees a name that is not its own and leaves it alone. The same channel carries the
471
- * ⏳ → ✓/✗ rename. The worker is also registered as a worker, so the dev-flow copy its loader runs
472
- * keeps its guards but injects none of the driver's context (see `isWorkerSession`). */
473
-
474
- export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
475
-
476
- /** The worker's session manager, built exactly as the real seam builds it — split out so a test can
477
- * drive the production composition (header link + driver's bucket) without spawning a model.
478
- * Both or neither: `dir` is the driver's own bucket read off the live manager, so a custom
479
- * PI_CODING_AGENT_DIR can never strand a worker in a different agent dir from its driver, and pi's
480
- * private `--<encoded cwd>--` directory encoding is never duplicated here. */
481
- export function workerSessionManager(work: string, parent?: string, dir?: string): SessionManager | undefined {
482
- return parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
483
- }
484
-
485
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
486
- run: async ({ work, model, name, tools, parent, dir }) => {
487
- const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
488
- await loader.reload();
489
- const sessionManager = workerSessionManager(work, parent, dir);
490
- const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
491
- // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
492
- // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
493
- // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
494
- try { markWorkerSession(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the driver context */ }
495
- const rename = (n: string) => { try { session.setSessionName(n); } catch { /* naming is visibility, not function */ } };
496
- rename(name);
497
- return { session, rename };
498
- },
499
- };
500
-
501
- /** Seam that reads the driver's session bucket the way the picker does — a stub in the smoke suite,
502
- * because a test must not scan the operator's real session directory. `listAll(dir)`, not
503
- * `list(cwd, dir)`: pi's `list` drops rows whose header cwd is not `cwd` whenever it is handed a
504
- * directory that is not that cwd's default — which is precisely a stage worker (header cwd = the
505
- * worktree, file in the driver's bucket), and precisely the layout a configured `sessionDir`
506
- * creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
507
- * the family list and the tree agree there; under a configured session dir the text view stays
508
- * complete even where that scope hides the worker, which is the cheaper direction to err in. */
509
- export const sessionRowsScan: { run: (o: { cwd: string; dir?: string; parent?: string }) => Promise<WorkerSessionRow[]> } = {
510
- run: async ({ dir, parent }) => {
511
- // no bucket or no driver file to match: the old full listing (a host that never reaches here in practice)
512
- 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 }));
513
- return scanFamilyRows(dir, parent);
514
- },
515
- };
516
-
517
- /** Header bytes read per transcript in the family scan's cheap pass — the same budget pi gives its own
518
- * header reads. A pi header line is a few hundred bytes. */
519
- const SESSION_HEADER_BYTES = 4096;
520
-
521
- /** The family read in two passes, so its cost follows the family, not the bucket: the first line of
522
- * every transcript (≤ 4 KB each) names its parent; only the files whose parent is `parent` are read
523
- * in full. `listAll(dir)` parsed every transcript in the bucket — ~15 ms per MB, and a driver bucket
524
- * only grows (the dev-flow checkout's was 55 MB, ~0.8 s for every idle status and settled card).
525
- * `fullReads` counts the second pass for the smoke suite. */
526
- export async function scanFamilyRows(dir: string, parent: string, fullReads?: { n: number }): Promise<WorkerSessionRow[]> {
527
- let names: string[];
528
- try { names = (await readdirAsync(dir)).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
529
- const want = sessionPathKey(parent);
530
- const rows: WorkerSessionRow[] = [];
531
- await Promise.all(names.map(async (n) => {
532
- const file = path.join(dir, n);
533
- let head = "";
534
- try {
535
- const fh = await openFile(file, "r");
536
- try {
537
- const buf = Buffer.alloc(SESSION_HEADER_BYTES);
538
- const { bytesRead } = await fh.read(buf, 0, SESSION_HEADER_BYTES, 0);
539
- head = buf.subarray(0, bytesRead).toString("utf8");
540
- } finally { await fh.close(); }
541
- } catch { return; }
542
- const p = sessionHeaderParent(head);
543
- if (!p || sessionPathKey(p) !== want) return;
544
- try {
545
- if (fullReads) fullReads.n++;
546
- const [text, st] = await Promise.all([readFileAsync(file, "utf8"), statAsync(file)]);
547
- const row = parseSessionSummary(text, file, st.mtimeMs);
548
- if (row) rows.push(row);
549
- } catch { /* a transcript deleted mid-scan is simply not in the family */ }
550
- }));
551
- return rows;
552
- }
553
-
554
- /** Where this session's own transcripts live, when it has any: the file the worker links to, and the
555
- * bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
556
- * which is a fact to print, never an error to raise. */
557
- function lineageOf(ctx: ExtensionContext): { file: string | null; dir: string | null } {
558
- try {
559
- return { file: ctx.sessionManager.getSessionFile() ?? null, dir: ctx.sessionManager.getSessionDir() ?? null };
560
- } catch { /* an in-memory or otherwise unbacked session says so here */ return { file: null, dir: null }; }
561
- }
562
-
563
- /** With no file-backed lineage to read — an unbacked host, or a driver pi never wrote a file for —
564
- * the ledger is what the flow knows: every worker it recorded, newest first. Coarser than the
565
- * picker's data (no message count, no rename), so the status heading names the source. */
566
- function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
567
- try {
568
- const drop = exclude ? sessionPathKey(exclude) : null;
569
- const mine = parseWorkerTranscripts(readFileSync(logPath, "utf8")).filter((r) => !drop || sessionPathKey(r.path) !== drop);
570
- const shown = mine.slice(-WORKER_FAMILY_ITEMS).reverse().map((r) => `${r.op} · ${r.at} · ${r.path}`);
571
- return mine.length > shown.length ? [...shown, familyFoldLine(mine.length - shown.length)] : shown;
572
- } catch { return []; }
573
- }
574
-
575
- /** Bucket reads are the one IO-bound thing the family view does: one header read per transcript in
576
- * the driver's bucket, plus a full read of each worker (`scanFamilyRows`). A host renders a running
577
- * worker by calling status repeatedly, so that path is allowed a slightly stale read; the places the
578
- * operator draws a conclusion from — idle status, the settled card — always re-read. */
579
- const BUCKET_FRESH_MS = 2000;
580
- const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
581
-
582
- async function bucketRows(ctx: ExtensionContext, dir: string | null, parent: string, staleMs = 0) {
583
- const key = `${dir ?? "(default bucket)"}\0${parent}`;
584
- const hit = bucketCache.get(key);
585
- // staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
586
- // and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
587
- // condition also holds inside the caller's own millisecond, and a fast host got the previous read back
588
- // as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
589
- // as the call before it printed the family that had just gone empty).
590
- if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
591
- const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined, parent });
592
- if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
593
- bucketCache.set(key, { at: Date.now(), rows });
594
- return rows;
595
- }
596
-
597
- /** The flow's workers as lines, newest first — `null` when this session has no file to be a parent of,
598
- * which is when the caller reaches for `ledgerFamilyLines` instead.
599
- * Deliberately read from the picker's own data, not from a dev-flow index: renames, deletions and
600
- * workers an older session already delegated all read back correctly for free. `exclude` drops one
601
- * transcript: the caller already shows that run, and meeting it again as an anonymous row under
602
- * "other workers" reads like somebody else's work belongs to this flow. */
603
- async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleMs = 0): Promise<string[] | null> {
604
- const { file, dir } = lineageOf(ctx);
605
- if (!file) return null;
606
- try {
607
- return workerFamily(await bucketRows(ctx, dir, file, staleMs), file, { exclude });
608
- } catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
609
- }
610
-
611
- /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
612
- export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
613
-
614
-
615
- /** What a live worker run knows about itself — the one-worker-per-session guard and the ledger the
616
- * `op: "status"` verb reads. `lastLines` mirrors the live log (bounded); usage and turns accumulate
617
- * per run so the card and the result can say what the worker cost. */
618
- interface StageRun {
619
- startedAt: number;
620
- budgetMin: number;
621
- softFired: boolean;
622
- work: string;
623
- lastLines: string[];
624
- op: WorkerOp;
625
- /** "🔨 implement" / "🔍 verify" (+ ` · label`) — how the card and the beats name the run; session names use workerName instead. */
626
- kind: string;
627
- slug: string;
628
- usage: StageUsage;
629
- turns: number;
630
- /** the live worker's own session file, once spawned — a family listing leaves it out rather than
631
- * meeting the run twice: once as the run, once as an unlabeled row under "other workers". */
632
- transcript?: string;
633
- }
634
-
635
- const stageRuns = new Map<string, StageRun>();
636
-
637
406
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
638
407
  const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
639
408
 
@@ -687,13 +456,7 @@ function readClaim(root: string, slug: string): SessionClaim | null {
687
456
  }
688
457
 
689
458
  const writeClaim = (root: string, slug: string, key: string) =>
690
- atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now(), start: processStart(process.pid) })}\n`);
691
-
692
- /** "pid 854, claim 3 days old" — the age is what tells a live session from a recycled pid. */
693
- const claimWho = (claim: SessionClaim): string => {
694
- const age = claimAge(claim);
695
- return `pid ${claim.pid}${age ? `, claim ${age}` : ""}`;
696
- };
459
+ atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
697
460
 
698
461
  /** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
699
462
  * never dies, so a claim left behind by a finished session keeps refusing every later session with
@@ -877,26 +640,6 @@ async function worktreeFingerprint(cwd: string): Promise<string | null> {
877
640
  return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
878
641
  }
879
642
 
880
- /** The fingerprint a verify PASS belongs to: the worktree's, hashed TOGETHER WITH the feature's plan/
881
- * dir — the checker read the plan too, so a mid-stage plan edit voids its verdict exactly like a code
882
- * edit. null = git could not answer (same fingerprintless-stamp rule as tier-1 records). */
883
- async function verifyStampFingerprint(root: string, st: FlowState): Promise<string | null> {
884
- const base = await worktreeFingerprint(gateCwd(root, st));
885
- if (!base) return null;
886
- return createHash("sha256").update(`${base}\n${planFingerprint(path.join(root, ".dev-flow", st.slug, "plan"))}`).digest("hex").slice(0, 16);
887
- }
888
-
889
- /** Drop a PASS whose worktree-or-plan fingerprint no longer matches; true if one was dropped. Every
890
- * reader of the stamp (the verify gate, and the check/status views that must not keep advertising a
891
- * dead PASS) runs this before trusting the record. */
892
- async function voidStaleVerifyStamp(root: string, st: FlowState): Promise<boolean> {
893
- if (!st.checks[VERIFY_STAMP]) return false;
894
- const vfp = await verifyStampFingerprint(root, st);
895
- if (!vfp || st.checks[VERIFY_STAMP]!.wt === vfp) return false;
896
- delete st.checks[VERIFY_STAMP];
897
- return true;
898
- }
899
-
900
643
  /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
901
644
  * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
902
645
  async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
@@ -1182,21 +925,8 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1182
925
  // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
1183
926
  // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
1184
927
  // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
1185
- const fpAtGate = await worktreeFingerprint(gateCwd(root, state!));
1186
- const staleAtGate = freshenChecks(state!, fpAtGate, (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1187
- // The stamp is judged by its own wider fingerprint (see verifyStampFingerprint): a change to the
1188
- // plan the verdict was written against demotes it exactly like a worktree change would.
1189
- const stampVoided = await voidStaleVerifyStamp(root, state!);
1190
- if (staleAtGate.length || stampVoided) writeState(root, state!);
1191
- // An independent checker has to have looked at THIS tree before the operator is asked to approve it:
1192
- // the verify worker's PASS is a precondition of the gate, refused before any command runs so a long
1193
- // suite is never spent on a run that cannot pass. The stamp lives in state.checks, so a worktree edit
1194
- // or a moved fingerprint drops it exactly like a tier-1 record — one fresh verify worker per change,
1195
- // precise friction rather than a sticky lock. docs mode is exempt (nothing there to check).
1196
- if (verifyStampMissing(state!)) {
1197
- writeState(root, state!);
1198
- 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 };
1199
- }
928
+ const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
929
+ if (staleAtGate.length) writeState(root, state!);
1200
930
  const pending = pendingChecks(state!, cfg);
1201
931
  const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
1202
932
  if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
@@ -1212,7 +942,6 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1212
942
  // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
1213
943
  did.push("docs mode: project commands skipped (build/dev/health)");
1214
944
  } else {
1215
- did.push(`verify worker PASS over this tree (${state!.checks[VERIFY_STAMP]?.at ?? "recorded"})`);
1216
945
  if (cfg.commands.build) {
1217
946
  const res = await sh(cfg.commands.build, gateCwd(root, state!));
1218
947
  state!.checks.build = { ok: res.ok, at: now() };
@@ -1353,11 +1082,15 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1353
1082
  const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1354
1083
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1355
1084
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1356
- // a PASS whose worktree-or-plan moved is dead here too — no gate may act on a verdict it cannot prove current
1357
- if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1358
1085
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1359
1086
  const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1360
1087
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
1088
+ // the build the tag will trigger, proven before anything ships: a broken artifact build found after the
1089
+ // tag costs follow-up PRs and a re-cut tag
1090
+ if (cfg.release.preflight) {
1091
+ const pf = await sh(cfg.release.preflight, wtCwd);
1092
+ 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 };
1093
+ }
1361
1094
  // a stale session build is the operator's decision, never a block: publishing under an older gate is a
1362
1095
  // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1363
1096
  // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
@@ -1843,12 +1576,14 @@ ${mdDigest(draftRefresh)}`))
1843
1576
 
1844
1577
  async function gateStart(o: GateCtx): Promise<RunResult> {
1845
1578
  const { root, ui, sess, cfg, rest, flag, slugArg } = o;
1846
- 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 };
1579
+ 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 };
1847
1580
  if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
1848
1581
  // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
1849
1582
  if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
1850
1583
  const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
1851
1584
  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 };
1585
+ // --ui adds the rendered-mockup gate to plan: worth it only when screens change, and the operator says so
1586
+ 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 };
1852
1587
  // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
1853
1588
  const curBr = await currentBranch(root);
1854
1589
  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 };
@@ -1974,23 +1709,13 @@ async function gateStatus(o: GateCtx): Promise<RunResult> {
1974
1709
  const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
1975
1710
  const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
1976
1711
  const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
1977
- // status (and --json, which feeds worker briefs) must never advertise a PASS the gates would refuse:
1978
- // reap dead stamps in the copies being rendered — and persist only THIS session's own feature, since
1979
- // a foreign state.json belongs to its own session (a listing must not write another session's file).
1980
- const states = new Map<string, FlowState>();
1981
- for (const s of slugs) {
1982
- const stV = readState(root, s);
1983
- if (!stV) continue;
1984
- if (await voidStaleVerifyStamp(root, stV) && s === sess.slug) writeState(root, stV);
1985
- states.set(s, stV);
1986
- }
1987
1712
  if (flag("json")) {
1988
- const sts = slugs.map((s) => states.get(s)).filter((s): s is FlowState => s !== undefined);
1713
+ const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
1989
1714
  return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
1990
1715
  }
1991
1716
  if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
1992
1717
  const lines = slugs.flatMap((s) => {
1993
- const st = states.get(s);
1718
+ const st = readState(root, s);
1994
1719
  if (!st) return [];
1995
1720
  return [
1996
1721
  `${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}` : ""}`,
@@ -2092,7 +1817,6 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2092
1817
  const loaded = loadProject(df);
2093
1818
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
2094
1819
  findings.push(...(await gitConsistency(root, loaded.cfg)));
2095
- findings.push(...orphanBucketFindings(root));
2096
1820
  const refl = readReflections(root);
2097
1821
  const fold = await foldView(root, refl, isSelfRepo(root));
2098
1822
  if (refl.length) {
@@ -2114,35 +1838,6 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2114
1838
  return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
2115
1839
  }
2116
1840
 
2117
- /** Session buckets stage workers left under finished or vanished worktrees (see `orphanWorktreeBuckets`).
2118
- * Information only: the doctor names them and the command that removes them; deleting transcripts is
2119
- * the operator's call, never the doctor's. Silent when there is no session store to read. */
2120
- function orphanBucketFindings(root: string): string[] {
2121
- const sessionsRoot = testSeams.sessionsRoot.value === undefined ? path.join(getAgentDir(), "sessions") : testSeams.sessionsRoot.value;
2122
- if (!sessionsRoot || !existsSync(sessionsRoot)) return [];
2123
- let buckets: string[];
2124
- try { buckets = readdirSync(sessionsRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { return []; }
2125
- const features = new Map<string, WorktreeBucketFeature>();
2126
- try {
2127
- for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
2128
- if (!d.isDirectory()) continue;
2129
- const st = readState(root, d.name);
2130
- if (!st) continue;
2131
- const wt = st.worktree ? path.resolve(root, st.worktree) : null;
2132
- features.set(d.name, { finished: st.stage === "done" || !!st.aborted, worktreeExists: !!wt && existsSync(wt) });
2133
- }
2134
- } catch { /* no .dev-flow dir: every matching bucket is an orphan */ }
2135
- const orphans = orphanWorktreeBuckets(buckets, root, features);
2136
- if (!orphans.length) return [];
2137
- const rows = orphans.map((o) => {
2138
- const dir = path.join(sessionsRoot, o.bucket);
2139
- let n = 0;
2140
- try { n = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).length; } catch { /* count is cosmetic */ }
2141
- return ` ${o.slug}: ${n} transcript(s) — rm -r ${sq(dir)}`;
2142
- });
2143
- 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")}`];
2144
- }
2145
-
2146
1841
  /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
2147
1842
  * their own names back, so the bodies needed zero edits. */
2148
1843
  interface GateCtx {
@@ -2197,7 +1892,6 @@ async function gateCheck(o: GateCtx): Promise<RunResult> {
2197
1892
  // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
2198
1893
  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)" };
2199
1894
  if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
2200
- if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
2201
1895
  const ran = await runChecks(root, state!, cfg, cfg.checkList);
2202
1896
  return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
2203
1897
  }
@@ -2223,7 +1917,7 @@ async function gateUse(o: GateCtx): Promise<RunResult> {
2223
1917
  const st = readState(root, slugArg);
2224
1918
  if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
2225
1919
  const prior = readClaim(root, slugArg);
2226
- const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (${claimWho(prior!)})` : "";
1920
+ const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
2227
1921
  sess.bind(slugArg);
2228
1922
  sess.rename(slugArg);
2229
1923
  // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
@@ -2244,7 +1938,7 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2244
1938
  // a live claim locks the whole feature, not only its gates: aborting it out from under the session
2245
1939
  // that works it erases the plan that session is still writing (same rule needState applies)
2246
1940
  const claim = readClaim(root, target);
2247
- 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 };
1941
+ 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 };
2248
1942
  if (sess.slug === target) sess.bind(null);
2249
1943
  if (st && !st.worktree) {
2250
1944
  // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
@@ -2257,7 +1951,28 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2257
1951
  }
2258
1952
 
2259
1953
 
2260
- /** True inside a linked worktree (its git dir is not the common dir), false in a main checkout or on error. */
1954
+ /** Sessions spawned by flow_stage in this process: they get no [dev-flow] driver context injected
1955
+ * (their brief is their whole context) — the guards still judge them like any session. */
1956
+ const workerSessions = new Set<string>();
1957
+
1958
+ /** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
1959
+ const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"] };
1960
+
1961
+ /** Seam that spawns a worker as a real pi session — tests replace `.run`. With the driver's session
1962
+ * file and directory known, the worker's header links back to the driver (`parentSession`), so pi's
1963
+ * picker nests it under the driver. */
1964
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<AgentSession> } = {
1965
+ run: async ({ work, model, name, tools, parent, dir }) => {
1966
+ const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
1967
+ await loader.reload();
1968
+ const sessionManager = parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
1969
+ const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
1970
+ try { workerSessions.add(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the default context */ }
1971
+ try { session.setSessionName(name); } catch { /* naming is visibility, not function */ }
1972
+ return session;
1973
+ },
1974
+ };
1975
+
2261
1976
  async function isLinkedWorktree(root: string): Promise<boolean> {
2262
1977
  const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", root);
2263
1978
  if (!r.ok) return false;
@@ -2265,6 +1980,26 @@ async function isLinkedWorktree(root: string): Promise<boolean> {
2265
1980
  return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
2266
1981
  }
2267
1982
 
1983
+ /** Per-cwd cache for flowRoot — the tool_call hook consults it on every call. */
1984
+ const flowRootCache = new Map<string, string>();
1985
+
1986
+ /** The root whose .dev-flow/ is the flow truth for a session cwd. A feature worktree is a linked git
1987
+ * worktree whose tracked .dev-flow/ holds only project.md — state, claims and plans live in the main
1988
+ * checkout. Judging a session by its own cwd found no features and every guard answered "no active
1989
+ * flow". So a linked worktree resolves to its main checkout when that checkout is initiated. */
1990
+ async function flowRoot(cwd: string): Promise<string> {
1991
+ const hit = flowRootCache.get(cwd);
1992
+ if (hit !== undefined) return hit;
1993
+ let root = cwd;
1994
+ if (await isLinkedWorktree(cwd)) {
1995
+ const r = await sh("git rev-parse --path-format=absolute --git-common-dir", cwd);
1996
+ const main = mainCheckoutRoot(cwd, r.ok ? r.out.trim() : null);
1997
+ if (main && initiated(main)) root = main;
1998
+ }
1999
+ flowRootCache.set(cwd, root);
2000
+ return root;
2001
+ }
2002
+
2268
2003
  async function currentBranch(root: string): Promise<string> {
2269
2004
  const r = await sh("git branch --show-current", root);
2270
2005
  return r.ok ? r.out.split("\n")[0] : "";
@@ -2285,7 +2020,7 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
2285
2020
  // sessions overwrite one state file (last write wins) while both believe they own the stage.
2286
2021
  const claim = readClaim(root, slug);
2287
2022
  if (sess.slug !== slug && claimBlocks(claim, sess.key))
2288
- return { state: null, err: { text: `${slug} is claimed by another live session (${claimWho(claim!)}) — flow use ${slug} takes it over explicitly`, isError: true } };
2023
+ return { state: null, err: { text: `${slug} is claimed by another live session (pid ${claim!.pid}) — flow use ${slug} takes it over explicitly`, isError: true } };
2289
2024
  return { state };
2290
2025
  }
2291
2026
 
@@ -2424,7 +2159,7 @@ export default function devFlow(pi: ExtensionAPI) {
2424
2159
  description:
2425
2160
  "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.",
2426
2161
  parameters: Type.Object({
2427
- args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug", "--ui"]' }),
2162
+ args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug"]' }),
2428
2163
  }),
2429
2164
  execute: async (_id, params, _signal, _onUpdate, ctx) => {
2430
2165
  const res = await runFlow(params.args, ctx.cwd, uiFrom(ctx), sessFor(ctx));
@@ -2434,390 +2169,109 @@ export default function devFlow(pi: ExtensionAPI) {
2434
2169
  });
2435
2170
  pi.registerTool(flowTool);
2436
2171
 
2437
- /** The text a worker's finished tool call carried (first text part, else an error string) — the live
2438
- * ✓/✗ line is built from it, so a worker that gets an error back shows it, not just the tool name. */
2439
- function resultText(result: unknown): string {
2440
- const r = result as { content?: unknown; text?: string; errorMessage?: string } | undefined;
2441
- const parts = Array.isArray(r?.content) ? (r!.content as { type?: string; text?: string }[]) : [];
2442
- return parts.find((p) => p?.type === "text")?.text ?? r?.text ?? r?.errorMessage ?? "";
2443
- }
2444
-
2445
- /** The assistant prose of a worker turn — text parts only, thinking and tool calls have their own lines. */
2446
- function assistantText(content: unknown): string {
2447
- if (typeof content === "string") return content;
2448
- if (!Array.isArray(content)) return "";
2449
- return (content as { type?: string; text?: string }[]).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n");
2450
- }
2172
+ /** Driver sessions with a worker running right now — one worker per session at a time. */
2173
+ const runningWorkers = new Set<string>();
2451
2174
 
2452
- /** Last non-empty line: the end of a tool dump is the verdict-bearing part ("251 pass", "exit 1",
2453
- * the error), its head is almost never the news. */
2454
- function lastLineOf(text: string): string {
2455
- return (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
2456
- }
2457
-
2458
- // ---- stage worker (flow_stage): one stage's work, its check and its review in a disposable sub-session --
2459
- // The child stays UNBOUND on purpose: writeGuard attributes worktree writes to the owning
2460
- // feature's stage and bashFlowGuard stops only default-branch git ops, so an implement worker may
2461
- // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and the
2462
- // parent holds the live claim) — and its tool list holds no flow tool at all. The claim, every gate
2463
- // and every checkpoint stay with the driving session; the worker owes one report.
2464
- // Three ops share this one mechanism on purpose: `run` (a stage's work), `verify` (an independent
2465
- // read-only checker whose PASS the verify gate demands) and `reflect` (an independent review of the
2466
- // whole finished flow). Only the brief, the toolset, the budget default and the closing contract
2467
- // differ — the unbound-worker safety story is identical, and a second mechanism would drift.
2468
2175
  const stageWorkerTool = defineTool({
2469
2176
  name: "flow_stage",
2470
2177
  label: "Stage worker",
2471
2178
  description:
2472
- '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.',
2473
- promptSnippet:
2474
- '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',
2179
+ 'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (advisory: no gate depends on it). The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Small work and small fixes are fine to do inline.',
2180
+ promptSnippet: 'flow_stage(op: "implement"|"review", note, label?) — optional fresh-session worker for a big implement slice, or an independent review; gates stay with you',
2475
2181
  parameters: Type.Object({
2476
- 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' })),
2477
- 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.' })),
2478
- note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
2479
- 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." })),
2480
- 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.' })),
2182
+ op: Type.String({ description: '"implement" (a worker edits + commits a slice) or "review" (read-only reviewer, findings + verdict)' }),
2183
+ note: Type.String({ description: "The slice: what to do and anything from this conversation the worker must know (operator answers, decisions). Facts (plan path, commits, checks) are added for you." }),
2184
+ label: Type.Optional(Type.String({ description: "A few words naming this delegation, shown in the worker's session name." })),
2185
+ budgetMin: Type.Optional(Type.Number({ description: "Wall-clock budget in minutes (5-180; default 60 implement, 30 review). Past it the worker is interrupted." })),
2481
2186
  }),
2482
- // The card is the guaranteed worker-visibility surface: it renders inside the driver's own
2483
- // transcript, in TUI and in pi-web alike, because every line also travels as the update's text.
2484
- renderCall: (args, theme) => {
2485
- const op = String(args.op ?? "run");
2486
- const what = op === "run" ? `run ${args.stage ?? "?"}` : op;
2487
- return new Text(theme.fg("toolTitle", `flow_stage ${what}`) + (args.note ? ` ${theme.fg("muted", liveClip(String(args.note), 70))}` : ""), 0, 0);
2488
- },
2489
- renderResult: (result, options, theme) => {
2490
- const d = result.details as { card?: string[]; cardFull?: string[]; verdict?: string | null } | undefined;
2491
- const lines = (options.expanded ? d?.cardFull ?? d?.card : d?.card) ?? [];
2492
- if (!lines.length) return new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n") || "(no output)", 0, 0);
2493
- const box = new Container();
2494
- for (const line of lines) {
2495
- const text = options.expanded ? line : liveClip(line, 120);
2496
- 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));
2497
- }
2498
- if (options.expanded) {
2499
- box.addChild(new Text(theme.fg("dim", "─── report ───"), 0, 0));
2500
- box.addChild(new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n"), 0, 0));
2501
- }
2502
- return box;
2503
- },
2504
2187
  execute: async (_id, params, signal, onUpdate, ctx) => {
2505
2188
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2506
- const opRaw = String(params.op ?? "run").trim().toLowerCase();
2507
- 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)`);
2508
- const op: WorkerOp = opRaw;
2509
- if (op === "status") {
2510
- const run = stageRuns.get(sessionKey(ctx));
2511
- // The family is the question op:"status" gets when nothing is running — "what has this flow
2512
- // spawned, and how did each end?". pi's picker threads the same rows into a tree; this is
2513
- // that fact for a host with no tree, and for the moment between runs. A worker that is live
2514
- // right now is the section above, not one of "the others" — so it is left out here. The whole
2515
- // section is gated on a bound feature: an unbound session has never spawned a stage worker,
2516
- // so there it would be noise paid for with a directory scan.
2517
- const boundState = (() => { try { return initiated(ctx.cwd) ? boundFeature(ctx.cwd, sessionKey(ctx)) : null; } catch { return null; } })();
2518
- const inFlow = !!boundState;
2519
- const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
2520
- // the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
2521
- const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), "stage-sessions", TRANSCRIPTS_FILE), run?.transcript) : null);
2522
- const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
2523
- if (!run) {
2524
- return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
2525
- }
2526
- const elapsed = Date.now() - run.startedAt;
2527
- const dirtyNow = await sh("git status --porcelain", run.work);
2528
- const logNow = await sh("git log --oneline -5", run.work);
2529
- const text = [
2530
- `stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
2531
- ...liveTail(run.lastLines),
2532
- stageUsageLine(run.usage, run.turns),
2533
- `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2534
- `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2535
- ...(inFlow ? ["", ...familySection] : []),
2536
- ].join("\n");
2537
- 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) } };
2538
- }
2189
+ const op = String(params.op ?? "").trim().toLowerCase();
2539
2190
  if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2540
- const st = boundFeature(ctx.cwd, sessionKey(ctx));
2541
- if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2542
- const stageArg = String(params.stage ?? "");
2543
- if (op === "run") {
2544
- 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)`);
2545
- 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`);
2546
- } else {
2547
- const why = workerOpError(op, st);
2548
- if (why) return err(why);
2549
- 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`);
2550
- }
2551
2191
  const key = sessionKey(ctx);
2552
- 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`);
2553
- const budgetMin = clampStageBudgetMin(params.budgetMin ?? WORKER_OP_BUDGET_MIN[op]);
2554
- const budgetMs = budgetMin * 60_000;
2555
- const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
2556
- const hardMs = stageTimingOverride.hardMs ?? budgetMs;
2557
- const glyph = WORKER_OP_GLYPH[op];
2558
- const label = typeof params.label === "string" ? sanitizeWorkerLabel(params.label) : "";
2559
- // the card/beats keep the descriptive kind (the card line has no other stage context); the
2560
- // session NAMES are compact — glyph, ordinal, purpose (see workerName)
2561
- const kind = op === "run" ? `${glyph} ${st.stage}` : `${glyph} ${op}`;
2562
- const kindCard = label ? `${kind} · ${label}` : kind;
2563
- const work = gateCwd(ctx.cwd, st);
2564
- const run: StageRun = {
2565
- startedAt: Date.now(), budgetMin, softFired: false, work, lastLines: [],
2566
- 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,
2567
- };
2568
- stageRuns.set(key, run);
2192
+ const st = boundFeature(ctx.cwd, key);
2193
+ if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2194
+ const why = workerOpError(op, st.stage);
2195
+ if (why) return err(why);
2196
+ const wop = op as WorkerOp;
2197
+ const work = worktreeAbs(ctx.cwd, st);
2198
+ if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk — nothing for a worker to work in`);
2199
+ if (runningWorkers.has(key)) return err("a worker is already running for this session — wait for it to return");
2200
+ runningWorkers.add(key);
2569
2201
  const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2570
- const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2571
- const transcriptLog = path.join(featDir(ctx.cwd, st.slug), "stage-sessions", TRANSCRIPTS_FILE);
2572
- // read once, used twice: the worker's header links to this file and lands in this bucket,
2573
- // and the reflect brief names this session's own transcript to the reviewer
2574
- const lineage = lineageOf(ctx);
2202
+ const budgetMin = clampBudgetMin(params.budgetMin, wop);
2203
+ const label = String(params.label ?? "").replace(/[\r\n]+/g, " ").trim().slice(0, 40);
2204
+ const glyph = wop === "implement" ? "🔨" : "🔍";
2205
+ const name = `${glyph} ${st.slug}${label ? ` · ${label}` : ""}`;
2206
+ const started = Date.now();
2207
+ const git = async (cmd: string) => { const r = await sh(cmd, work); return r.ok ? r.out : ""; };
2208
+ const headBefore = (await git("git rev-parse HEAD")).trim();
2209
+ const brief = buildWorkerBrief({
2210
+ op: wop, slug: st.slug, workDir: work,
2211
+ planFile: path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md"),
2212
+ defaultBranch: cfg.defaultBranch,
2213
+ commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
2214
+ status: await git("git status --short"),
2215
+ checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
2216
+ note: String(params.note ?? ""),
2217
+ });
2218
+ let lineage: { file?: string; dir?: string } = {};
2219
+ try { lineage = { file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
2575
2220
  let child: AgentSession | undefined;
2576
- let crash: string | null = null;
2577
2221
  let timedOut = false;
2578
- /** The card frame for this instant — one place so the streamed text, the TUI card and
2579
- * op:"status" can never disagree about what the worker is doing. */
2580
- const cardView = (state: "running" | "done" | "failed", extra: { verdict?: "pass" | "fail" | null; transcript?: string } = {}) =>
2581
- 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 });
2582
- const emit = (event: string, data: Record<string, unknown>) => {
2583
- try { pi.events.emit(event, { slug: st.slug, op, stage: st.stage, ...data }); } catch { /* the bus is visibility, never function */ }
2584
- };
2222
+ let crash: string | null = null;
2223
+ let nudges = 0;
2224
+ let report = parseWorkerReport("");
2225
+ const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2226
+ const timer = setTimeout(() => { timedOut = true; abortChild(); }, budgetMin * 60_000);
2227
+ signal?.addEventListener("abort", abortChild);
2228
+ let unsub: (() => void) | undefined;
2585
2229
  try {
2586
- writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2587
- const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2588
- // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2589
- // read #2, #3 in the list instead of identical rows. A verify is numbered too: a feature that
2590
- // takes six rounds to PASS reads as a sequence, not as six free-text labels. A reflect is one per flow.
2591
- const seq = op !== "reflect" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2592
- const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2593
- const git = await sh("git status --porcelain -b", work);
2594
- const note = typeof params.note === "string" ? params.note : undefined;
2595
- const planFile = path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md");
2596
- let brief: string;
2597
- if (op === "verify") {
2598
- // the reviewer reads the full diff itself; the stat is only the shape of what it is in for
2599
- const stat = await sh(`git diff --shortstat ${sq(`origin/${cfg.defaultBranch}`)}...HEAD 2>/dev/null || git diff --shortstat ${sq(cfg.defaultBranch)}...HEAD`, work);
2600
- const tier1 = [...cfg.checkList];
2601
- if (cfg.commands.test && !tier1.some((c) => c.name === "test")) tier1.push({ name: "test", cmd: cfg.commands.test });
2602
- brief = buildVerifyBrief({
2603
- slug: st.slug, workDir: work, planFile, statusJson: statusJsonText,
2604
- gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2605
- diffStat: stat.ok ? stat.out.trim() : "(no diff stat)",
2606
- defaultBranch: cfg.defaultBranch, checks: tier1, note,
2607
- });
2608
- } else if (op === "reflect") {
2609
- const transcripts = existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")) : [];
2610
- brief = buildReflectBrief({
2611
- slug: st.slug, planFile, statusJson: statusJsonText, driverSession: lineage.file, transcripts,
2612
- openReflections: readReflections(ctx.cwd).map((r) => r.line), note,
2613
- });
2614
- } else {
2615
- const refRel = stageReference(st.stage);
2616
- let refText = "";
2617
- if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2618
- 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 });
2619
- }
2620
- // the tree identity a verify verdict belongs to, before anything runs: the same comparison
2621
- // the tier-1 fingerprint makes, done here because a reviewer must not be the one who edited.
2622
- // HEAD is captured too: a reviewer that commits or moves a ref leaves `git status` clean while
2623
- // reading a different tree, so a porcelain-only diff would stamp a PASS for a HEAD it never saw.
2624
- const statusBefore = await sh("git status --porcelain", work);
2625
- const headBefore = await sh("git rev-parse HEAD", work);
2626
- const refBefore = await sh("git symbolic-ref -q HEAD || true", work);
2627
- // the plan is an input the reviewer reads from OUTSIDE the worktree — it belongs in the
2628
- // before/after proof too, or a reviewer could rewrite the ground it is judging mid-run
2629
- const planDir = path.join(ctx.cwd, ".dev-flow", st.slug, "plan");
2630
- const planBefore = planFingerprint(planDir);
2631
- // the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
2632
- // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2633
- // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2634
- 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 });
2635
- child = worker.session;
2636
- try { run.transcript = child.sessionManager.getSessionFile() ?? undefined; } catch { /* the family listing just won't know which row is this run */ }
2637
- emit("dev-flow:worker-started", { budgetMin, startedAt: new Date().toISOString() });
2638
- let lastBeat = 0;
2639
- /** One live line: ledger, durable log, and the streamed card — same text on every host. */
2640
- const pushLine = (line: string) => {
2641
- if (!line) return;
2642
- run.lastLines.push(line);
2643
- if (run.lastLines.length > 50) run.lastLines.shift();
2644
- try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2645
- const card = cardView("running");
2646
- 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) } });
2647
- };
2648
- const unsub = child.subscribe((ev: unknown) => {
2649
- 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> } } };
2650
- const elapsed = () => Date.now() - run.startedAt;
2230
+ child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir });
2231
+ unsub = child.subscribe((ev: unknown) => {
2232
+ const e = ev as { type?: string; toolName?: string };
2651
2233
  if (e.type === "tool_execution_start") {
2652
- pushLine(stageLiveLine(elapsed(), e.toolName ?? "?", summarizeToolArgs(e.args)));
2653
- const now = Date.now();
2654
- if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
2655
- }
2656
- if (e.type === "tool_execution_end") {
2657
- // the last line of the result is the verdict-bearing one ("251 pass", "exit 1",
2658
- // the error) — the head of a tool dump is almost never the news
2659
- pushLine(stageLiveResultLine(elapsed(), e.toolName ?? "?", !e.isError, lastLineOf(resultText(e.result))));
2660
- }
2661
- if (e.type === "message_end" && e.message?.role === "assistant") {
2662
- run.turns++;
2663
- const u = e.message.usage;
2664
- if (u) {
2665
- for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) run.usage[f] += Number(u[f] ?? 0);
2666
- if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) run.usage.cost[f] += Number(u.cost[f] ?? 0);
2667
- }
2668
- pushLine(stageLiveAssistantLine(elapsed(), assistantText(e.message.content)));
2234
+ const min = Math.floor((Date.now() - started) / 60_000);
2235
+ onUpdate?.({ content: [{ type: "text", text: `⏳ ${name} — ${min}/${budgetMin} min · ${e.toolName ?? "?"}` }], details: { running: true } });
2669
2236
  }
2670
2237
  });
2671
- const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2672
- // grace before the cliff: at 75% the worker is told to commit and report — an honest handoff
2673
- // beats an abort; the hard timer stays the backstop for a worker that ignores the steer
2674
- const softTimer = setTimeout(() => {
2675
- run.softFired = true;
2676
- try { void Promise.resolve(child?.steer(stageInterruptSteer(budgetMin))).catch(() => {}); } catch { /* hard cut follows */ }
2677
- }, softMs);
2678
- const hardTimer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2679
- signal?.addEventListener("abort", abortChild);
2680
- try {
2681
- await child.prompt(brief);
2682
- } catch (e) {
2683
- crash = e instanceof Error ? e.message : String(e);
2684
- } finally {
2685
- clearTimeout(softTimer);
2686
- clearTimeout(hardTimer);
2687
- unsub();
2688
- }
2689
- const clean = !crash && !timedOut;
2690
- const transcript = child.sessionManager.getSessionFile() ?? "";
2691
- // the durable worker index: until now a transcript path lived only in this call's result,
2692
- // i.e. only as long as the driver kept it in context — the reflect worker needs the list
2693
- if (transcript) {
2694
- try {
2695
- mkdirSync(path.dirname(transcriptLog), { recursive: true });
2696
- appendFileSync(transcriptLog, `${workerTranscriptLine(now(), op, transcript)}\n`);
2697
- } catch { /* an index that failed to append is never a reason to lose the run */ }
2698
- }
2699
- const report = op === "run" ? parseStageReport(child.getLastAssistantText() ?? "") : null;
2700
- const verify = op === "verify" ? parseVerifyReport(child.getLastAssistantText() ?? "") : null;
2701
- const findings = op === "reflect" ? parseReflectFindings(child.getLastAssistantText() ?? "") : null;
2702
- // A check-only worker must leave the tree exactly as it found it: the verdict is a claim
2703
- // about THIS tree, so a reviewer that touched anything voids its own report. Computed before
2704
- // the rename and the stamp so both readers agree on one verdict of "did the ground move".
2705
- // (The gate's own uncommitted-path policy stays unchanged — a tree already dirty is not the
2706
- // worker's fault; only movement counts.)
2707
- const statusAfter = await sh("git status --porcelain", work);
2708
- const headAfter = await sh("git rev-parse HEAD", work);
2709
- const refAfter = await sh("git symbolic-ref -q HEAD || true", work);
2710
- // four legs, because each alone has a clean-tree bypass: porcelain misses ref moves,
2711
- // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2712
- // and all three miss the plan the verdict was written against living outside the worktree
2713
- 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);
2714
- // the outcome goes INTO the final name — a picker row like `✓ 🔍 #3 · PASS · stamp attack` or
2715
- // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2716
- let outcome: string | null = null;
2717
- if (clean) {
2718
- if (op === "run" && headBefore.ok) {
2719
- const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
2720
- const n = c.ok ? c.out.trim() : "0";
2721
- if (n !== "0") outcome = `${n} commit${n === "1" ? "" : "s"}`;
2722
- }
2723
- if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
2724
- if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
2725
- } else {
2726
- outcome = timedOut ? "hard-cut" : "crashed";
2727
- }
2728
- worker.rename(workerName(clean ? "✓" : "✗", glyph, seq, label, outcome));
2729
- // never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
2730
- // via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
2731
- let snapshot: string | null = null;
2732
- const dirty = await sh("git status --porcelain", work);
2733
- if (dirty.ok && dirty.out.trim()) {
2734
- const snapDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
2735
- mkdirSync(snapDir, { recursive: true });
2736
- const stamp = Date.now();
2737
- const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
2738
- const idx = path.join(snapDir, `.snap-index-${stamp}`);
2739
- 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);
2740
- if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
2741
- }
2742
- // An implement worker dirtied tier-1 records through the same hooks any edit dirties them, so
2743
- // the check reruns here: it runs on the driver's binding and its verdict rides along in the
2744
- // digest. A check-only op touched nothing (proved below), so its records still stand — and
2745
- // re-running a whole suite here would spend it twice and hide the gate's own re-run.
2746
- const check = op === "run" ? await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx)) : null;
2747
- // the PASS is stamped AFTER the rerun so it belongs to the settled tree, and only over a tree
2748
- // the reviewer actually left untouched — this stamp is what flow verify demands at the gate
2749
- let stamped = false;
2750
- let cleared = false;
2751
- if (verify?.verdict === "pass" && clean && !moved) {
2752
- const fresh = readState(ctx.cwd, st.slug);
2753
- if (fresh) {
2754
- recordVerifyPass(fresh, now(), await verifyStampFingerprint(ctx.cwd, fresh));
2755
- writeState(ctx.cwd, fresh);
2756
- stamped = true;
2757
- }
2758
- } else if (verify?.verdict === "fail" && !moved) {
2759
- // a FAIL over an unmoved tree contradicts any earlier PASS — the gate may not ask
2760
- // Verified? against a tree its newest checker rejected
2761
- const fresh = readState(ctx.cwd, st.slug);
2762
- if (fresh?.checks[VERIFY_STAMP]) {
2763
- delete fresh.checks[VERIFY_STAMP];
2764
- writeState(ctx.cwd, fresh);
2765
- cleared = true;
2766
- }
2767
- }
2768
- const parts: string[] = [];
2769
- if (report) parts.push(renderStageReport(report));
2770
- if (verify) {
2771
- parts.push(renderVerifyReport(verify));
2772
- 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).`);
2773
- 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.");
2774
- 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}` : ""}`);
2775
- else if (!clean) parts.push("no verdict recorded from a crashed or interrupted run — rerun the verify worker.");
2776
- 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)" : ""}.`);
2238
+ await child.prompt(brief);
2239
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2240
+ // a turn that ends in prose ("now let me write D4…") ends the session: tell it to keep going
2241
+ while (!report.found && !timedOut && !signal?.aborted && nudges < WORKER_NUDGES) {
2242
+ nudges++;
2243
+ await child.prompt(WORKER_NUDGE);
2244
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2777
2245
  }
2778
- if (findings) {
2779
- 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, "```");
2780
- else {
2781
- parts.push(
2782
- `playbook findings (${findings.playbook.length}):`, ...(findings.playbook.length ? findings.playbook.map((x) => `[playbook] ${x}`) : ["- none"]),
2783
- `plugin findings (${findings.plugin.length}):`, ...(findings.plugin.length ? findings.plugin.map((x) => `[plugin] ${x}`) : ["- none"]),
2784
- ...(findings.other.length ? ["other:", ...findings.other.map((x) => `[neither] ${x}`)] : []),
2785
- "put the findings to the operator (Fold? Fix? Drop?) — queue what they fold with flow reflect --playbook|--plugin; the worker queued nothing.",
2786
- );
2787
- }
2788
- }
2789
- 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"}`);
2790
- if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
2791
- if (crash) parts.push(`worker run ended with an error: ${crash}`);
2792
- if (snapshot && !verify) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2793
- 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.");
2794
- 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)` : ""}`);
2795
- const failed = !!crash || timedOut || moved;
2796
- // the family belongs on the settled card and the result only: a live frame redraws on every
2797
- // worker tool call, and reading a session bucket is IO. This run is excluded — the card names
2798
- // its transcript already, and repeating it as a bare row reads like a different worker.
2799
- const famFromPicker = await workerFamilyLines(ctx, transcript || undefined);
2800
- const fam = famFromPicker ?? ledgerFamilyLines(transcriptLog, transcript || undefined);
2801
- emit(failed ? "dev-flow:worker-failed" : "dev-flow:worker-completed", {
2802
- elapsedMs: Date.now() - run.startedAt, usage: run.usage, turns: run.turns, budgetMin, softFired: run.softFired, timedOut, crash,
2803
- verdict: verify?.verdict ?? null, reportMissing: report?.missing ?? findings?.missing ?? false, transcript, snapshot,
2804
- });
2805
- const card = cardView(failed ? "failed" : "done", { verdict: verify?.verdict ?? null, transcript });
2806
- return {
2807
- content: [{ type: "text" as const, text: parts.join("\n\n") }],
2808
- details: {
2809
- 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),
2810
- done: report?.done, files: report?.files, notes: report?.notes, blockers: report?.blockers, reportMissing: report?.missing ?? findings?.missing ?? false,
2811
- verdict: verify?.verdict ?? null, stamped, clearedStamp: cleared, verdictVoided: moved, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot,
2812
- },
2813
- usage: run.usage,
2814
- isError: failed,
2815
- };
2246
+ } catch (e) {
2247
+ crash = e instanceof Error ? e.message : String(e);
2816
2248
  } finally {
2817
- stageRuns.delete(key);
2818
- if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", undefined);
2819
- try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
2249
+ clearTimeout(timer);
2250
+ signal?.removeEventListener("abort", abortChild);
2251
+ unsub?.();
2252
+ runningWorkers.delete(key);
2820
2253
  }
2254
+ const transcript = (() => { try { return child?.sessionManager.getSessionFile() ?? ""; } catch { return ""; } })();
2255
+ const headAfter = (await git("git rev-parse HEAD")).trim();
2256
+ const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
2257
+ const dirty = (await git("git status --short")).trim();
2258
+ const outcome = crash ? `crashed: ${crash}` : timedOut ? `interrupted at the ${budgetMin}-min budget` : report.found ? "reported" : `ended without REPORT after ${nudges} nudge(s)`;
2259
+ try { child?.setSessionName(`${report.found && !crash && !timedOut ? "✓" : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2260
+ const parts = [
2261
+ `${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`,
2262
+ report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : `no REPORT — last words:\n${report.body}`,
2263
+ `new commits:\n${newCommits.trim() || "(none)"}`,
2264
+ `uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
2265
+ ];
2266
+ if (wop === "implement") {
2267
+ const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
2268
+ parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
2269
+ } else if (newCommits.trim() || dirty) {
2270
+ parts.push("note: the reviewer changed the tree — treat its verdict with suspicion and inspect the change");
2271
+ }
2272
+ parts.push(`transcript: ${transcript || "(unknown)"}`);
2273
+ 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.");
2274
+ return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
2821
2275
  },
2822
2276
  });
2823
2277
  pi.registerTool(stageWorkerTool);
@@ -2914,7 +2368,9 @@ export default function devFlow(pi: ExtensionAPI) {
2914
2368
  // an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
2915
2369
  // the guards, the no-playbook bash-timeout default included
2916
2370
  if (noDf) return undefined;
2917
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2371
+ // flow truth lives in the main checkout even when the session runs inside a feature worktree
2372
+ const guardRoot = await flowRoot(ctx.cwd);
2373
+ const cfg = loadProject(dfDir(guardRoot)).cfg;
2918
2374
  const mustStateTimeout = shellCmd !== "" && explicitTimeout === undefined && cfg.bashTimeout === "require";
2919
2375
  // for bash this verdict waits behind the operator's own deny/confirm rules further down;
2920
2376
  // powershell meets no project rules at all, so it is answered here
@@ -2923,8 +2379,8 @@ export default function devFlow(pi: ExtensionAPI) {
2923
2379
 
2924
2380
  if (isToolCallEventType("edit", event) || isToolCallEventType("write", event)) {
2925
2381
  const abs = path.resolve(ctx.cwd, String(event.input.path ?? ""));
2926
- const feats = featureRefs(ctx.cwd);
2927
- const bound = boundFeature(ctx.cwd, key);
2382
+ const feats = featureRefs(guardRoot);
2383
+ const bound = boundFeature(guardRoot, key);
2928
2384
  // operator safety rules from project.md run first — as in the bash guard, the operator's deny outranks flow discipline
2929
2385
  const pv = guardPath(abs, ctx.cwd, cfg.guard);
2930
2386
  if (pv.block) return { block: true, reason: pv.block };
@@ -2932,14 +2388,14 @@ export default function devFlow(pi: ExtensionAPI) {
2932
2388
  const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
2933
2389
  if (why) return { block: true, reason: why };
2934
2390
  }
2935
- const reason = writeGuard({ abs, dfDir: dfDir(ctx.cwd), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd });
2391
+ const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd });
2936
2392
  if (reason) return { block: true, reason };
2937
2393
  // Editing a worktree invalidates that feature's tier-1 checks and tier-2 confirmation until they rerun.
2938
2394
  const owner = feats.find((f) => f.worktreeAbs && abs.startsWith(f.worktreeAbs + path.sep));
2939
2395
  if (owner && (owner.state.stage === "implement" || owner.state.stage === "pre-release") && (Object.keys(owner.state.checks).length || owner.state.confirmations?.implement)) {
2940
2396
  owner.state.checks = {};
2941
2397
  delete owner.state.confirmations?.implement;
2942
- writeState(ctx.cwd, owner.state);
2398
+ writeState(guardRoot, owner.state);
2943
2399
  }
2944
2400
  return undefined;
2945
2401
  }
@@ -2975,9 +2431,14 @@ export default function devFlow(pi: ExtensionAPI) {
2975
2431
  const why = await askOperator(ctx, command, mv.confirm);
2976
2432
  if (why) return { block: true, reason: why };
2977
2433
  }
2434
+ // shipping on the forge (PR merge, release page) is release-stage work for a bound feature
2435
+ if (/\b(?:gh|glab)\b/.test(command)) {
2436
+ const ro = releaseOrderInvocation(command, boundFeature(guardRoot, key)?.stage ?? null);
2437
+ if (ro) return { block: true, reason: ro };
2438
+ }
2978
2439
  const inv = gitInvocation(command);
2979
2440
  if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
2980
- const bound = boundFeature(ctx.cwd, key);
2441
+ const bound = boundFeature(guardRoot, key);
2981
2442
  // judge EACH git segment by the branch of the directory it runs in — a chain may cd across
2982
2443
  // directories; one last-cd-wins verdict misattributed mixed-dir chains and blocked legit worktree commits
2983
2444
  const branchCache = new Map<string, string>();
@@ -2991,7 +2452,7 @@ export default function devFlow(pi: ExtensionAPI) {
2991
2452
  }
2992
2453
  return branchCache.get(at)!;
2993
2454
  };
2994
- const worktrees = featureRefs(ctx.cwd).map((f) => f.worktreeAbs).filter((w): w is string => !!w);
2455
+ const worktrees = featureRefs(guardRoot).map((f) => f.worktreeAbs).filter((w): w is string => !!w);
2995
2456
  for (const g of inv.gitSegs) {
2996
2457
  const gitDir = g.dir ? path.resolve(ctx.cwd, g.dir) : ctx.cwd;
2997
2458
  const seg = gitInvocation(g.seg); // parsed once per segment — this runs on every bash call of every session
@@ -3017,6 +2478,11 @@ export default function devFlow(pi: ExtensionAPI) {
3017
2478
  }
3018
2479
  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` });
3019
2480
  if (reason) return { block: true, reason };
2481
+ // A feature worktree stays on its feature branch: a side branch cut inside it repurposes the
2482
+ // worktree (and leaves it off its branch for the next gate); out-of-flow fixes get their own flow.
2483
+ const created = branchCreateTarget(g.seg);
2484
+ const homeWt = worktrees.find((w) => gitDir === w || gitDir.startsWith(w + path.sep));
2485
+ if (created && homeWt) return { block: true, reason: `a feature worktree stays on its own branch — not creating ${created} in ${homeWt}; an unrelated fix is its own flow (flow start <slug> --patch --confirmed)` };
3020
2486
  // Branch discipline: feature branches live in their worktree — never checked out or created (-b) in the main checkout
3021
2487
  const target = checkoutTarget(g.seg);
3022
2488
  if (target && target.startsWith(featureBranchPrefix(cfg))) {
@@ -3042,10 +2508,7 @@ export default function devFlow(pi: ExtensionAPI) {
3042
2508
  // client attaches, and this is the earliest point the client is certainly listening
3043
2509
  refreshStatus(ctx);
3044
2510
  if (!initiated(ctx.cwd)) return undefined;
3045
- // A stage worker's whole instruction is its brief. The driver's context is wrong there twice over:
3046
- // the unbound posture tells it to pre-plan and `flow start`, and the branch check reads its
3047
- // worktree as a main checkout on the wrong branch. Guards still run — they hang off tool_call.
3048
- if (isWorkerSession(ctx.sessionManager?.getSessionId?.())) return undefined;
2511
+ try { if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined; } catch { /* not a worker */ }
3049
2512
  const key = sessionKey(ctx);
3050
2513
  // The playbook core rides along on the message this run writes anyway — once per session.
3051
2514
  const core = corePreamble(key);
@@ -3053,12 +2516,10 @@ export default function devFlow(pi: ExtensionAPI) {
3053
2516
  const state = boundFeature(ctx.cwd, key);
3054
2517
  if (!state || state.stage === "done") {
3055
2518
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
3056
- 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>.";
2519
+ let content = "[dev-flow] no flow bound. Every request goes through flow. New work: flow start <slug>; unfinished feature: flow use <slug>.";
3057
2520
  const cb = claimBlocker(ctx.cwd, key);
3058
- 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.`;
3059
- // only the main checkout has a "main checkout branch": a session opened in a linked worktree is
3060
- // on its feature branch by construction, and calling that a drift misleads it
3061
- const curBr = (await isLinkedWorktree(ctx.cwd)) ? "" : await currentBranch(ctx.cwd);
2521
+ if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (pid ${cb.claim.pid}) — flow use ${cb.state.slug} takes it over explicitly.`;
2522
+ const curBr = await currentBranch(ctx.cwd);
3062
2523
  if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
3063
2524
  const refl0 = readReflections(ctx.cwd);
3064
2525
  if (refl0.length) content += ` Also: ${refl0.length} reflection(s) open — run flow doctor.`;