pi-dev-flow 0.68.1 → 0.70.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,11 +20,13 @@
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";
23
24
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
24
25
  import path from "node:path";
25
26
  import { promisify } from "node:util";
26
27
  import { Type } from "@earendil-works/pi-ai";
27
- import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
28
+ import { Container, Text } from "@earendil-works/pi-tui";
29
+ import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
28
30
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
29
31
  import {
30
32
  ALLOW_REWRITE,
@@ -36,6 +38,8 @@ import {
36
38
  buildStageBrief,
37
39
  checkFingerprint,
38
40
  changelogVersionsBetween,
41
+ familyFoldLine,
42
+ familyHeading,
39
43
  normalizeReleaseBody,
40
44
  pendingEntryLines,
41
45
  pickReleaseNotes,
@@ -109,11 +113,44 @@ import {
109
113
  roadmapTidy,
110
114
  shouldSelfCompact,
111
115
  shouldTakeOverCompaction,
112
- stageGuidance,
116
+ TRANSCRIPTS_FILE,
117
+ stageCardLines,
113
118
  stageElapsedLabel,
119
+ stageGuidance,
114
120
  stageInterruptSteer,
121
+ stageLiveAssistantLine,
115
122
  stageLiveLine,
123
+ stageLiveResultLine,
124
+ stageUsageLine,
116
125
  summarizeToolArgs,
126
+ VERIFY_STAMP,
127
+ VERIFY_STAMP_REFUSAL,
128
+ WORKER_OP_BUDGET_MIN,
129
+ WORKER_OP_GLYPH,
130
+ WORKER_OP_TOOLS,
131
+ type StageUsage,
132
+ type WorkerOp,
133
+ buildReflectBrief,
134
+ buildVerifyBrief,
135
+ isWorkerOp,
136
+ liveClip,
137
+ liveTail,
138
+ parseReflectFindings,
139
+ parseVerifyReport,
140
+ parseWorkerTranscripts,
141
+ planFingerprint,
142
+ recordVerifyPass,
143
+ renderVerifyReport,
144
+ verifyStampMissing,
145
+ sessionPathKey,
146
+ workerFamily,
147
+ workerFamilyCount,
148
+ WORKER_FAMILY_ITEMS,
149
+ workerOpError,
150
+ workerTranscriptLine,
151
+ type WorkerSessionRow,
152
+ workerName,
153
+ sanitizeWorkerLabel,
117
154
  stateTamper,
118
155
  statusFor,
119
156
  statusJson,
@@ -406,13 +443,27 @@ export const compactionTakeover: { run: typeof compact } = { run: compact };
406
443
 
407
444
  /** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
408
445
  * `.run` with a stub, so the worker contract stays testable without spending a model and tests
409
- * never touch the real session directory. The real spawn uses the DEFAULT session location (the
410
- * picker and `pi export` find it for free) and names the session through an inline extension —
411
- * `setSessionName` only exists on a session's own extension API — handing back a rename channel
412
- * the driver uses for the ⏳ → ✓/✗ lifecycle. */
446
+ * never touch the real session directory. The real spawn stamps lineage: the worker's header
447
+ * carries `parentSession` → the driver's own session file, and its transcript goes into the
448
+ * driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
449
+ * scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
450
+ * as /handoff can do the same"). Naming runs through an inline extension — `setSessionName` only
451
+ * exists on a session's own extension API — handing back a rename channel the driver uses for the
452
+ * ⏳ → ✓/✗ lifecycle. */
453
+
413
454
  export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
414
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string }) => Promise<StageWorkerHandle> } = {
415
- run: async ({ work, model, name }) => {
455
+
456
+ /** The worker's session manager, built exactly as the real seam builds it — split out so a test can
457
+ * drive the production composition (header link + driver's bucket) without spawning a model.
458
+ * Both or neither: `dir` is the driver's own bucket read off the live manager, so a custom
459
+ * PI_CODING_AGENT_DIR can never strand a worker in a different agent dir from its driver, and pi's
460
+ * private `--<encoded cwd>--` directory encoding is never duplicated here. */
461
+ export function workerSessionManager(work: string, parent?: string, dir?: string): SessionManager | undefined {
462
+ return parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
463
+ }
464
+
465
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
466
+ run: async ({ work, model, name, tools, parent, dir }) => {
416
467
  let rename: (name: string) => void = () => {};
417
468
  const loader = new DefaultResourceLoader({
418
469
  cwd: work,
@@ -427,19 +478,109 @@ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name:
427
478
  }],
428
479
  });
429
480
  await loader.reload();
430
- const { session } = await createAgentSession({ cwd: work, model: model as never, tools: ["read", "bash", "edit", "write"], excludeTools: ["flow", "flow_stage"], resourceLoader: loader });
431
- // coding tools only: what a worker cannot reach is a flow it cannot touch — the allowlist picks
432
- // the defaults, excludeTools is the belt on the extension tools (allowlist semantics for those are ambiguous)
481
+ const sessionManager = workerSessionManager(work, parent, dir);
482
+ const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
483
+ // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
484
+ // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
485
+ // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
433
486
  return { session, rename: (n) => rename(n) };
434
487
  },
435
488
  };
436
489
 
490
+ /** Seam that reads the driver's session bucket the way the picker does — a stub in the smoke suite,
491
+ * because a test must not scan the operator's real session directory. `listAll(dir)`, not
492
+ * `list(cwd, dir)`: pi's `list` drops rows whose header cwd is not `cwd` whenever it is handed a
493
+ * directory that is not that cwd's default — which is precisely a stage worker (header cwd = the
494
+ * worktree, file in the driver's bucket), and precisely the layout a configured `sessionDir`
495
+ * creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
496
+ * the family list and the tree agree there; under a configured session dir the text view stays
497
+ * complete even where that scope hides the worker, which is the cheaper direction to err in. */
498
+ export const sessionRowsScan: { run: (o: { cwd: string; dir?: string }) => Promise<WorkerSessionRow[]> } = {
499
+ run: async ({ dir }) => (await SessionManager.listAll(dir)).map((s) => ({ path: s.path, parent: s.parentSessionPath, name: s.name, messageCount: s.messageCount, modified: s.modified })),
500
+ };
501
+
502
+ /** Where this session's own transcripts live, when it has any: the file the worker links to, and the
503
+ * bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
504
+ * which is a fact to print, never an error to raise. */
505
+ function lineageOf(ctx: ExtensionContext): { file: string | null; dir: string | null } {
506
+ try {
507
+ return { file: ctx.sessionManager.getSessionFile() ?? null, dir: ctx.sessionManager.getSessionDir() ?? null };
508
+ } catch { /* an in-memory or otherwise unbacked session says so here */ return { file: null, dir: null }; }
509
+ }
510
+
511
+ /** With no file-backed lineage to read — an unbacked host, or a driver pi never wrote a file for —
512
+ * the ledger is what the flow knows: every worker it recorded, newest first. Coarser than the
513
+ * picker's data (no message count, no rename), so the status heading names the source. */
514
+ function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
515
+ try {
516
+ const drop = exclude ? sessionPathKey(exclude) : null;
517
+ const mine = parseWorkerTranscripts(readFileSync(logPath, "utf8")).filter((r) => !drop || sessionPathKey(r.path) !== drop);
518
+ const shown = mine.slice(-WORKER_FAMILY_ITEMS).reverse().map((r) => `${r.op} · ${r.at} · ${r.path}`);
519
+ return mine.length > shown.length ? [...shown, familyFoldLine(mine.length - shown.length)] : shown;
520
+ } catch { return []; }
521
+ }
522
+
523
+ /** Bucket reads are the one expensive thing the family view does: pi parses every transcript in the
524
+ * driver's bucket in full — measured here at ~15 ms per MB of bucket history (25 sessions / 10.4 MB
525
+ * ≈ 150–200 ms, 48 MB ≈ 1.3 s). A host renders a running worker by calling status repeatedly, so
526
+ * that path is allowed a slightly stale read; the places the operator draws a conclusion from — idle
527
+ * status, the settled card — always re-read. */
528
+ const BUCKET_FRESH_MS = 2000;
529
+ const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
530
+
531
+ async function bucketRows(ctx: ExtensionContext, dir: string | null, staleMs = 0) {
532
+ const key = dir ?? "(default bucket)";
533
+ const hit = bucketCache.get(key);
534
+ // staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
535
+ // and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
536
+ // condition also holds inside the caller's own millisecond, and a fast host got the previous read back
537
+ // as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
538
+ // as the call before it printed the family that had just gone empty).
539
+ if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
540
+ const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined });
541
+ if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
542
+ bucketCache.set(key, { at: Date.now(), rows });
543
+ return rows;
544
+ }
545
+
546
+ /** The flow's workers as lines, newest first — `null` when this session has no file to be a parent of,
547
+ * which is when the caller reaches for `ledgerFamilyLines` instead.
548
+ * Deliberately read from the picker's own data, not from a dev-flow index: renames, deletions and
549
+ * workers an older session already delegated all read back correctly for free. `exclude` drops one
550
+ * transcript: the caller already shows that run, and meeting it again as an anonymous row under
551
+ * "other workers" reads like somebody else's work belongs to this flow. */
552
+ async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleMs = 0): Promise<string[] | null> {
553
+ const { file, dir } = lineageOf(ctx);
554
+ if (!file) return null;
555
+ try {
556
+ return workerFamily(await bucketRows(ctx, dir, staleMs), file, { exclude });
557
+ } catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
558
+ }
559
+
437
560
  /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
438
561
  export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
439
562
 
563
+
440
564
  /** What a live worker run knows about itself — the one-worker-per-session guard and the ledger the
441
- * `op: "status"` verb reads. `lastLines` mirrors the live log (bounded). */
442
- interface StageRun { startedAt: number; budgetMin: number; softFired: boolean; work: string; lastLines: string[] }
565
+ * `op: "status"` verb reads. `lastLines` mirrors the live log (bounded); usage and turns accumulate
566
+ * per run so the card and the result can say what the worker cost. */
567
+ interface StageRun {
568
+ startedAt: number;
569
+ budgetMin: number;
570
+ softFired: boolean;
571
+ work: string;
572
+ lastLines: string[];
573
+ op: WorkerOp;
574
+ /** "🔨 implement" / "🔍 verify" (+ ` · label`) — how the card and the beats name the run; session names use workerName instead. */
575
+ kind: string;
576
+ slug: string;
577
+ usage: StageUsage;
578
+ turns: number;
579
+ /** the live worker's own session file, once spawned — a family listing leaves it out rather than
580
+ * meeting the run twice: once as the run, once as an unlabeled row under "other workers". */
581
+ transcript?: string;
582
+ }
583
+
443
584
  const stageRuns = new Map<string, StageRun>();
444
585
 
445
586
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
@@ -679,6 +820,26 @@ async function worktreeFingerprint(cwd: string): Promise<string | null> {
679
820
  return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
680
821
  }
681
822
 
823
+ /** The fingerprint a verify PASS belongs to: the worktree's, hashed TOGETHER WITH the feature's plan/
824
+ * dir — the checker read the plan too, so a mid-stage plan edit voids its verdict exactly like a code
825
+ * edit. null = git could not answer (same fingerprintless-stamp rule as tier-1 records). */
826
+ async function verifyStampFingerprint(root: string, st: FlowState): Promise<string | null> {
827
+ const base = await worktreeFingerprint(gateCwd(root, st));
828
+ if (!base) return null;
829
+ return createHash("sha256").update(`${base}\n${planFingerprint(path.join(root, ".dev-flow", st.slug, "plan"))}`).digest("hex").slice(0, 16);
830
+ }
831
+
832
+ /** Drop a PASS whose worktree-or-plan fingerprint no longer matches; true if one was dropped. Every
833
+ * reader of the stamp (the verify gate, and the check/status views that must not keep advertising a
834
+ * dead PASS) runs this before trusting the record. */
835
+ async function voidStaleVerifyStamp(root: string, st: FlowState): Promise<boolean> {
836
+ if (!st.checks[VERIFY_STAMP]) return false;
837
+ const vfp = await verifyStampFingerprint(root, st);
838
+ if (!vfp || st.checks[VERIFY_STAMP]!.wt === vfp) return false;
839
+ delete st.checks[VERIFY_STAMP];
840
+ return true;
841
+ }
842
+
682
843
  /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
683
844
  * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
684
845
  async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
@@ -964,8 +1125,21 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
964
1125
  // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
965
1126
  // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
966
1127
  // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
967
- const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
968
- if (staleAtGate.length) writeState(root, state!);
1128
+ const fpAtGate = await worktreeFingerprint(gateCwd(root, state!));
1129
+ const staleAtGate = freshenChecks(state!, fpAtGate, (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1130
+ // The stamp is judged by its own wider fingerprint (see verifyStampFingerprint): a change to the
1131
+ // plan the verdict was written against demotes it exactly like a worktree change would.
1132
+ const stampVoided = await voidStaleVerifyStamp(root, state!);
1133
+ if (staleAtGate.length || stampVoided) writeState(root, state!);
1134
+ // An independent checker has to have looked at THIS tree before the operator is asked to approve it:
1135
+ // the verify worker's PASS is a precondition of the gate, refused before any command runs so a long
1136
+ // suite is never spent on a run that cannot pass. The stamp lives in state.checks, so a worktree edit
1137
+ // or a moved fingerprint drops it exactly like a tier-1 record — one fresh verify worker per change,
1138
+ // precise friction rather than a sticky lock. docs mode is exempt (nothing there to check).
1139
+ if (verifyStampMissing(state!)) {
1140
+ writeState(root, state!);
1141
+ 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 };
1142
+ }
969
1143
  const pending = pendingChecks(state!, cfg);
970
1144
  const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
971
1145
  if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
@@ -981,6 +1155,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
981
1155
  // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
982
1156
  did.push("docs mode: project commands skipped (build/dev/health)");
983
1157
  } else {
1158
+ did.push(`verify worker PASS over this tree (${state!.checks[VERIFY_STAMP]?.at ?? "recorded"})`);
984
1159
  if (cfg.commands.build) {
985
1160
  const res = await sh(cfg.commands.build, gateCwd(root, state!));
986
1161
  state!.checks.build = { ok: res.ok, at: now() };
@@ -1121,6 +1296,8 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1121
1296
  const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1122
1297
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1123
1298
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1299
+ // a PASS whose worktree-or-plan moved is dead here too — no gate may act on a verdict it cannot prove current
1300
+ if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1124
1301
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1125
1302
  const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1126
1303
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
@@ -1740,13 +1917,23 @@ async function gateStatus(o: GateCtx): Promise<RunResult> {
1740
1917
  const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
1741
1918
  const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
1742
1919
  const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
1920
+ // status (and --json, which feeds worker briefs) must never advertise a PASS the gates would refuse:
1921
+ // reap dead stamps in the copies being rendered — and persist only THIS session's own feature, since
1922
+ // a foreign state.json belongs to its own session (a listing must not write another session's file).
1923
+ const states = new Map<string, FlowState>();
1924
+ for (const s of slugs) {
1925
+ const stV = readState(root, s);
1926
+ if (!stV) continue;
1927
+ if (await voidStaleVerifyStamp(root, stV) && s === sess.slug) writeState(root, stV);
1928
+ states.set(s, stV);
1929
+ }
1743
1930
  if (flag("json")) {
1744
- const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
1931
+ const sts = slugs.map((s) => states.get(s)).filter((s): s is FlowState => s !== undefined);
1745
1932
  return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
1746
1933
  }
1747
1934
  if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
1748
1935
  const lines = slugs.flatMap((s) => {
1749
- const st = readState(root, s);
1936
+ const st = states.get(s);
1750
1937
  if (!st) return [];
1751
1938
  return [
1752
1939
  `${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}` : ""}`,
@@ -1923,6 +2110,7 @@ async function gateCheck(o: GateCtx): Promise<RunResult> {
1923
2110
  // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
1924
2111
  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)" };
1925
2112
  if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
2113
+ if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1926
2114
  const ran = await runChecks(root, state!, cfg, cfg.checkList);
1927
2115
  return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
1928
2116
  }
@@ -2151,99 +2339,238 @@ export default function devFlow(pi: ExtensionAPI) {
2151
2339
  });
2152
2340
  pi.registerTool(flowTool);
2153
2341
 
2154
- // ---- stage worker (flow_stage): a stage's heavy work in a disposable sub-session ----------
2342
+ /** The text a worker's finished tool call carried (first text part, else an error string) — the live
2343
+ * ✓/✗ line is built from it, so a worker that gets an error back shows it, not just the tool name. */
2344
+ function resultText(result: unknown): string {
2345
+ const r = result as { content?: unknown; text?: string; errorMessage?: string } | undefined;
2346
+ const parts = Array.isArray(r?.content) ? (r!.content as { type?: string; text?: string }[]) : [];
2347
+ return parts.find((p) => p?.type === "text")?.text ?? r?.text ?? r?.errorMessage ?? "";
2348
+ }
2349
+
2350
+ /** The assistant prose of a worker turn — text parts only, thinking and tool calls have their own lines. */
2351
+ function assistantText(content: unknown): string {
2352
+ if (typeof content === "string") return content;
2353
+ if (!Array.isArray(content)) return "";
2354
+ return (content as { type?: string; text?: string }[]).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n");
2355
+ }
2356
+
2357
+ /** Last non-empty line: the end of a tool dump is the verdict-bearing part ("251 pass", "exit 1",
2358
+ * the error), its head is almost never the news. */
2359
+ function lastLineOf(text: string): string {
2360
+ return (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
2361
+ }
2362
+
2363
+ // ---- stage worker (flow_stage): one stage's work, its check and its review in a disposable sub-session --
2155
2364
  // The child stays UNBOUND on purpose: writeGuard attributes worktree writes to the owning
2156
- // feature's stage and bashFlowGuard stops only default-branch git ops, so an unbound worker may
2157
- // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and
2158
- // the parent holds the live claim) — and its tool list holds no flow tool at all. The claim,
2159
- // every gate and every checkpoint stay with the driving session; the worker owes one report.
2365
+ // feature's stage and bashFlowGuard stops only default-branch git ops, so an implement worker may
2366
+ // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and the
2367
+ // parent holds the live claim) — and its tool list holds no flow tool at all. The claim, every gate
2368
+ // and every checkpoint stay with the driving session; the worker owes one report.
2369
+ // Three ops share this one mechanism on purpose: `run` (a stage's work), `verify` (an independent
2370
+ // read-only checker whose PASS the verify gate demands) and `reflect` (an independent review of the
2371
+ // whole finished flow). Only the brief, the toolset, the budget default and the closing contract
2372
+ // differ — the unbound-worker safety story is identical, and a second mechanism would drift.
2160
2373
  const stageWorkerTool = defineTool({
2161
2374
  name: "flow_stage",
2162
2375
  label: "Stage worker",
2163
2376
  description:
2164
- "Delegate the current stage's heavy work to a disposable dev-flow worker session with a fresh context (implement | pre-release). 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. The worker edits and commits in the worktree but cannot run gates or talk to the operator; it appears as a live named session (pi export renders it). At 75% of its budget (budgetMin, default 45) the worker is steered to commit and report instead of being cut. While it runs, flow_stage with op \"status\" answers how the worker is doing. When it returns: read its stage report, run flow check yourself, then ask the checkpoint — the report is a handoff, not a verification.",
2165
- promptSnippet: 'flow_stage(stage: "implement"|"pre-release", note, budgetMin?) — do the stage\'s work in a fresh worker session; op: "status" reads the live run; gates and checkpoints stay with you',
2377
+ '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 `⏳ 🔍 · <label>` while running and `✓ 🔍 · <label> · PASS` (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.',
2378
+ promptSnippet:
2379
+ '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',
2166
2380
  parameters: Type.Object({
2167
- op: Type.Optional(Type.String({ description: '"run" (default) delegates the stage work; "status" reports the live worker run in this session' })),
2168
- stage: Type.Optional(Type.String({ description: "Stage to delegate the work for — must match the bound feature's current stage" })),
2381
+ 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' })),
2382
+ 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.' })),
2169
2383
  note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
2170
- budgetMin: Type.Optional(Type.Number({ description: "Worker budget in minutes (5-120, default 45). At 75% the worker is steered to commit and report; past the budget it is interrupted and the tree snapshotted." })),
2384
+ 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." })),
2385
+ 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.' })),
2171
2386
  }),
2387
+ // The card is the guaranteed worker-visibility surface: it renders inside the driver's own
2388
+ // transcript, in TUI and in pi-web alike, because every line also travels as the update's text.
2389
+ renderCall: (args, theme) => {
2390
+ const op = String(args.op ?? "run");
2391
+ const what = op === "run" ? `run ${args.stage ?? "?"}` : op;
2392
+ return new Text(theme.fg("toolTitle", `flow_stage ${what}`) + (args.note ? ` ${theme.fg("muted", liveClip(String(args.note), 70))}` : ""), 0, 0);
2393
+ },
2394
+ renderResult: (result, options, theme) => {
2395
+ const d = result.details as { card?: string[]; cardFull?: string[]; verdict?: string | null } | undefined;
2396
+ const lines = (options.expanded ? d?.cardFull ?? d?.card : d?.card) ?? [];
2397
+ if (!lines.length) return new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n") || "(no output)", 0, 0);
2398
+ const box = new Container();
2399
+ for (const line of lines) {
2400
+ const text = options.expanded ? line : liveClip(line, 120);
2401
+ 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));
2402
+ }
2403
+ if (options.expanded) {
2404
+ box.addChild(new Text(theme.fg("dim", "─── report ───"), 0, 0));
2405
+ box.addChild(new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n"), 0, 0));
2406
+ }
2407
+ return box;
2408
+ },
2172
2409
  execute: async (_id, params, signal, onUpdate, ctx) => {
2173
2410
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2174
- if (String(params.op ?? "run") === "status") {
2411
+ const opRaw = String(params.op ?? "run").trim().toLowerCase();
2412
+ 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)`);
2413
+ const op: WorkerOp = opRaw;
2414
+ if (op === "status") {
2175
2415
  const run = stageRuns.get(sessionKey(ctx));
2176
- if (!run) return { content: [{ type: "text", text: "no stage worker is running in this session" }], details: { running: false } };
2416
+ // The family is the question op:"status" gets when nothing is running — "what has this flow
2417
+ // spawned, and how did each end?". pi's picker threads the same rows into a tree; this is
2418
+ // that fact for a host with no tree, and for the moment between runs. A worker that is live
2419
+ // right now is the section above, not one of "the others" — so it is left out here. The whole
2420
+ // section is gated on a bound feature: an unbound session has never spawned a stage worker,
2421
+ // so there it would be noise paid for with a directory scan.
2422
+ const boundState = (() => { try { return initiated(ctx.cwd) ? boundFeature(ctx.cwd, sessionKey(ctx)) : null; } catch { return null; } })();
2423
+ const inFlow = !!boundState;
2424
+ const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
2425
+ // the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
2426
+ const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), "stage-sessions", TRANSCRIPTS_FILE), run?.transcript) : null);
2427
+ const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
2428
+ if (!run) {
2429
+ return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
2430
+ }
2177
2431
  const elapsed = Date.now() - run.startedAt;
2178
2432
  const dirtyNow = await sh("git status --porcelain", run.work);
2179
2433
  const logNow = await sh("git log --oneline -5", run.work);
2180
2434
  const text = [
2181
2435
  `stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
2182
- ...run.lastLines.slice(-10),
2436
+ ...liveTail(run.lastLines),
2437
+ stageUsageLine(run.usage, run.turns),
2183
2438
  `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2184
2439
  `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2440
+ ...(inFlow ? ["", ...familySection] : []),
2185
2441
  ].join("\n");
2186
- return { content: [{ type: "text", text }], details: { running: true, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired } };
2442
+ 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) } };
2187
2443
  }
2188
- const stageArg = String(params.stage ?? "");
2189
- 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)`);
2190
2444
  if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2191
2445
  const st = boundFeature(ctx.cwd, sessionKey(ctx));
2192
2446
  if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2193
- 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`);
2447
+ const stageArg = String(params.stage ?? "");
2448
+ if (op === "run") {
2449
+ 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)`);
2450
+ 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`);
2451
+ } else {
2452
+ const why = workerOpError(op, st);
2453
+ if (why) return err(why);
2454
+ 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`);
2455
+ }
2194
2456
  const key = sessionKey(ctx);
2195
2457
  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`);
2196
- const budgetMin = clampStageBudgetMin(params.budgetMin);
2458
+ const budgetMin = clampStageBudgetMin(params.budgetMin ?? WORKER_OP_BUDGET_MIN[op]);
2197
2459
  const budgetMs = budgetMin * 60_000;
2198
2460
  const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
2199
2461
  const hardMs = stageTimingOverride.hardMs ?? budgetMs;
2200
- const run: StageRun = { startedAt: Date.now(), budgetMin, softFired: false, work: gateCwd(ctx.cwd, st), lastLines: [] };
2462
+ const glyph = WORKER_OP_GLYPH[op];
2463
+ const label = typeof params.label === "string" ? sanitizeWorkerLabel(params.label) : "";
2464
+ // the card/beats keep the descriptive kind (the card line has no other stage context); the
2465
+ // session NAMES are compact — glyph, ordinal, purpose (see workerName)
2466
+ const kind = op === "run" ? `${glyph} ${st.stage}` : `${glyph} ${op}`;
2467
+ const kindCard = label ? `${kind} · ${label}` : kind;
2468
+ const work = gateCwd(ctx.cwd, st);
2469
+ const run: StageRun = {
2470
+ startedAt: Date.now(), budgetMin, softFired: false, work, lastLines: [],
2471
+ 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,
2472
+ };
2201
2473
  stageRuns.set(key, run);
2202
- const work = run.work;
2474
+ const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2203
2475
  const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2476
+ const transcriptLog = path.join(featDir(ctx.cwd, st.slug), "stage-sessions", TRANSCRIPTS_FILE);
2477
+ // read once, used twice: the worker's header links to this file and lands in this bucket,
2478
+ // and the reflect brief names this session's own transcript to the reviewer
2479
+ const lineage = lineageOf(ctx);
2204
2480
  let child: AgentSession | undefined;
2205
2481
  let crash: string | null = null;
2206
2482
  let timedOut = false;
2207
- const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
2483
+ /** The card frame for this instant — one place so the streamed text, the TUI card and
2484
+ * op:"status" can never disagree about what the worker is doing. */
2485
+ const cardView = (state: "running" | "done" | "failed", extra: { verdict?: "pass" | "fail" | null; transcript?: string } = {}) =>
2486
+ 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 });
2487
+ const emit = (event: string, data: Record<string, unknown>) => {
2488
+ try { pi.events.emit(event, { slug: st.slug, op, stage: st.stage, ...data }); } catch { /* the bus is visibility, never function */ }
2489
+ };
2208
2490
  try {
2209
- writeFileSync(logFile, `${stageLiveLine(0, "worker", `started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2210
- const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ stage worker ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName} · ${st.slug}`); };
2491
+ writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2492
+ const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2493
+ // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2494
+ // read #2, #3 in the list instead of identical rows (only run gets a seq; a verify is known
2495
+ // by its verdict, a reflect is one per flow)
2496
+ const seq = op === "run" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2211
2497
  const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2212
2498
  const git = await sh("git status --porcelain -b", work);
2213
- const refRel = stageReference(st.stage);
2214
- let refText = "";
2215
- if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2216
- const brief = buildStageBrief({
2217
- slug: st.slug,
2218
- stage: st.stage as DelegableStage,
2219
- workDir: work,
2220
- planFile: path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md"),
2221
- referenceText: refText,
2222
- statusJson: statusJsonText,
2223
- gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2224
- note: typeof params.note === "string" ? params.note : undefined,
2225
- });
2499
+ const note = typeof params.note === "string" ? params.note : undefined;
2500
+ const planFile = path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md");
2501
+ let brief: string;
2502
+ if (op === "verify") {
2503
+ // the reviewer reads the full diff itself; the stat is only the shape of what it is in for
2504
+ const stat = await sh(`git diff --shortstat ${sq(`origin/${cfg.defaultBranch}`)}...HEAD 2>/dev/null || git diff --shortstat ${sq(cfg.defaultBranch)}...HEAD`, work);
2505
+ const tier1 = [...cfg.checkList];
2506
+ if (cfg.commands.test && !tier1.some((c) => c.name === "test")) tier1.push({ name: "test", cmd: cfg.commands.test });
2507
+ brief = buildVerifyBrief({
2508
+ slug: st.slug, workDir: work, planFile, statusJson: statusJsonText,
2509
+ gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2510
+ diffStat: stat.ok ? stat.out.trim() : "(no diff stat)",
2511
+ defaultBranch: cfg.defaultBranch, checks: tier1, note,
2512
+ });
2513
+ } else if (op === "reflect") {
2514
+ const transcripts = existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")) : [];
2515
+ brief = buildReflectBrief({
2516
+ slug: st.slug, planFile, statusJson: statusJsonText, driverSession: lineage.file, transcripts,
2517
+ openReflections: readReflections(ctx.cwd).map((r) => r.line), note,
2518
+ });
2519
+ } else {
2520
+ const refRel = stageReference(st.stage);
2521
+ let refText = "";
2522
+ if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2523
+ 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 });
2524
+ }
2525
+ // the tree identity a verify verdict belongs to, before anything runs: the same comparison
2526
+ // the tier-1 fingerprint makes, done here because a reviewer must not be the one who edited.
2527
+ // HEAD is captured too: a reviewer that commits or moves a ref leaves `git status` clean while
2528
+ // reading a different tree, so a porcelain-only diff would stamp a PASS for a HEAD it never saw.
2529
+ const statusBefore = await sh("git status --porcelain", work);
2530
+ const headBefore = await sh("git rev-parse HEAD", work);
2531
+ const refBefore = await sh("git symbolic-ref -q HEAD || true", work);
2532
+ // the plan is an input the reviewer reads from OUTSIDE the worktree — it belongs in the
2533
+ // before/after proof too, or a reviewer could rewrite the ground it is judging mid-run
2534
+ const planDir = path.join(ctx.cwd, ".dev-flow", st.slug, "plan");
2535
+ const planBefore = planFingerprint(planDir);
2226
2536
  // the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
2227
- // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2228
- // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2229
- const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ stage worker · ${st.stage} · ${st.slug}` });
2230
- child = worker.session;
2537
+ // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2538
+ // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2539
+ 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 });
2540
+ child = worker.session;
2541
+ try { run.transcript = child.sessionManager.getSessionFile() ?? undefined; } catch { /* the family listing just won't know which row is this run */ }
2542
+ emit("dev-flow:worker-started", { budgetMin, startedAt: new Date().toISOString() });
2231
2543
  let lastBeat = 0;
2544
+ /** One live line: ledger, durable log, and the streamed card — same text on every host. */
2545
+ const pushLine = (line: string) => {
2546
+ if (!line) return;
2547
+ run.lastLines.push(line);
2548
+ if (run.lastLines.length > 50) run.lastLines.shift();
2549
+ try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2550
+ const card = cardView("running");
2551
+ 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) } });
2552
+ };
2232
2553
  const unsub = child.subscribe((ev: unknown) => {
2233
- const e = ev as { type?: string; toolName?: string; args?: unknown; message?: { role?: string; usage?: Record<string, number> & { cost?: Record<string, number> } } };
2554
+ 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> } } };
2555
+ const elapsed = () => Date.now() - run.startedAt;
2234
2556
  if (e.type === "tool_execution_start") {
2235
- const line = stageLiveLine(Date.now() - run.startedAt, e.toolName ?? "?", summarizeToolArgs(e.args));
2236
- run.lastLines.push(line);
2237
- if (run.lastLines.length > 50) run.lastLines.shift();
2238
- try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2239
- onUpdate?.({ content: [{ type: "text", text: `stage worker ${stageElapsedLabel(Date.now() - run.startedAt)} · ${e.toolName ?? "?"}` }], details: undefined });
2557
+ pushLine(stageLiveLine(elapsed(), e.toolName ?? "?", summarizeToolArgs(e.args)));
2240
2558
  const now = Date.now();
2241
2559
  if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
2242
2560
  }
2243
- if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
2561
+ if (e.type === "tool_execution_end") {
2562
+ // the last line of the result is the verdict-bearing one ("251 pass", "exit 1",
2563
+ // the error) — the head of a tool dump is almost never the news
2564
+ pushLine(stageLiveResultLine(elapsed(), e.toolName ?? "?", !e.isError, lastLineOf(resultText(e.result))));
2565
+ }
2566
+ if (e.type === "message_end" && e.message?.role === "assistant") {
2567
+ run.turns++;
2244
2568
  const u = e.message.usage;
2245
- for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) usage[f] += Number(u[f] ?? 0);
2246
- if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) usage.cost[f] += Number(u.cost[f] ?? 0);
2569
+ if (u) {
2570
+ for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) run.usage[f] += Number(u[f] ?? 0);
2571
+ if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) run.usage.cost[f] += Number(u.cost[f] ?? 0);
2572
+ }
2573
+ pushLine(stageLiveAssistantLine(elapsed(), assistantText(e.message.content)));
2247
2574
  }
2248
2575
  });
2249
2576
  const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
@@ -2265,9 +2592,45 @@ export default function devFlow(pi: ExtensionAPI) {
2265
2592
  unsub();
2266
2593
  }
2267
2594
  const clean = !crash && !timedOut;
2268
- worker.rename(`${clean ? "✓" : "✗"} stage worker · ${st.stage} · ${st.slug}`);
2269
2595
  const transcript = child.sessionManager.getSessionFile() ?? "";
2270
- const report = parseStageReport(child.getLastAssistantText() ?? "");
2596
+ // the durable worker index: until now a transcript path lived only in this call's result,
2597
+ // i.e. only as long as the driver kept it in context — the reflect worker needs the list
2598
+ if (transcript) {
2599
+ try {
2600
+ mkdirSync(path.dirname(transcriptLog), { recursive: true });
2601
+ appendFileSync(transcriptLog, `${workerTranscriptLine(now(), op, transcript)}\n`);
2602
+ } catch { /* an index that failed to append is never a reason to lose the run */ }
2603
+ }
2604
+ const report = op === "run" ? parseStageReport(child.getLastAssistantText() ?? "") : null;
2605
+ const verify = op === "verify" ? parseVerifyReport(child.getLastAssistantText() ?? "") : null;
2606
+ const findings = op === "reflect" ? parseReflectFindings(child.getLastAssistantText() ?? "") : null;
2607
+ // A check-only worker must leave the tree exactly as it found it: the verdict is a claim
2608
+ // about THIS tree, so a reviewer that touched anything voids its own report. Computed before
2609
+ // the rename and the stamp so both readers agree on one verdict of "did the ground move".
2610
+ // (The gate's own uncommitted-path policy stays unchanged — a tree already dirty is not the
2611
+ // worker's fault; only movement counts.)
2612
+ const statusAfter = await sh("git status --porcelain", work);
2613
+ const headAfter = await sh("git rev-parse HEAD", work);
2614
+ const refAfter = await sh("git symbolic-ref -q HEAD || true", work);
2615
+ // four legs, because each alone has a clean-tree bypass: porcelain misses ref moves,
2616
+ // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2617
+ // and all three miss the plan the verdict was written against living outside the worktree
2618
+ 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);
2619
+ // the outcome goes INTO the final name — a picker row like `✓ 🔍 · PASS · stamp attack` or
2620
+ // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2621
+ let outcome: string | null = null;
2622
+ if (clean) {
2623
+ if (op === "run" && headBefore.ok) {
2624
+ const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
2625
+ const n = c.ok ? c.out.trim() : "0";
2626
+ if (n !== "0") outcome = `${n} commit${n === "1" ? "" : "s"}`;
2627
+ }
2628
+ if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
2629
+ if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
2630
+ } else {
2631
+ outcome = timedOut ? "hard-cut" : "crashed";
2632
+ }
2633
+ worker.rename(workerName(clean ? "✓" : "✗", glyph, seq, label, outcome));
2271
2634
  // never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
2272
2635
  // via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
2273
2636
  let snapshot: string | null = null;
@@ -2276,26 +2639,84 @@ export default function devFlow(pi: ExtensionAPI) {
2276
2639
  const snapDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
2277
2640
  mkdirSync(snapDir, { recursive: true });
2278
2641
  const stamp = Date.now();
2279
- const diffFile = path.join(snapDir, `${st.stage}-${stamp}.diff`);
2642
+ const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
2280
2643
  const idx = path.join(snapDir, `.snap-index-${stamp}`);
2281
2644
  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);
2282
2645
  if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
2283
2646
  }
2284
- // the worker dirtied tier-1 records through the same hooks any edit dirties them — the
2285
- // driving session re-greens after the stage: the check runs on its binding, verdict rides along.
2286
- const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
2287
- const parts = [renderStageReport(report)];
2647
+ // An implement worker dirtied tier-1 records through the same hooks any edit dirties them, so
2648
+ // the check reruns here: it runs on the driver's binding and its verdict rides along in the
2649
+ // digest. A check-only op touched nothing (proved below), so its records still stand — and
2650
+ // re-running a whole suite here would spend it twice and hide the gate's own re-run.
2651
+ const check = op === "run" ? await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx)) : null;
2652
+ // the PASS is stamped AFTER the rerun so it belongs to the settled tree, and only over a tree
2653
+ // the reviewer actually left untouched — this stamp is what flow verify demands at the gate
2654
+ let stamped = false;
2655
+ let cleared = false;
2656
+ if (verify?.verdict === "pass" && clean && !moved) {
2657
+ const fresh = readState(ctx.cwd, st.slug);
2658
+ if (fresh) {
2659
+ recordVerifyPass(fresh, now(), await verifyStampFingerprint(ctx.cwd, fresh));
2660
+ writeState(ctx.cwd, fresh);
2661
+ stamped = true;
2662
+ }
2663
+ } else if (verify?.verdict === "fail" && !moved) {
2664
+ // a FAIL over an unmoved tree contradicts any earlier PASS — the gate may not ask
2665
+ // Verified? against a tree its newest checker rejected
2666
+ const fresh = readState(ctx.cwd, st.slug);
2667
+ if (fresh?.checks[VERIFY_STAMP]) {
2668
+ delete fresh.checks[VERIFY_STAMP];
2669
+ writeState(ctx.cwd, fresh);
2670
+ cleared = true;
2671
+ }
2672
+ }
2673
+ const parts: string[] = [];
2674
+ if (report) parts.push(renderStageReport(report));
2675
+ if (verify) {
2676
+ parts.push(renderVerifyReport(verify));
2677
+ 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).`);
2678
+ 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.");
2679
+ 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}` : ""}`);
2680
+ else if (!clean) parts.push("no verdict recorded from a crashed or interrupted run — rerun the verify worker.");
2681
+ 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)" : ""}.`);
2682
+ }
2683
+ if (findings) {
2684
+ 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, "```");
2685
+ else {
2686
+ parts.push(
2687
+ `playbook findings (${findings.playbook.length}):`, ...(findings.playbook.length ? findings.playbook.map((x) => `[playbook] ${x}`) : ["- none"]),
2688
+ `plugin findings (${findings.plugin.length}):`, ...(findings.plugin.length ? findings.plugin.map((x) => `[plugin] ${x}`) : ["- none"]),
2689
+ ...(findings.other.length ? ["other:", ...findings.other.map((x) => `[neither] ${x}`)] : []),
2690
+ "put the findings to the operator (Fold? Fix? Drop?) — queue what they fold with flow reflect --playbook|--plugin; the worker queued nothing.",
2691
+ );
2692
+ }
2693
+ }
2288
2694
  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"}`);
2289
2695
  if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
2290
2696
  if (crash) parts.push(`worker run ended with an error: ${crash}`);
2291
- if (snapshot) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2292
- parts.push(`tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}`);
2293
- parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}`);
2697
+ if (snapshot && !verify) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2698
+ 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.");
2699
+ 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)` : ""}`);
2700
+ const failed = !!crash || timedOut || moved;
2701
+ // the family belongs on the settled card and the result only: a live frame redraws on every
2702
+ // worker tool call, and reading a session bucket is IO. This run is excluded — the card names
2703
+ // its transcript already, and repeating it as a bare row reads like a different worker.
2704
+ const famFromPicker = await workerFamilyLines(ctx, transcript || undefined);
2705
+ const fam = famFromPicker ?? ledgerFamilyLines(transcriptLog, transcript || undefined);
2706
+ emit(failed ? "dev-flow:worker-failed" : "dev-flow:worker-completed", {
2707
+ elapsedMs: Date.now() - run.startedAt, usage: run.usage, turns: run.turns, budgetMin, softFired: run.softFired, timedOut, crash,
2708
+ verdict: verify?.verdict ?? null, reportMissing: report?.missing ?? findings?.missing ?? false, transcript, snapshot,
2709
+ });
2710
+ const card = cardView(failed ? "failed" : "done", { verdict: verify?.verdict ?? null, transcript });
2294
2711
  return {
2295
2712
  content: [{ type: "text" as const, text: parts.join("\n\n") }],
2296
- details: { slug: st.slug, stage: st.stage, done: report.done, files: report.files, notes: report.notes, blockers: report.blockers, reportMissing: report.missing, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot },
2297
- usage,
2298
- isError: !!crash || timedOut,
2713
+ details: {
2714
+ 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),
2715
+ done: report?.done, files: report?.files, notes: report?.notes, blockers: report?.blockers, reportMissing: report?.missing ?? findings?.missing ?? false,
2716
+ verdict: verify?.verdict ?? null, stamped, clearedStamp: cleared, verdictVoided: moved, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot,
2717
+ },
2718
+ usage: run.usage,
2719
+ isError: failed,
2299
2720
  };
2300
2721
  } finally {
2301
2722
  stageRuns.delete(key);
@@ -2533,7 +2954,7 @@ export default function devFlow(pi: ExtensionAPI) {
2533
2954
  const state = boundFeature(ctx.cwd, key);
2534
2955
  if (!state || state.stage === "done") {
2535
2956
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
2536
- let content = "[dev-flow] no flow bound. Every request goes through flow. New work: flow start <slug>; unfinished feature: flow use <slug>.";
2957
+ 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>.";
2537
2958
  const cb = claimBlocker(ctx.cwd, key);
2538
2959
  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.`;
2539
2960
  const curBr = await currentBranch(ctx.cwd);