pi-dev-flow 0.72.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,28 +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
- DELEGATIONS_FILE,
52
- STAGE_SESSIONS_DIR,
53
- delegationErrors,
54
- delegationLine,
55
- parseDelegationLedger,
56
- mainCheckoutRoot,
57
- type DelegationWindow,
58
43
  checkoutTarget,
59
44
  claimBlocks,
60
- clampStageBudgetMin,
61
45
  classifyMergeHistory,
62
46
  cmpVersions,
63
47
  cleanupAssess,
@@ -73,8 +57,6 @@ import {
73
57
  gateHelpJson,
74
58
  gitInvocation,
75
59
  githubSlug,
76
- DELEGABLE_STAGES,
77
- isDelegableStage,
78
60
  guardBash,
79
61
  guardPath,
80
62
  healthProbe,
@@ -121,52 +103,7 @@ import {
121
103
  roadmapTidy,
122
104
  shouldSelfCompact,
123
105
  shouldTakeOverCompaction,
124
- TRANSCRIPTS_FILE,
125
- stageCardLines,
126
- stageElapsedLabel,
127
106
  stageGuidance,
128
- stageInterruptSteer,
129
- stageLiveAssistantLine,
130
- stageLiveLine,
131
- stageLiveResultLine,
132
- stageUsageLine,
133
- summarizeToolArgs,
134
- VERIFY_STAMP,
135
- VERIFY_STAMP_REFUSAL,
136
- WORKER_OP_BUDGET_MIN,
137
- WORKER_OP_GLYPH,
138
- WORKER_OP_TOOLS,
139
- type StageUsage,
140
- type WorkerOp,
141
- buildReflectBrief,
142
- buildVerifyBrief,
143
- isWorkerOp,
144
- liveClip,
145
- liveTail,
146
- parseReflectFindings,
147
- parseVerifyReport,
148
- parseWorkerTranscripts,
149
- planFingerprint,
150
- recordVerifyPass,
151
- renderVerifyReport,
152
- verifyStampMissing,
153
- sessionPathKey,
154
- sessionHeaderParent,
155
- parseSessionSummary,
156
- markWorkerSession,
157
- isWorkerSession,
158
- orphanWorktreeBuckets,
159
- claimAge,
160
- processStart,
161
- type WorktreeBucketFeature,
162
- workerFamily,
163
- workerFamilyCount,
164
- WORKER_FAMILY_ITEMS,
165
- workerOpError,
166
- workerTranscriptLine,
167
- type WorkerSessionRow,
168
- workerName,
169
- sanitizeWorkerLabel,
170
107
  stateTamper,
171
108
  statusFor,
172
109
  statusJson,
@@ -177,6 +114,16 @@ import {
177
114
  verifyGate,
178
115
  versionTagGate,
179
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,
180
127
  type BranchState,
181
128
  type Config,
182
129
  type FeatureRef,
@@ -184,7 +131,6 @@ import {
184
131
  type StageCheck,
185
132
  type PushRef,
186
133
  type SessionClaim,
187
- type DelegableStage,
188
134
  } from "../src/core.ts";
189
135
  import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
190
136
  import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
@@ -257,13 +203,7 @@ function copyWarning(): string | null {
257
203
  }
258
204
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
259
205
  * entries and asserts the warnings the real duplicate would print. */
260
- export const testSeams = {
261
- copies: COPIES,
262
- skillCore: { value: undefined as string | null | undefined },
263
- /** Where `flow doctor` looks for pi's session buckets; tests point it at a scratch dir so the suite
264
- * never reads the operator's real session store. `undefined` = `<agent dir>/sessions`. */
265
- sessionsRoot: { value: undefined as string | null | undefined },
266
- };
206
+ export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined } };
267
207
 
268
208
  interface Ui {
269
209
  hasUI: boolean;
@@ -394,7 +334,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
394
334
  }
395
335
 
396
336
  const GATE_HELP =
397
- "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|list|tidy|move <n> --plugin|--playbook] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui] [--force] [--patch|--docs --confirmed] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — start preflights the playbook before creating anything: it prints playbook gaps and warns when the session runs an older dev-flow build than the disk ships (in the dev-flow repo, an older build than this checkout's own manifest), and it refuses until a merge policy is set (ask the operator squash / merge / rebase / any in chat, then re-run with --merge=<style> --confirmed — the answer is written into project.md and enforced from then on: gh/glab merges that contradict it are blocked, and release-done proves what actually landed); version prints the build the disk says to run (this checkout's own manifest in the dev-flow repo, the installed package's elsewhere) and names any other dev-flow copies registered in the same process (--check-upstream also asks the registry for the published one) — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there; --plugin / --playbook / --both state the section instead of leaving it to the wording, and the echo prints why the note landed where it did); reflect list numbers the open items with their section; reflect move <n> --plugin|--playbook re-files one of them; reflect tidy drops the closed (`- [x]`) items from reflections.md — every surface that queues or reviews reflections nudges when the checked-off pile grows; bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned); when the session runs an older dev-flow build than the checkout, release names both builds, lists what the running code can no longer prove, and asks the operator update (/reload) or proceed with the old release — an operator decision recorded in state and repeated by release-done, never a block";
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";
398
338
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
399
339
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
400
340
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -415,8 +355,7 @@ function writeState(root: string, state: FlowState): void {
415
355
  * truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
416
356
  * and every recorded check, with the folder gitignored so nothing else could restore it. */
417
357
  function atomicWrite(file: string, text: string): void {
418
- // per-process temp name: two sessions writing the same file must not rename each other's half-write
419
- const tmp = `${file}.${process.pid}.tmp`;
358
+ const tmp = `${file}.tmp`;
420
359
  writeFileSync(tmp, text);
421
360
  renameSync(tmp, file);
422
361
  }
@@ -464,183 +403,6 @@ function skillCore(): string | null {
464
403
  /** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
465
404
  export const compactionTakeover: { run: typeof compact } = { run: compact };
466
405
 
467
- /** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
468
- * `.run` with a stub, so the worker contract stays testable without spending a model and tests
469
- * never touch the real session directory. The real spawn stamps lineage: the worker's header
470
- * carries `parentSession` → the driver's own session file, and its transcript goes into the
471
- * driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
472
- * scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
473
- * as /handoff can do the same"). The live ⏳ name is written straight onto the session before its
474
- * first prompt: pi emits `session_start` only from `bindExtensions()`, which an SDK-created worker
475
- * never runs, so a name set from a `session_start` handler never lands — every worker used to run
476
- * under whatever an auto-namer derived from its brief ("you-are-a-dev"). Named before the prompt,
477
- * an auto-namer sees a name that is not its own and leaves it alone. The same channel carries the
478
- * ⏳ → ✓/✗ rename. The worker is also registered as a worker, so the dev-flow copy its loader runs
479
- * keeps its guards but injects none of the driver's context (see `isWorkerSession`). */
480
-
481
- export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
482
-
483
- /** The worker's session manager, built exactly as the real seam builds it — split out so a test can
484
- * drive the production composition (header link + driver's bucket) without spawning a model.
485
- * Both or neither: `dir` is the driver's own bucket read off the live manager, so a custom
486
- * PI_CODING_AGENT_DIR can never strand a worker in a different agent dir from its driver, and pi's
487
- * private `--<encoded cwd>--` directory encoding is never duplicated here. */
488
- export function workerSessionManager(work: string, parent?: string, dir?: string): SessionManager | undefined {
489
- return parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
490
- }
491
-
492
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
493
- run: async ({ work, model, name, tools, parent, dir }) => {
494
- const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
495
- await loader.reload();
496
- const sessionManager = workerSessionManager(work, parent, dir);
497
- const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
498
- // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
499
- // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
500
- // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
501
- try { markWorkerSession(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the driver context */ }
502
- const rename = (n: string) => { try { session.setSessionName(n); } catch { /* naming is visibility, not function */ } };
503
- rename(name);
504
- return { session, rename };
505
- },
506
- };
507
-
508
- /** Seam that reads the driver's session bucket the way the picker does — a stub in the smoke suite,
509
- * because a test must not scan the operator's real session directory. `listAll(dir)`, not
510
- * `list(cwd, dir)`: pi's `list` drops rows whose header cwd is not `cwd` whenever it is handed a
511
- * directory that is not that cwd's default — which is precisely a stage worker (header cwd = the
512
- * worktree, file in the driver's bucket), and precisely the layout a configured `sessionDir`
513
- * creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
514
- * the family list and the tree agree there; under a configured session dir the text view stays
515
- * complete even where that scope hides the worker, which is the cheaper direction to err in. */
516
- export const sessionRowsScan: { run: (o: { cwd: string; dir?: string; parent?: string }) => Promise<WorkerSessionRow[]> } = {
517
- run: async ({ dir, parent }) => {
518
- // no bucket or no driver file to match: the old full listing (a host that never reaches here in practice)
519
- if (!dir || !parent) return (await SessionManager.listAll(dir)).map((s) => ({ path: s.path, parent: s.parentSessionPath, name: s.name, messageCount: s.messageCount, modified: s.modified }));
520
- return scanFamilyRows(dir, parent);
521
- },
522
- };
523
-
524
- /** Header bytes read per transcript in the family scan's cheap pass — the same budget pi gives its own
525
- * header reads. A pi header line is a few hundred bytes. */
526
- const SESSION_HEADER_BYTES = 4096;
527
-
528
- /** The family read in two passes, so its cost follows the family, not the bucket: the first line of
529
- * every transcript (≤ 4 KB each) names its parent; only the files whose parent is `parent` are read
530
- * in full. `listAll(dir)` parsed every transcript in the bucket — ~15 ms per MB, and a driver bucket
531
- * only grows (the dev-flow checkout's was 55 MB, ~0.8 s for every idle status and settled card).
532
- * `fullReads` counts the second pass for the smoke suite. */
533
- export async function scanFamilyRows(dir: string, parent: string, fullReads?: { n: number }): Promise<WorkerSessionRow[]> {
534
- let names: string[];
535
- try { names = (await readdirAsync(dir)).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
536
- const want = sessionPathKey(parent);
537
- const rows: WorkerSessionRow[] = [];
538
- await Promise.all(names.map(async (n) => {
539
- const file = path.join(dir, n);
540
- let head = "";
541
- try {
542
- const fh = await openFile(file, "r");
543
- try {
544
- const buf = Buffer.alloc(SESSION_HEADER_BYTES);
545
- const { bytesRead } = await fh.read(buf, 0, SESSION_HEADER_BYTES, 0);
546
- head = buf.subarray(0, bytesRead).toString("utf8");
547
- } finally { await fh.close(); }
548
- } catch { return; }
549
- const p = sessionHeaderParent(head);
550
- if (!p || sessionPathKey(p) !== want) return;
551
- try {
552
- if (fullReads) fullReads.n++;
553
- const [text, st] = await Promise.all([readFileAsync(file, "utf8"), statAsync(file)]);
554
- const row = parseSessionSummary(text, file, st.mtimeMs);
555
- if (row) rows.push(row);
556
- } catch { /* a transcript deleted mid-scan is simply not in the family */ }
557
- }));
558
- return rows;
559
- }
560
-
561
- /** Where this session's own transcripts live, when it has any: the file the worker links to, and the
562
- * bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
563
- * which is a fact to print, never an error to raise. */
564
- function lineageOf(ctx: ExtensionContext): { file: string | null; dir: string | null } {
565
- try {
566
- return { file: ctx.sessionManager.getSessionFile() ?? null, dir: ctx.sessionManager.getSessionDir() ?? null };
567
- } catch { /* an in-memory or otherwise unbacked session says so here */ return { file: null, dir: null }; }
568
- }
569
-
570
- /** With no file-backed lineage to read — an unbacked host, or a driver pi never wrote a file for —
571
- * the ledger is what the flow knows: every worker it recorded, newest first. Coarser than the
572
- * picker's data (no message count, no rename), so the status heading names the source. */
573
- function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
574
- try {
575
- const drop = exclude ? sessionPathKey(exclude) : null;
576
- const mine = parseWorkerTranscripts(readFileSync(logPath, "utf8")).filter((r) => !drop || sessionPathKey(r.path) !== drop);
577
- const shown = mine.slice(-WORKER_FAMILY_ITEMS).reverse().map((r) => `${r.op} · ${r.at} · ${r.path}`);
578
- return mine.length > shown.length ? [...shown, familyFoldLine(mine.length - shown.length)] : shown;
579
- } catch { return []; }
580
- }
581
-
582
- /** Bucket reads are the one IO-bound thing the family view does: one header read per transcript in
583
- * the driver's bucket, plus a full read of each worker (`scanFamilyRows`). A host renders a running
584
- * worker by calling status repeatedly, so that path is allowed a slightly stale read; the places the
585
- * operator draws a conclusion from — idle status, the settled card — always re-read. */
586
- const BUCKET_FRESH_MS = 2000;
587
- const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
588
-
589
- async function bucketRows(ctx: ExtensionContext, dir: string | null, parent: string, staleMs = 0) {
590
- const key = `${dir ?? "(default bucket)"}\0${parent}`;
591
- const hit = bucketCache.get(key);
592
- // staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
593
- // and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
594
- // condition also holds inside the caller's own millisecond, and a fast host got the previous read back
595
- // as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
596
- // as the call before it printed the family that had just gone empty).
597
- if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
598
- const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined, parent });
599
- if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
600
- bucketCache.set(key, { at: Date.now(), rows });
601
- return rows;
602
- }
603
-
604
- /** The flow's workers as lines, newest first — `null` when this session has no file to be a parent of,
605
- * which is when the caller reaches for `ledgerFamilyLines` instead.
606
- * Deliberately read from the picker's own data, not from a dev-flow index: renames, deletions and
607
- * workers an older session already delegated all read back correctly for free. `exclude` drops one
608
- * transcript: the caller already shows that run, and meeting it again as an anonymous row under
609
- * "other workers" reads like somebody else's work belongs to this flow. */
610
- async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleMs = 0): Promise<string[] | null> {
611
- const { file, dir } = lineageOf(ctx);
612
- if (!file) return null;
613
- try {
614
- return workerFamily(await bucketRows(ctx, dir, file, staleMs), file, { exclude });
615
- } catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
616
- }
617
-
618
- /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
619
- export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
620
-
621
-
622
- /** What a live worker run knows about itself — the one-worker-per-session guard and the ledger the
623
- * `op: "status"` verb reads. `lastLines` mirrors the live log (bounded); usage and turns accumulate
624
- * per run so the card and the result can say what the worker cost. */
625
- interface StageRun {
626
- startedAt: number;
627
- budgetMin: number;
628
- softFired: boolean;
629
- work: string;
630
- lastLines: string[];
631
- op: WorkerOp;
632
- /** "🔨 implement" / "🔍 verify" (+ ` · label`) — how the card and the beats name the run; session names use workerName instead. */
633
- kind: string;
634
- slug: string;
635
- usage: StageUsage;
636
- turns: number;
637
- /** the live worker's own session file, once spawned — a family listing leaves it out rather than
638
- * meeting the run twice: once as the run, once as an unlabeled row under "other workers". */
639
- transcript?: string;
640
- }
641
-
642
- const stageRuns = new Map<string, StageRun>();
643
-
644
406
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
645
407
  const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
646
408
 
@@ -694,13 +456,7 @@ function readClaim(root: string, slug: string): SessionClaim | null {
694
456
  }
695
457
 
696
458
  const writeClaim = (root: string, slug: string, key: string) =>
697
- atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now(), start: processStart(process.pid) })}\n`);
698
-
699
- /** "pid 854, claim 3 days old" — the age is what tells a live session from a recycled pid. */
700
- const claimWho = (claim: SessionClaim): string => {
701
- const age = claimAge(claim);
702
- return `pid ${claim.pid}${age ? `, claim ${age}` : ""}`;
703
- };
459
+ atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
704
460
 
705
461
  /** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
706
462
  * never dies, so a claim left behind by a finished session keeps refusing every later session with
@@ -884,26 +640,6 @@ async function worktreeFingerprint(cwd: string): Promise<string | null> {
884
640
  return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
885
641
  }
886
642
 
887
- /** The fingerprint a verify PASS belongs to: the worktree's, hashed TOGETHER WITH the feature's plan/
888
- * dir — the checker read the plan too, so a mid-stage plan edit voids its verdict exactly like a code
889
- * edit. null = git could not answer (same fingerprintless-stamp rule as tier-1 records). */
890
- async function verifyStampFingerprint(root: string, st: FlowState): Promise<string | null> {
891
- const base = await worktreeFingerprint(gateCwd(root, st));
892
- if (!base) return null;
893
- return createHash("sha256").update(`${base}\n${planFingerprint(path.join(root, ".dev-flow", st.slug, "plan"))}`).digest("hex").slice(0, 16);
894
- }
895
-
896
- /** Drop a PASS whose worktree-or-plan fingerprint no longer matches; true if one was dropped. Every
897
- * reader of the stamp (the verify gate, and the check/status views that must not keep advertising a
898
- * dead PASS) runs this before trusting the record. */
899
- async function voidStaleVerifyStamp(root: string, st: FlowState): Promise<boolean> {
900
- if (!st.checks[VERIFY_STAMP]) return false;
901
- const vfp = await verifyStampFingerprint(root, st);
902
- if (!vfp || st.checks[VERIFY_STAMP]!.wt === vfp) return false;
903
- delete st.checks[VERIFY_STAMP];
904
- return true;
905
- }
906
-
907
643
  /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
908
644
  * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
909
645
  async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
@@ -917,8 +653,9 @@ async function stampChecks(root: string, state: FlowState, names: string[]): Pro
917
653
  * question. Local refs only — same offline-safe stance as the changelog proof — and an
918
654
  * unanswerable merge base reports null instead of refusing on a measurement failure. */
919
655
  async function branchState(cwd: string, defaultBranch: string): Promise<BranchState> {
920
- const base = await mergeBase(cwd, defaultBranch);
921
- if (!base) return { commitsAhead: null, uncommitted: 0 };
656
+ const mb = await sh(`git merge-base origin/${sq(defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(defaultBranch)} HEAD 2>/dev/null || true`, cwd);
657
+ const base = mb.out.trim();
658
+ if (!mb.ok || !base) return { commitsAhead: null, uncommitted: 0 };
922
659
  const ahead = await sh(`git rev-list --count ${sq(base)}..HEAD`, cwd);
923
660
  const n = Number.parseInt(ahead.out.trim(), 10);
924
661
  const dirty = await sh("git status --porcelain", cwd);
@@ -928,54 +665,6 @@ async function branchState(cwd: string, defaultBranch: string): Promise<BranchSt
928
665
  };
929
666
  }
930
667
 
931
- /** The branch's merge base with the default branch, or "" when git cannot answer (no such ref, a
932
- * shallow clone). Callers read "" as "unprovable", never as "nothing ahead". Local refs only —
933
- * the same offline-safe stance as the changelog proof. */
934
- async function mergeBase(cwd: string, defaultBranch: string): Promise<string> {
935
- const mb = await sh(`git merge-base origin/${sq(defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(defaultBranch)} HEAD 2>/dev/null || true`, cwd);
936
- return mb.ok ? mb.out.trim() : "";
937
- }
938
-
939
- /** What the branch proves about *who* worked it: the flow's delegation ledger, the commits the branch
940
- * holds over the default branch, and the sha set each recorded **implement** window covers. Returns null for a
941
- * --docs or --patch flow — those modes are exempt, so nothing is measured and no git call is spent.
942
- * A window whose shas git cannot resolve covers nothing rather than excusing itself: a hand-written
943
- * line must not be able to exempt the commits lying next to it. */
944
- async function delegationProof(root: string, state: FlowState, defaultBranch: string): Promise<{ ledger: DelegationWindow[]; branchCommits: string[] | null; windowCommits: (w: DelegationWindow) => string[]; covered: number; windows: number } | null> {
945
- if (state.docs || state.patch) return null;
946
- const work = gateCwd(root, state);
947
- let ledger: DelegationWindow[] = [];
948
- try {
949
- ledger = parseDelegationLedger(readFileSync(path.join(featDir(root, state.slug), STAGE_SESSIONS_DIR, DELEGATIONS_FILE), "utf8"));
950
- } catch { /* no ledger yet: nobody delegated, which the gate reports rather than throwing on */ }
951
- const shas = async (cmd: string) => {
952
- const r = await sh(cmd, work);
953
- return r.ok ? r.out.split("\n").map((l) => l.trim()).filter(Boolean) : null;
954
- };
955
- const base = await mergeBase(work, defaultBranch);
956
- let branchCommits = base ? await shas(`git rev-list ${sq(base)}..HEAD`) : null;
957
- // Only implement windows are ever consulted (delegationErrors filters the same way), so a pre-release
958
- // or release worker's line resolves to nothing instead of costing a `git rev-list` per line — the
959
- // ledger grows with every worker the feature runs, and the gate reads it on every verify.
960
- // The `?? []` stays: a window whose objects git cannot resolve covers nothing, it does not excuse
961
- // itself — otherwise a hand-written line about a garbage range would exempt the commits beside it.
962
- const impl = ledger.filter((w) => w.stage === "implement");
963
- const ranges = new Map<string, string[]>();
964
- const key = (w: DelegationWindow) => `${w.start}..${w.end}`;
965
- for (const w of impl) ranges.set(key(w), (await shas(`git rev-list ${sq(w.start)}..${sq(w.end)}`)) ?? []);
966
- const windowCommits = (w: DelegationWindow) => ranges.get(key(w)) ?? [];
967
- // What the gate prints as proven is what the operator is approving, so the count is intersected with
968
- // the branch: a reset or an amend leaves the window's shas resolvable as loose objects while they are
969
- // no longer on the branch, and "delegation proven: 2 worker commit(s)" over a branch of one is a
970
- // claim about commits nobody is verifying. Coverage itself is delegationErrors' business — it reads
971
- // the branch, so nothing here can widen it.
972
- const onBranch = branchCommits ? new Set(branchCommits) : null;
973
- const proves = (w: DelegationWindow) => windowCommits(w).some((sha) => !onBranch || onBranch.has(sha));
974
- const covered = new Set<string>();
975
- for (const w of impl) for (const sha of windowCommits(w)) if (!onBranch || onBranch.has(sha)) covered.add(sha);
976
- return { ledger, branchCommits, windowCommits, covered: covered.size, windows: impl.filter(proves).length };
977
- }
978
-
979
668
  function describeBranchState(b: BranchState, defaultBranch: string): string {
980
669
  return b.commitsAhead === null
981
670
  ? `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`
@@ -1236,32 +925,8 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1236
925
  // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
1237
926
  // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
1238
927
  // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
1239
- const fpAtGate = await worktreeFingerprint(gateCwd(root, state!));
1240
- const staleAtGate = freshenChecks(state!, fpAtGate, (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1241
- // The stamp is judged by its own wider fingerprint (see verifyStampFingerprint): a change to the
1242
- // plan the verdict was written against demotes it exactly like a worktree change would.
1243
- const stampVoided = await voidStaleVerifyStamp(root, state!);
1244
- if (staleAtGate.length || stampVoided) writeState(root, state!);
1245
- // An independent checker has to have looked at THIS tree before the operator is asked to approve it:
1246
- // the verify worker's PASS is a precondition of the gate, refused before any command runs so a long
1247
- // suite is never spent on a run that cannot pass. The stamp lives in state.checks, so a worktree edit
1248
- // or a moved fingerprint drops it exactly like a tier-1 record — one fresh verify worker per change,
1249
- // precise friction rather than a sticky lock. docs mode is exempt (nothing there to check).
1250
- if (verifyStampMissing(state!)) {
1251
- writeState(root, state!);
1252
- return { text: `verify gate FAILED:\n- ${VERIFY_STAMP_REFUSAL}${staleAtGate.includes(VERIFY_STAMP) || stampVoided ? " (a PASS was recorded, but the tree or its plan moved since — that is why it no longer counts)" : ""}\n${branchLine}`, isError: true };
1253
- }
1254
- // The implement stage has to have been *worked*, not just driven: every commit the branch holds
1255
- // must fall inside a worker's run window, as recorded in stage-sessions/delegations.log. Refused
1256
- // before any command runs, like the stamp — and judged only here, because the driver's own commits
1257
- // after this gate (changelog, bump) are pre-release work and belong to the session by design.
1258
- // Coverage is an implement-stage claim. The stage check is verifyGate's and it sits AFTER this one,
1259
- // so a re-run at pre-release would otherwise answer "verify only applies to implement" with a
1260
- // delegation accusation about the driver's own changelog and bump commits — commits that are
1261
- // in-session work by design. Measuring only at implement keeps the refusal honest.
1262
- const deleg = state!.stage === "implement" ? await delegationProof(root, state!, cfg.defaultBranch) : null;
1263
- const delegErrs = deleg ? delegationErrors(state!, deleg.ledger, deleg.branchCommits, deleg.windowCommits) : [];
1264
- if (delegErrs.length) return { text: `verify gate FAILED:\n- ${delegErrs.join("\n- ")}\n${branchLine}`, isError: true };
928
+ const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
929
+ if (staleAtGate.length) writeState(root, state!);
1265
930
  const pending = pendingChecks(state!, cfg);
1266
931
  const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
1267
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 };
@@ -1273,12 +938,10 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1273
938
  const did: string[] = [];
1274
939
  if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
1275
940
  if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
1276
- if (deleg) did.push(`delegation proven: ${deleg.covered} worker commit(s) in ${deleg.windows} window(s)`);
1277
941
  if (state!.docs) {
1278
942
  // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
1279
943
  did.push("docs mode: project commands skipped (build/dev/health)");
1280
944
  } else {
1281
- did.push(`verify worker PASS over this tree (${state!.checks[VERIFY_STAMP]?.at ?? "recorded"})`);
1282
945
  if (cfg.commands.build) {
1283
946
  const res = await sh(cfg.commands.build, gateCwd(root, state!));
1284
947
  state!.checks.build = { ok: res.ok, at: now() };
@@ -1419,11 +1082,15 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1419
1082
  const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1420
1083
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1421
1084
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1422
- // a PASS whose worktree-or-plan moved is dead here too — no gate may act on a verdict it cannot prove current
1423
- if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1424
1085
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1425
1086
  const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1426
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
+ }
1427
1094
  // a stale session build is the operator's decision, never a block: publishing under an older gate is a
1428
1095
  // legitimate choice (hotfix, offline reload), and refusing would close exactly the emergency the relaxed
1429
1096
  // modes exist for. The gate names both builds, lists what the running code is missing, and folds the
@@ -1909,12 +1576,14 @@ ${mdDigest(draftRefresh)}`))
1909
1576
 
1910
1577
  async function gateStart(o: GateCtx): Promise<RunResult> {
1911
1578
  const { root, ui, sess, cfg, rest, flag, slugArg } = o;
1912
- if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --patch/--docs are operator-granted modes — ask the operator in chat, then add --confirmed", isError: true };
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 };
1913
1580
  if (existsSync(featDir(root, slugArg))) return { text: `feature ${slugArg} already exists`, isError: true };
1914
1581
  // relaxed modes are operator-granted: --confirmed anchors a literal chat grant, same convention as the gate verbs
1915
1582
  if (flag("patch") && flag("docs")) return { text: "--patch and --docs are exclusive — ask the operator which mode they grant", isError: true };
1916
1583
  const mode = flag("patch") ? "patch" : flag("docs") ? "docs" : null;
1917
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 };
1918
1587
  // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
1919
1588
  const curBr = await currentBranch(root);
1920
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 };
@@ -2040,23 +1709,13 @@ async function gateStatus(o: GateCtx): Promise<RunResult> {
2040
1709
  const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
2041
1710
  const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
2042
1711
  const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
2043
- // status (and --json, which feeds worker briefs) must never advertise a PASS the gates would refuse:
2044
- // reap dead stamps in the copies being rendered — and persist only THIS session's own feature, since
2045
- // a foreign state.json belongs to its own session (a listing must not write another session's file).
2046
- const states = new Map<string, FlowState>();
2047
- for (const s of slugs) {
2048
- const stV = readState(root, s);
2049
- if (!stV) continue;
2050
- if (await voidStaleVerifyStamp(root, stV) && s === sess.slug) writeState(root, stV);
2051
- states.set(s, stV);
2052
- }
2053
1712
  if (flag("json")) {
2054
- 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);
2055
1714
  return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
2056
1715
  }
2057
1716
  if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
2058
1717
  const lines = slugs.flatMap((s) => {
2059
- const st = states.get(s);
1718
+ const st = readState(root, s);
2060
1719
  if (!st) return [];
2061
1720
  return [
2062
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}` : ""}`,
@@ -2158,7 +1817,6 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2158
1817
  const loaded = loadProject(df);
2159
1818
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
2160
1819
  findings.push(...(await gitConsistency(root, loaded.cfg)));
2161
- findings.push(...orphanBucketFindings(root));
2162
1820
  const refl = readReflections(root);
2163
1821
  const fold = await foldView(root, refl, isSelfRepo(root));
2164
1822
  if (refl.length) {
@@ -2180,35 +1838,6 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2180
1838
  return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
2181
1839
  }
2182
1840
 
2183
- /** Session buckets stage workers left under finished or vanished worktrees (see `orphanWorktreeBuckets`).
2184
- * Information only: the doctor names them and the command that removes them; deleting transcripts is
2185
- * the operator's call, never the doctor's. Silent when there is no session store to read. */
2186
- function orphanBucketFindings(root: string): string[] {
2187
- const sessionsRoot = testSeams.sessionsRoot.value === undefined ? path.join(getAgentDir(), "sessions") : testSeams.sessionsRoot.value;
2188
- if (!sessionsRoot || !existsSync(sessionsRoot)) return [];
2189
- let buckets: string[];
2190
- try { buckets = readdirSync(sessionsRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { return []; }
2191
- const features = new Map<string, WorktreeBucketFeature>();
2192
- try {
2193
- for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
2194
- if (!d.isDirectory()) continue;
2195
- const st = readState(root, d.name);
2196
- if (!st) continue;
2197
- const wt = st.worktree ? path.resolve(root, st.worktree) : null;
2198
- features.set(d.name, { finished: st.stage === "done" || !!st.aborted, worktreeExists: !!wt && existsSync(wt) });
2199
- }
2200
- } catch { /* no .dev-flow dir: every matching bucket is an orphan */ }
2201
- const orphans = orphanWorktreeBuckets(buckets, root, features);
2202
- if (!orphans.length) return [];
2203
- const rows = orphans.map((o) => {
2204
- const dir = path.join(sessionsRoot, o.bucket);
2205
- let n = 0;
2206
- try { n = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).length; } catch { /* count is cosmetic */ }
2207
- return ` ${o.slug}: ${n} transcript(s) — rm -r ${sq(dir)}`;
2208
- });
2209
- return [`worker session buckets left by finished or removed worktrees (${orphans.length}) — stage workers before 0.70 filed under their worktree, where no picker scope opened from this checkout shows them; keep them for the record or remove:\n${rows.join("\n")}`];
2210
- }
2211
-
2212
1841
  /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
2213
1842
  * their own names back, so the bodies needed zero edits. */
2214
1843
  interface GateCtx {
@@ -2263,7 +1892,6 @@ async function gateCheck(o: GateCtx): Promise<RunResult> {
2263
1892
  // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
2264
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)" };
2265
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 };
2266
- if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
2267
1895
  const ran = await runChecks(root, state!, cfg, cfg.checkList);
2268
1896
  return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
2269
1897
  }
@@ -2289,7 +1917,7 @@ async function gateUse(o: GateCtx): Promise<RunResult> {
2289
1917
  const st = readState(root, slugArg);
2290
1918
  if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
2291
1919
  const prior = readClaim(root, slugArg);
2292
- 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})` : "";
2293
1921
  sess.bind(slugArg);
2294
1922
  sess.rename(slugArg);
2295
1923
  // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
@@ -2310,7 +1938,7 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2310
1938
  // a live claim locks the whole feature, not only its gates: aborting it out from under the session
2311
1939
  // that works it erases the plan that session is still writing (same rule needState applies)
2312
1940
  const claim = readClaim(root, target);
2313
- if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (${claimWho(claim!)}) — flow use ${target} takes it over explicitly`, isError: true };
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 };
2314
1942
  if (sess.slug === target) sess.bind(null);
2315
1943
  if (st && !st.worktree) {
2316
1944
  // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
@@ -2323,7 +1951,28 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2323
1951
  }
2324
1952
 
2325
1953
 
2326
- /** 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
+
2327
1976
  async function isLinkedWorktree(root: string): Promise<boolean> {
2328
1977
  const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", root);
2329
1978
  if (!r.ok) return false;
@@ -2331,23 +1980,13 @@ async function isLinkedWorktree(root: string): Promise<boolean> {
2331
1980
  return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
2332
1981
  }
2333
1982
 
2334
- /** Per-cwd cache for flowRoot: consulted on every tool call of every session, and a git probe per call
2335
- * is not acceptable there. A cwd's answer never changes while the process lives (a worktree that gets
2336
- * removed stops being anyone's cwd; a plain clone does not become one). */
1983
+ /** Per-cwd cache for flowRoot — the tool_call hook consults it on every call. */
2337
1984
  const flowRootCache = new Map<string, string>();
2338
1985
 
2339
- /** The root whose .dev-flow/ is the flow truth for a session cwd.
2340
- *
2341
- * A feature worktree is a **linked git worktree**, and the default worktreeDir (.dev-flow/<slug>/worktree)
2342
- * makes its own tracked .dev-flow/ hold one file: project.md. The state, the claims, the plans and the
2343
- * delegation ledger all live in the main checkout, so judging a worker by its own cwd found zero features
2344
- * and every guard answered "no active flow" — the write-guard's worker half never fired, because byWorker
2345
- * was only ever consulted after owner attribution, and owner attribution had nothing to attribute. A
2346
- * worker fell back to bash authoring, which is the half the guard was never meant to police.
2347
- *
2348
- * So: a linked worktree resolves to its main checkout (git's common dir is <main>/.git), and only when
2349
- * that checkout is actually initiated — otherwise the cwd answer stands, which keeps plain clones, scratch
2350
- * repos and every test fixture behaving exactly as before. */
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. */
2351
1990
  async function flowRoot(cwd: string): Promise<string> {
2352
1991
  const hit = flowRootCache.get(cwd);
2353
1992
  if (hit !== undefined) return hit;
@@ -2381,7 +2020,7 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
2381
2020
  // sessions overwrite one state file (last write wins) while both believe they own the stage.
2382
2021
  const claim = readClaim(root, slug);
2383
2022
  if (sess.slug !== slug && claimBlocks(claim, sess.key))
2384
- return { state: null, err: { text: `${slug} is claimed by another live session (${claimWho(claim!)}) — flow use ${slug} takes it over explicitly`, isError: true } };
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 } };
2385
2024
  return { state };
2386
2025
  }
2387
2026
 
@@ -2520,7 +2159,7 @@ export default function devFlow(pi: ExtensionAPI) {
2520
2159
  description:
2521
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.",
2522
2161
  parameters: Type.Object({
2523
- 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"]' }),
2524
2163
  }),
2525
2164
  execute: async (_id, params, _signal, _onUpdate, ctx) => {
2526
2165
  const res = await runFlow(params.args, ctx.cwd, uiFrom(ctx), sessFor(ctx));
@@ -2530,399 +2169,109 @@ export default function devFlow(pi: ExtensionAPI) {
2530
2169
  });
2531
2170
  pi.registerTool(flowTool);
2532
2171
 
2533
- /** The text a worker's finished tool call carried (first text part, else an error string) — the live
2534
- * ✓/✗ line is built from it, so a worker that gets an error back shows it, not just the tool name. */
2535
- function resultText(result: unknown): string {
2536
- const r = result as { content?: unknown; text?: string; errorMessage?: string } | undefined;
2537
- const parts = Array.isArray(r?.content) ? (r!.content as { type?: string; text?: string }[]) : [];
2538
- return parts.find((p) => p?.type === "text")?.text ?? r?.text ?? r?.errorMessage ?? "";
2539
- }
2540
-
2541
- /** The assistant prose of a worker turn — text parts only, thinking and tool calls have their own lines. */
2542
- function assistantText(content: unknown): string {
2543
- if (typeof content === "string") return content;
2544
- if (!Array.isArray(content)) return "";
2545
- return (content as { type?: string; text?: string }[]).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n");
2546
- }
2172
+ /** Driver sessions with a worker running right now — one worker per session at a time. */
2173
+ const runningWorkers = new Set<string>();
2547
2174
 
2548
- /** Last non-empty line: the end of a tool dump is the verdict-bearing part ("251 pass", "exit 1",
2549
- * the error), its head is almost never the news. */
2550
- function lastLineOf(text: string): string {
2551
- return (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
2552
- }
2553
-
2554
- // ---- stage worker (flow_stage): one stage's work, its check and its review in a disposable sub-session --
2555
- // The child stays UNBOUND on purpose: writeGuard attributes worktree writes to the owning
2556
- // feature's stage and bashFlowGuard stops only default-branch git ops, so an implement worker may
2557
- // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and the
2558
- // parent holds the live claim) — and its tool list holds no flow tool at all. The claim, every gate
2559
- // and every checkpoint stay with the driving session; the worker owes one report.
2560
- // Three ops share this one mechanism on purpose: `run` (a stage's work), `verify` (an independent
2561
- // read-only checker whose PASS the verify gate demands) and `reflect` (an independent review of the
2562
- // whole finished flow). Only the brief, the toolset, the budget default and the closing contract
2563
- // differ — the unbound-worker safety story is identical, and a second mechanism would drift.
2564
2175
  const stageWorkerTool = defineTool({
2565
2176
  name: "flow_stage",
2566
2177
  label: "Stage worker",
2567
2178
  description:
2568
- 'Delegate to a disposable dev-flow worker session with a fresh context. op "run" (default) does the current stage\'s work (implement | pre-release) and edits + commits on the feature branch; op "verify" is an independent read-only checker of the implement work (read + bash, standing order "check, don\'t fix", closes with a VERIFY REPORT verdict — flow verify refuses until a PASS exists over the current tree); op "reflect" reviews the finished flow — the driver transcript plus every worker transcript — at the release stage after release-done. Everything the worker must know — operator answers not yet recorded by a gate, decisions, warnings, the exact next action — travels in `note`; otherwise it sees only plan, git and flow status. Give each delegation a short `label` (a few words of purpose) — session names then read `⏳ 🔍 #1 · <label>` while running and `✓ 🔍 #1 · PASS · <label>` (or `✗ … · hard-cut`, `✓ 🔨 #2 · 3 commits · <label>`) when done, so the picker is never a column of identical rows. A worker holds no flow tool: gates, checkpoints and the claim stay with you. At 75% of its budget (budgetMin: default 45 for run, 30 for verify/reflect) the worker is steered to commit and report instead of being cut. The tool card streams the live tail (current tool, last assistant line, ✓/✗ results, elapsed/budget, usage) and op "status" mirrors it on any host. When a worker returns: read its report, run flow check yourself, then ask the checkpoint — a stage report is a handoff, never a verification.',
2569
- promptSnippet:
2570
- 'flow_stage(op: "run"|"verify"|"reflect", note, budgetMin?) — delegate stage work, an independent read-only check, or the finish review to a fresh worker session; op: "status" reads the live run; gates and checkpoints stay with you',
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',
2571
2181
  parameters: Type.Object({
2572
- op: Type.Optional(Type.String({ description: '"run" (default) delegates the stage work; "verify" = independent check-only review of the implement work (legal only while the feature is at implement); "reflect" = independent review of the finished flow (legal at release, after release-done); "status" reports the live worker run in this session' })),
2573
- stage: Type.Optional(Type.String({ description: 'With op "run": the stage to delegate the work for — must match the bound feature\'s current stage. "verify" and "reflect" belong to a fixed stage and ignore this.' })),
2574
- note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
2575
- budgetMin: Type.Optional(Type.Number({ description: "Worker budget in minutes (5-120; default 45 for run, 30 for verify/reflect). At 75% the worker is steered to commit and report; past the budget it is interrupted and the tree snapshotted." })),
2576
- label: Type.Optional(Type.String({ description: 'Short purpose for this delegation (≤\u007e32 chars) shown in the session name and card, so a re-delegation reads `🔨 #2 · <purpose>` instead of a clone row. Sanitized and clipped.' })),
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." })),
2577
2186
  }),
2578
- // The card is the guaranteed worker-visibility surface: it renders inside the driver's own
2579
- // transcript, in TUI and in pi-web alike, because every line also travels as the update's text.
2580
- renderCall: (args, theme) => {
2581
- const op = String(args.op ?? "run");
2582
- const what = op === "run" ? `run ${args.stage ?? "?"}` : op;
2583
- return new Text(theme.fg("toolTitle", `flow_stage ${what}`) + (args.note ? ` ${theme.fg("muted", liveClip(String(args.note), 70))}` : ""), 0, 0);
2584
- },
2585
- renderResult: (result, options, theme) => {
2586
- const d = result.details as { card?: string[]; cardFull?: string[]; verdict?: string | null } | undefined;
2587
- const lines = (options.expanded ? d?.cardFull ?? d?.card : d?.card) ?? [];
2588
- if (!lines.length) return new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n") || "(no output)", 0, 0);
2589
- const box = new Container();
2590
- for (const line of lines) {
2591
- const text = options.expanded ? line : liveClip(line, 120);
2592
- box.addChild(new Text(line.startsWith("✗") || line.startsWith("verdict: FAIL") ? theme.fg("error", text) : line.startsWith("✓") || line.startsWith("verdict: PASS") ? theme.fg("success", text) : theme.fg("muted", text), 0, 0));
2593
- }
2594
- if (options.expanded) {
2595
- box.addChild(new Text(theme.fg("dim", "─── report ───"), 0, 0));
2596
- box.addChild(new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n"), 0, 0));
2597
- }
2598
- return box;
2599
- },
2600
2187
  execute: async (_id, params, signal, onUpdate, ctx) => {
2601
2188
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2602
- const opRaw = String(params.op ?? "run").trim().toLowerCase();
2603
- if (!isWorkerOp(opRaw)) return err(`unknown op "${opRaw}" — flow_stage ops: run (delegate the stage work), verify (independent check), reflect (finish review), status (the live run)`);
2604
- const op: WorkerOp = opRaw;
2605
- if (op === "status") {
2606
- const run = stageRuns.get(sessionKey(ctx));
2607
- // The family is the question op:"status" gets when nothing is running — "what has this flow
2608
- // spawned, and how did each end?". pi's picker threads the same rows into a tree; this is
2609
- // that fact for a host with no tree, and for the moment between runs. A worker that is live
2610
- // right now is the section above, not one of "the others" — so it is left out here. The whole
2611
- // section is gated on a bound feature: an unbound session has never spawned a stage worker,
2612
- // so there it would be noise paid for with a directory scan.
2613
- const boundState = (() => { try { return initiated(ctx.cwd) ? boundFeature(ctx.cwd, sessionKey(ctx)) : null; } catch { return null; } })();
2614
- const inFlow = !!boundState;
2615
- const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
2616
- // the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
2617
- const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE), run?.transcript) : null);
2618
- const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
2619
- if (!run) {
2620
- return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
2621
- }
2622
- const elapsed = Date.now() - run.startedAt;
2623
- const dirtyNow = await sh("git status --porcelain", run.work);
2624
- const logNow = await sh("git log --oneline -5", run.work);
2625
- const text = [
2626
- `stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
2627
- ...liveTail(run.lastLines),
2628
- stageUsageLine(run.usage, run.turns),
2629
- `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2630
- `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2631
- ...(inFlow ? ["", ...familySection] : []),
2632
- ].join("\n");
2633
- return { content: [{ type: "text", text }], details: { running: true, op: run.op, slug: run.slug, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired, usage: run.usage, turns: run.turns, workers: workerFamilyCount(familyLines) } };
2634
- }
2189
+ const op = String(params.op ?? "").trim().toLowerCase();
2635
2190
  if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2636
- const st = boundFeature(ctx.cwd, sessionKey(ctx));
2637
- if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2638
- const stageArg = String(params.stage ?? "");
2639
- if (op === "run") {
2640
- if (!isDelegableStage(stageArg)) return err(`flow_stage delegates the work of: ${DELEGABLE_STAGES.join(" or ")} — "${stageArg}" is not delegable (plan is the operator dialogue; release/finish carry the checkpoint words; op "status" needs no stage)`);
2641
- if (st.stage !== stageArg) return err(`feature ${st.slug} is at stage "${st.stage}", not "${stageArg}" — flow_stage runs the work of the stage you are in`);
2642
- } else {
2643
- const why = workerOpError(op, st);
2644
- if (why) return err(why);
2645
- if (stageArg && stageArg !== st.stage) return err(`op "${op}" belongs to the stage the flow is in ("${st.stage}"), not "${stageArg}" — the op names its own stage`);
2646
- }
2647
2191
  const key = sessionKey(ctx);
2648
- if (stageRuns.has(key)) return err(`a stage worker for ${st.slug} is already running in this session — one worker per session; flow_stage {op: "status"} reads the live one`);
2649
- const budgetMin = clampStageBudgetMin(params.budgetMin ?? WORKER_OP_BUDGET_MIN[op]);
2650
- const budgetMs = budgetMin * 60_000;
2651
- const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
2652
- const hardMs = stageTimingOverride.hardMs ?? budgetMs;
2653
- const glyph = WORKER_OP_GLYPH[op];
2654
- const label = typeof params.label === "string" ? sanitizeWorkerLabel(params.label) : "";
2655
- // the card/beats keep the descriptive kind (the card line has no other stage context); the
2656
- // session NAMES are compact — glyph, ordinal, purpose (see workerName)
2657
- const kind = op === "run" ? `${glyph} ${st.stage}` : `${glyph} ${op}`;
2658
- const kindCard = label ? `${kind} · ${label}` : kind;
2659
- const work = gateCwd(ctx.cwd, st);
2660
- const run: StageRun = {
2661
- startedAt: Date.now(), budgetMin, softFired: false, work, lastLines: [],
2662
- op, kind, slug: st.slug, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, turns: 0,
2663
- };
2664
- stageRuns.set(key, run);
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);
2665
2201
  const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2666
- const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2667
- const transcriptLog = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE);
2668
- const delegationLog = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR, DELEGATIONS_FILE);
2669
- // read once, used twice: the worker's header links to this file and lands in this bucket,
2670
- // and the reflect brief names this session's own transcript to the reviewer
2671
- const lineage = lineageOf(ctx);
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 */ }
2672
2220
  let child: AgentSession | undefined;
2673
- let crash: string | null = null;
2674
2221
  let timedOut = false;
2675
- /** The card frame for this instant — one place so the streamed text, the TUI card and
2676
- * op:"status" can never disagree about what the worker is doing. */
2677
- const cardView = (state: "running" | "done" | "failed", extra: { verdict?: "pass" | "fail" | null; transcript?: string } = {}) =>
2678
- stageCardLines({ kind: kindCard, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state, ...extra });
2679
- const emit = (event: string, data: Record<string, unknown>) => {
2680
- try { pi.events.emit(event, { slug: st.slug, op, stage: st.stage, ...data }); } catch { /* the bus is visibility, never function */ }
2681
- };
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;
2682
2229
  try {
2683
- writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2684
- const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2685
- // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2686
- // read #2, #3 in the list instead of identical rows. A verify is numbered too: a feature that
2687
- // takes six rounds to PASS reads as a sequence, not as six free-text labels. A reflect is one per flow.
2688
- const seq = op !== "reflect" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2689
- const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2690
- const git = await sh("git status --porcelain -b", work);
2691
- const note = typeof params.note === "string" ? params.note : undefined;
2692
- const planFile = path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md");
2693
- let brief: string;
2694
- if (op === "verify") {
2695
- // the reviewer reads the full diff itself; the stat is only the shape of what it is in for
2696
- const stat = await sh(`git diff --shortstat ${sq(`origin/${cfg.defaultBranch}`)}...HEAD 2>/dev/null || git diff --shortstat ${sq(cfg.defaultBranch)}...HEAD`, work);
2697
- const tier1 = [...cfg.checkList];
2698
- if (cfg.commands.test && !tier1.some((c) => c.name === "test")) tier1.push({ name: "test", cmd: cfg.commands.test });
2699
- brief = buildVerifyBrief({
2700
- slug: st.slug, workDir: work, planFile, statusJson: statusJsonText,
2701
- gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2702
- diffStat: stat.ok ? stat.out.trim() : "(no diff stat)",
2703
- defaultBranch: cfg.defaultBranch, checks: tier1, note,
2704
- });
2705
- } else if (op === "reflect") {
2706
- const transcripts = existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")) : [];
2707
- brief = buildReflectBrief({
2708
- slug: st.slug, planFile, statusJson: statusJsonText, driverSession: lineage.file, transcripts,
2709
- openReflections: readReflections(ctx.cwd).map((r) => r.line), note,
2710
- });
2711
- } else {
2712
- const refRel = stageReference(st.stage);
2713
- let refText = "";
2714
- if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2715
- brief = buildStageBrief({ slug: st.slug, stage: st.stage as DelegableStage, workDir: work, planFile, referenceText: refText, statusJson: statusJsonText, gitSummary: git.ok ? git.out.trim() : "(git status failed)", note });
2716
- }
2717
- // the tree identity a verify verdict belongs to, before anything runs: the same comparison
2718
- // the tier-1 fingerprint makes, done here because a reviewer must not be the one who edited.
2719
- // HEAD is captured too: a reviewer that commits or moves a ref leaves `git status` clean while
2720
- // reading a different tree, so a porcelain-only diff would stamp a PASS for a HEAD it never saw.
2721
- const statusBefore = await sh("git status --porcelain", work);
2722
- const headBefore = await sh("git rev-parse HEAD", work);
2723
- const refBefore = await sh("git symbolic-ref -q HEAD || true", work);
2724
- // the plan is an input the reviewer reads from OUTSIDE the worktree — it belongs in the
2725
- // before/after proof too, or a reviewer could rewrite the ground it is judging mid-run
2726
- const planDir = path.join(ctx.cwd, ".dev-flow", st.slug, "plan");
2727
- const planBefore = planFingerprint(planDir);
2728
- // the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
2729
- // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2730
- // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2731
- const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: workerName("⏳", glyph, seq, label), tools: [...WORKER_OP_TOOLS[op]], parent: lineage.file ?? undefined, dir: lineage.dir ?? undefined });
2732
- child = worker.session;
2733
- try { run.transcript = child.sessionManager.getSessionFile() ?? undefined; } catch { /* the family listing just won't know which row is this run */ }
2734
- emit("dev-flow:worker-started", { budgetMin, startedAt: new Date().toISOString() });
2735
- let lastBeat = 0;
2736
- /** One live line: ledger, durable log, and the streamed card — same text on every host. */
2737
- const pushLine = (line: string) => {
2738
- if (!line) return;
2739
- run.lastLines.push(line);
2740
- if (run.lastLines.length > 50) run.lastLines.shift();
2741
- try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2742
- const card = cardView("running");
2743
- onUpdate?.({ content: [{ type: "text", text: card.join("\n") }], details: { running: true, op, slug: st.slug, stage: st.stage, card, cardFull: stageCardLines({ kind, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state: "running" }, true) } });
2744
- };
2745
- const unsub = child.subscribe((ev: unknown) => {
2746
- const e = ev as { type?: string; toolName?: string; args?: unknown; isError?: boolean; result?: unknown; message?: { role?: string; content?: unknown; usage?: Record<string, number> & { cost?: Record<string, number> } } };
2747
- const elapsed = () => Date.now() - run.startedAt;
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 };
2748
2233
  if (e.type === "tool_execution_start") {
2749
- pushLine(stageLiveLine(elapsed(), e.toolName ?? "?", summarizeToolArgs(e.args)));
2750
- const now = Date.now();
2751
- if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
2752
- }
2753
- if (e.type === "tool_execution_end") {
2754
- // the last line of the result is the verdict-bearing one ("251 pass", "exit 1",
2755
- // the error) — the head of a tool dump is almost never the news
2756
- pushLine(stageLiveResultLine(elapsed(), e.toolName ?? "?", !e.isError, lastLineOf(resultText(e.result))));
2757
- }
2758
- if (e.type === "message_end" && e.message?.role === "assistant") {
2759
- run.turns++;
2760
- const u = e.message.usage;
2761
- if (u) {
2762
- for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) run.usage[f] += Number(u[f] ?? 0);
2763
- if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) run.usage.cost[f] += Number(u.cost[f] ?? 0);
2764
- }
2765
- pushLine(stageLiveAssistantLine(elapsed(), assistantText(e.message.content)));
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 } });
2766
2236
  }
2767
2237
  });
2768
- const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2769
- // grace before the cliff: at 75% the worker is told to commit and report — an honest handoff
2770
- // beats an abort; the hard timer stays the backstop for a worker that ignores the steer
2771
- const softTimer = setTimeout(() => {
2772
- run.softFired = true;
2773
- try { void Promise.resolve(child?.steer(stageInterruptSteer(budgetMin))).catch(() => {}); } catch { /* hard cut follows */ }
2774
- }, softMs);
2775
- const hardTimer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2776
- signal?.addEventListener("abort", abortChild);
2777
- try {
2778
- await child.prompt(brief);
2779
- } catch (e) {
2780
- crash = e instanceof Error ? e.message : String(e);
2781
- } finally {
2782
- clearTimeout(softTimer);
2783
- clearTimeout(hardTimer);
2784
- unsub();
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() ?? "");
2785
2245
  }
2786
- const clean = !crash && !timedOut;
2787
- const transcript = child.sessionManager.getSessionFile() ?? "";
2788
- // the durable worker index: until now a transcript path lived only in this call's result,
2789
- // i.e. only as long as the driver kept it in context — the reflect worker needs the list
2790
- if (transcript) {
2791
- try {
2792
- mkdirSync(path.dirname(transcriptLog), { recursive: true });
2793
- appendFileSync(transcriptLog, `${workerTranscriptLine(now(), op, transcript)}\n`);
2794
- } catch { /* an index that failed to append is never a reason to lose the run */ }
2795
- }
2796
- const report = op === "run" ? parseStageReport(child.getLastAssistantText() ?? "") : null;
2797
- const verify = op === "verify" ? parseVerifyReport(child.getLastAssistantText() ?? "") : null;
2798
- const findings = op === "reflect" ? parseReflectFindings(child.getLastAssistantText() ?? "") : null;
2799
- // A check-only worker must leave the tree exactly as it found it: the verdict is a claim
2800
- // about THIS tree, so a reviewer that touched anything voids its own report. Computed before
2801
- // the rename and the stamp so both readers agree on one verdict of "did the ground move".
2802
- // (The gate's own uncommitted-path policy stays unchanged — a tree already dirty is not the
2803
- // worker's fault; only movement counts.)
2804
- const statusAfter = await sh("git status --porcelain", work);
2805
- const headAfter = await sh("git rev-parse HEAD", work);
2806
- const refAfter = await sh("git symbolic-ref -q HEAD || true", work);
2807
- // four legs, because each alone has a clean-tree bypass: porcelain misses ref moves,
2808
- // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2809
- // and all three miss the plan the verdict was written against living outside the worktree
2810
- const moved = op !== "run" && ((statusBefore.ok && statusAfter.ok && statusAfter.out !== statusBefore.out) || (headBefore.ok && headAfter.ok && headAfter.out !== headBefore.out) || (refBefore.ok && refAfter.ok && refAfter.out !== refBefore.out) || planFingerprint(planDir) !== planBefore);
2811
- // the outcome goes INTO the final name — a picker row like `✓ 🔍 #3 · PASS · stamp attack` or
2812
- // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2813
- let outcome: string | null = null;
2814
- // The delegation ledger: this run's commit window, recorded however it ended — a
2815
- // hard-cut worker's commits still sit on the branch, and a window the gate never learned
2816
- // about reads as driver-authored work at flow verify. One count serves both: the picker row and the ledger.
2817
- let runCommits = 0;
2818
- if (op === "run" && headBefore.ok && headAfter.ok) {
2819
- const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
2820
- runCommits = c.ok ? Number.parseInt(c.out.trim(), 10) || 0 : 0;
2821
- try {
2822
- mkdirSync(path.dirname(delegationLog), { recursive: true });
2823
- appendFileSync(delegationLog, `${delegationLine(now(), st.stage, headBefore.out.trim(), headAfter.out.trim(), runCommits)}\n`);
2824
- } catch { /* an index that failed to append is never a reason to lose the run */ }
2825
- }
2826
- if (clean) {
2827
- if (runCommits > 0) outcome = `${runCommits} commit${runCommits === 1 ? "" : "s"}`;
2828
- if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
2829
- if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
2830
- } else {
2831
- outcome = timedOut ? "hard-cut" : "crashed";
2832
- }
2833
- worker.rename(workerName(clean ? "✓" : "✗", glyph, seq, label, outcome));
2834
- // never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
2835
- // via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
2836
- let snapshot: string | null = null;
2837
- const dirty = await sh("git status --porcelain", work);
2838
- if (dirty.ok && dirty.out.trim()) {
2839
- const snapDir = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR);
2840
- mkdirSync(snapDir, { recursive: true });
2841
- const stamp = Date.now();
2842
- const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
2843
- const idx = path.join(snapDir, `.snap-index-${stamp}`);
2844
- const snapRun = await sh(`GIT_INDEX_FILE=${sq(idx)} git read-tree HEAD && GIT_INDEX_FILE=${sq(idx)} git add -A && T=$(GIT_INDEX_FILE=${sq(idx)} git write-tree) && git diff HEAD "$T" > ${sq(diffFile)}; rm -f ${sq(idx)}`, work);
2845
- if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
2846
- }
2847
- // An implement worker dirtied tier-1 records through the same hooks any edit dirties them, so
2848
- // the check reruns here: it runs on the driver's binding and its verdict rides along in the
2849
- // digest. A check-only op touched nothing (proved below), so its records still stand — and
2850
- // re-running a whole suite here would spend it twice and hide the gate's own re-run.
2851
- const check = op === "run" ? await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx)) : null;
2852
- // the PASS is stamped AFTER the rerun so it belongs to the settled tree, and only over a tree
2853
- // the reviewer actually left untouched — this stamp is what flow verify demands at the gate
2854
- let stamped = false;
2855
- let cleared = false;
2856
- if (verify?.verdict === "pass" && clean && !moved) {
2857
- const fresh = readState(ctx.cwd, st.slug);
2858
- if (fresh) {
2859
- recordVerifyPass(fresh, now(), await verifyStampFingerprint(ctx.cwd, fresh));
2860
- writeState(ctx.cwd, fresh);
2861
- stamped = true;
2862
- }
2863
- } else if (verify?.verdict === "fail" && !moved) {
2864
- // a FAIL over an unmoved tree contradicts any earlier PASS — the gate may not ask
2865
- // Verified? against a tree its newest checker rejected
2866
- const fresh = readState(ctx.cwd, st.slug);
2867
- if (fresh?.checks[VERIFY_STAMP]) {
2868
- delete fresh.checks[VERIFY_STAMP];
2869
- writeState(ctx.cwd, fresh);
2870
- cleared = true;
2871
- }
2872
- }
2873
- const parts: string[] = [];
2874
- if (report) parts.push(renderStageReport(report));
2875
- if (verify) {
2876
- parts.push(renderVerifyReport(verify));
2877
- if (stamped) parts.push(`PASS stamped on this tree — flow verify will accept it until the tree moves (any edit drops it like a tier-1 record, then a fresh verify worker is owed).`);
2878
- if (cleared) parts.push("an earlier PASS over this tree was DROPPED — this FAIL contradicts it; fix the findings, then a fresh verify worker is owed.");
2879
- else if (moved) parts.push(`VERDICT VOID: the verify worker moved the tree, HEAD, branch pointer or plan (the before/after proof differs from before its run) — a reviewer that edits invalidates its own report.${snapshot ? ` Snapshot: ${snapshot}` : ""}`);
2880
- else if (!clean) parts.push("no verdict recorded from a crashed or interrupted run — rerun the verify worker.");
2881
- else parts.push(`the verify gate will refuse Verified? until a verify worker returns verdict: pass over the current tree${verify.verdict === "fail" ? " (this one returned FAIL — fix the findings, then rerun)" : ""}.`);
2882
- }
2883
- if (findings) {
2884
- if (findings.missing) parts.push("reflect worker ended WITHOUT tagged findings — nothing parsed as [playbook]/[plugin]; its tail is below, read it before concluding the review found nothing:", "```", findings.rawTail, "```");
2885
- else {
2886
- parts.push(
2887
- `playbook findings (${findings.playbook.length}):`, ...(findings.playbook.length ? findings.playbook.map((x) => `[playbook] ${x}`) : ["- none"]),
2888
- `plugin findings (${findings.plugin.length}):`, ...(findings.plugin.length ? findings.plugin.map((x) => `[plugin] ${x}`) : ["- none"]),
2889
- ...(findings.other.length ? ["other:", ...findings.other.map((x) => `[neither] ${x}`)] : []),
2890
- "put the findings to the operator (Fold? Fix? Drop?) — queue what they fold with flow reflect --playbook|--plugin; the worker queued nothing.",
2891
- );
2892
- }
2893
- }
2894
- if (run.softFired) parts.push(`worker was steered to close out at its ${budgetMin}-min budget${timedOut ? " and still needed the hard cut — treat the report as mid-stage" : " — committed and reported by choice"}`);
2895
- if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
2896
- if (crash) parts.push(`worker run ended with an error: ${crash}`);
2897
- if (snapshot && !verify) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2898
- parts.push(check ? `tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}` : "tier-1 untouched: a check-only worker leaves the tree (and the records) as it found them — flow check / flow verify rerun what the tree still owes.");
2899
- parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}\nindexed in: ${transcriptLog}${lineage.file && transcript ? `\nlineage: nested under ${lineage.file} in pi's picker (Threaded, Current Folder)` : ""}`);
2900
- const failed = !!crash || timedOut || moved;
2901
- // the family belongs on the settled card and the result only: a live frame redraws on every
2902
- // worker tool call, and reading a session bucket is IO. This run is excluded — the card names
2903
- // its transcript already, and repeating it as a bare row reads like a different worker.
2904
- const famFromPicker = await workerFamilyLines(ctx, transcript || undefined);
2905
- const fam = famFromPicker ?? ledgerFamilyLines(transcriptLog, transcript || undefined);
2906
- emit(failed ? "dev-flow:worker-failed" : "dev-flow:worker-completed", {
2907
- elapsedMs: Date.now() - run.startedAt, usage: run.usage, turns: run.turns, budgetMin, softFired: run.softFired, timedOut, crash,
2908
- verdict: verify?.verdict ?? null, reportMissing: report?.missing ?? findings?.missing ?? false, transcript, snapshot,
2909
- });
2910
- const card = cardView(failed ? "failed" : "done", { verdict: verify?.verdict ?? null, transcript });
2911
- return {
2912
- content: [{ type: "text" as const, text: parts.join("\n\n") }],
2913
- details: {
2914
- op, slug: st.slug, stage: st.stage, card, cardFull: stageCardLines({ kind, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state: failed ? "failed" : "done", verdict: verify?.verdict ?? null, transcript, family: fam?.length ? fam : undefined, familyHeading: famFromPicker === null ? familyHeading({ ledger: true }) : undefined }, true),
2915
- done: report?.done, files: report?.files, notes: report?.notes, blockers: report?.blockers, reportMissing: report?.missing ?? findings?.missing ?? false,
2916
- verdict: verify?.verdict ?? null, stamped, clearedStamp: cleared, verdictVoided: moved, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot,
2917
- },
2918
- usage: run.usage,
2919
- isError: failed,
2920
- };
2246
+ } catch (e) {
2247
+ crash = e instanceof Error ? e.message : String(e);
2921
2248
  } finally {
2922
- stageRuns.delete(key);
2923
- if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", undefined);
2924
- try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
2249
+ clearTimeout(timer);
2250
+ signal?.removeEventListener("abort", abortChild);
2251
+ unsub?.();
2252
+ runningWorkers.delete(key);
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");
2925
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 } };
2926
2275
  },
2927
2276
  });
2928
2277
  pi.registerTool(stageWorkerTool);
@@ -3019,9 +2368,7 @@ export default function devFlow(pi: ExtensionAPI) {
3019
2368
  // an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
3020
2369
  // the guards, the no-playbook bash-timeout default included
3021
2370
  if (noDf) return undefined;
3022
- // Everything below that reads flow truth reads it from here: in a feature worktree that is the main
3023
- // checkout (see flowRoot), which is what makes owner attribution — and the worker half of the
3024
- // implement guard — reachable for the session that was actually sent to do the work.
2371
+ // flow truth lives in the main checkout even when the session runs inside a feature worktree
3025
2372
  const guardRoot = await flowRoot(ctx.cwd);
3026
2373
  const cfg = loadProject(dfDir(guardRoot)).cfg;
3027
2374
  const mustStateTimeout = shellCmd !== "" && explicitTimeout === undefined && cfg.bashTimeout === "require";
@@ -3041,19 +2388,13 @@ export default function devFlow(pi: ExtensionAPI) {
3041
2388
  const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
3042
2389
  if (why) return { block: true, reason: why };
3043
2390
  }
3044
- // A registered worker session is the one allowed to write a normal feature's worktree at
3045
- // implement — that is what it was sent to do (see writeGuard's byWorker).
3046
- // repoRoot stays the session's own checkout: the scratch rule asks where the BYTES land, and a
3047
- // project that parks its worktrees outside the checkout (or under the temp dir) must not have
3048
- // those writes read as a throwaway because the flow truth was resolved elsewhere.
3049
- const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd, byWorker: isWorkerSession(ctx.sessionManager?.getSessionId?.()) });
2391
+ const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd });
3050
2392
  if (reason) return { block: true, reason };
3051
2393
  // Editing a worktree invalidates that feature's tier-1 checks and tier-2 confirmation until they rerun.
3052
2394
  const owner = feats.find((f) => f.worktreeAbs && abs.startsWith(f.worktreeAbs + path.sep));
3053
2395
  if (owner && (owner.state.stage === "implement" || owner.state.stage === "pre-release") && (Object.keys(owner.state.checks).length || owner.state.confirmations?.implement)) {
3054
2396
  owner.state.checks = {};
3055
2397
  delete owner.state.confirmations?.implement;
3056
- // the owner's state lives in the flow-truth root, not in the worktree's own .dev-flow/ copy
3057
2398
  writeState(guardRoot, owner.state);
3058
2399
  }
3059
2400
  return undefined;
@@ -3090,6 +2431,11 @@ export default function devFlow(pi: ExtensionAPI) {
3090
2431
  const why = await askOperator(ctx, command, mv.confirm);
3091
2432
  if (why) return { block: true, reason: why };
3092
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
+ }
3093
2439
  const inv = gitInvocation(command);
3094
2440
  if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
3095
2441
  const bound = boundFeature(guardRoot, key);
@@ -3132,6 +2478,11 @@ export default function devFlow(pi: ExtensionAPI) {
3132
2478
  }
3133
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` });
3134
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)` };
3135
2486
  // Branch discipline: feature branches live in their worktree — never checked out or created (-b) in the main checkout
3136
2487
  const target = checkoutTarget(g.seg);
3137
2488
  if (target && target.startsWith(featureBranchPrefix(cfg))) {
@@ -3157,10 +2508,7 @@ export default function devFlow(pi: ExtensionAPI) {
3157
2508
  // client attaches, and this is the earliest point the client is certainly listening
3158
2509
  refreshStatus(ctx);
3159
2510
  if (!initiated(ctx.cwd)) return undefined;
3160
- // A stage worker's whole instruction is its brief. The driver's context is wrong there twice over:
3161
- // the unbound posture tells it to pre-plan and `flow start`, and the branch check reads its
3162
- // worktree as a main checkout on the wrong branch. Guards still run — they hang off tool_call.
3163
- if (isWorkerSession(ctx.sessionManager?.getSessionId?.())) return undefined;
2511
+ try { if (workerSessions.has(ctx.sessionManager.getSessionId())) return undefined; } catch { /* not a worker */ }
3164
2512
  const key = sessionKey(ctx);
3165
2513
  // The playbook core rides along on the message this run writes anyway — once per session.
3166
2514
  const core = corePreamble(key);
@@ -3168,12 +2516,10 @@ export default function devFlow(pi: ExtensionAPI) {
3168
2516
  const state = boundFeature(ctx.cwd, key);
3169
2517
  if (!state || state.stage === "done") {
3170
2518
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
3171
- let content = "[dev-flow] no flow bound. Every request goes through flow. New work — pre-plan first (see the skill): analyze read-only, bring findings + questions + a direction with a proposed slug/mode to the operator, and flow start <slug> only once they say start; unfinished feature: flow use <slug>.";
2519
+ let content = "[dev-flow] no flow bound. Every request goes through flow. New work: flow start <slug>; unfinished feature: flow use <slug>.";
3172
2520
  const cb = claimBlocker(ctx.cwd, key);
3173
- if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (${claimWho(cb.claim)}) — flow use ${cb.state.slug} takes it over explicitly.`;
3174
- // only the main checkout has a "main checkout branch": a session opened in a linked worktree is
3175
- // on its feature branch by construction, and calling that a drift misleads it
3176
- const curBr = (await isLinkedWorktree(ctx.cwd)) ? "" : await currentBranch(ctx.cwd);
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);
3177
2523
  if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
3178
2524
  const refl0 = readReflections(ctx.cwd);
3179
2525
  if (refl0.length) content += ` Also: ${refl0.length} reflection(s) open — run flow doctor.`;