pi-dev-flow 0.68.0 → 0.69.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,10 +20,12 @@
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";
28
+ import { Container, Text } from "@earendil-works/pi-tui";
27
29
  import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, 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 {
@@ -109,11 +111,39 @@ import {
109
111
  roadmapTidy,
110
112
  shouldSelfCompact,
111
113
  shouldTakeOverCompaction,
112
- stageGuidance,
114
+ TRANSCRIPTS_FILE,
115
+ stageCardLines,
113
116
  stageElapsedLabel,
117
+ stageGuidance,
114
118
  stageInterruptSteer,
119
+ stageLiveAssistantLine,
115
120
  stageLiveLine,
121
+ stageLiveResultLine,
122
+ stageUsageLine,
116
123
  summarizeToolArgs,
124
+ VERIFY_STAMP,
125
+ VERIFY_STAMP_REFUSAL,
126
+ WORKER_OP_BUDGET_MIN,
127
+ WORKER_OP_GLYPH,
128
+ WORKER_OP_TOOLS,
129
+ type StageUsage,
130
+ type WorkerOp,
131
+ buildReflectBrief,
132
+ buildVerifyBrief,
133
+ isWorkerOp,
134
+ liveClip,
135
+ liveTail,
136
+ parseReflectFindings,
137
+ parseVerifyReport,
138
+ parseWorkerTranscripts,
139
+ planFingerprint,
140
+ recordVerifyPass,
141
+ renderVerifyReport,
142
+ verifyStampMissing,
143
+ workerOpError,
144
+ workerTranscriptLine,
145
+ workerName,
146
+ sanitizeWorkerLabel,
117
147
  stateTamper,
118
148
  statusFor,
119
149
  statusJson,
@@ -410,9 +440,10 @@ export const compactionTakeover: { run: typeof compact } = { run: compact };
410
440
  * picker and `pi export` find it for free) and names the session through an inline extension —
411
441
  * `setSessionName` only exists on a session's own extension API — handing back a rename channel
412
442
  * the driver uses for the ⏳ → ✓/✗ lifecycle. */
443
+
413
444
  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 }) => {
445
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[] }) => Promise<StageWorkerHandle> } = {
446
+ run: async ({ work, model, name, tools }) => {
416
447
  let rename: (name: string) => void = () => {};
417
448
  const loader = new DefaultResourceLoader({
418
449
  cwd: work,
@@ -427,9 +458,10 @@ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name:
427
458
  }],
428
459
  });
429
460
  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)
461
+ const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader });
462
+ // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
463
+ // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
464
+ // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
433
465
  return { session, rename: (n) => rename(n) };
434
466
  },
435
467
  };
@@ -437,9 +469,24 @@ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name:
437
469
  /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
438
470
  export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
439
471
 
472
+
440
473
  /** 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[] }
474
+ * `op: "status"` verb reads. `lastLines` mirrors the live log (bounded); usage and turns accumulate
475
+ * per run so the card and the result can say what the worker cost. */
476
+ interface StageRun {
477
+ startedAt: number;
478
+ budgetMin: number;
479
+ softFired: boolean;
480
+ work: string;
481
+ lastLines: string[];
482
+ op: WorkerOp;
483
+ /** "🔨 implement" / "🔍 verify" (+ ` · label`) — how the card and the beats name the run; session names use workerName instead. */
484
+ kind: string;
485
+ slug: string;
486
+ usage: StageUsage;
487
+ turns: number;
488
+ }
489
+
443
490
  const stageRuns = new Map<string, StageRun>();
444
491
 
445
492
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
@@ -597,7 +644,9 @@ async function gitConsistency(root: string, cfg: Config): Promise<string[]> {
597
644
  for (const b of brRaw.out.split("\n").map((x) => x.replace(/^[*+]?\s+/, "").trim()).filter(Boolean)) {
598
645
  if (!ownedBr.has(b)) out.push(`orphan branch ${b} — no unfinished feature owns it (git branch -D ${b})`);
599
646
  }
600
- for (const f of feats) if (f.worktree && !existsSync(path.resolve(root, f.worktree))) out.push(`feature ${f.slug} (${f.stage}) has no worktree at ${f.worktree}`);
647
+ // an aborted feature is a designed state, not drift: the abort echo tells the operator to remove
648
+ // the worktree by hand, and the stamp keeps that cleanup from being re-reported forever (gh#138)
649
+ for (const f of feats) if (f.worktree && !f.aborted && !existsSync(path.resolve(root, f.worktree))) out.push(`feature ${f.slug} (${f.stage}) has no worktree at ${f.worktree}`);
601
650
  // the playbook belongs in git — an untracked project.md is invisible to teammates and lost on machine changes
602
651
  if (existsSync(path.join(root, ".dev-flow", "project.md")) && !(await sh("git ls-files --error-unmatch -- .dev-flow/project.md", root)).ok)
603
652
  out.push('.dev-flow/project.md is not tracked in git — track it: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force: a root .gitignore may exclude .dev-flow/ wholesale; the env prefix is for the installed hook — dev-flow allows a main commit whose only change is the playbook)');
@@ -677,6 +726,26 @@ async function worktreeFingerprint(cwd: string): Promise<string | null> {
677
726
  return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
678
727
  }
679
728
 
729
+ /** The fingerprint a verify PASS belongs to: the worktree's, hashed TOGETHER WITH the feature's plan/
730
+ * dir — the checker read the plan too, so a mid-stage plan edit voids its verdict exactly like a code
731
+ * edit. null = git could not answer (same fingerprintless-stamp rule as tier-1 records). */
732
+ async function verifyStampFingerprint(root: string, st: FlowState): Promise<string | null> {
733
+ const base = await worktreeFingerprint(gateCwd(root, st));
734
+ if (!base) return null;
735
+ return createHash("sha256").update(`${base}\n${planFingerprint(path.join(root, ".dev-flow", st.slug, "plan"))}`).digest("hex").slice(0, 16);
736
+ }
737
+
738
+ /** Drop a PASS whose worktree-or-plan fingerprint no longer matches; true if one was dropped. Every
739
+ * reader of the stamp (the verify gate, and the check/status views that must not keep advertising a
740
+ * dead PASS) runs this before trusting the record. */
741
+ async function voidStaleVerifyStamp(root: string, st: FlowState): Promise<boolean> {
742
+ if (!st.checks[VERIFY_STAMP]) return false;
743
+ const vfp = await verifyStampFingerprint(root, st);
744
+ if (!vfp || st.checks[VERIFY_STAMP]!.wt === vfp) return false;
745
+ delete st.checks[VERIFY_STAMP];
746
+ return true;
747
+ }
748
+
680
749
  /** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
681
750
  * that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
682
751
  async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
@@ -962,8 +1031,21 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
962
1031
  // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
963
1032
  // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
964
1033
  // tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
965
- const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
966
- if (staleAtGate.length) writeState(root, state!);
1034
+ const fpAtGate = await worktreeFingerprint(gateCwd(root, state!));
1035
+ const staleAtGate = freshenChecks(state!, fpAtGate, (n) => n === "health" && healthRerunsAfterDeploy(cfg));
1036
+ // The stamp is judged by its own wider fingerprint (see verifyStampFingerprint): a change to the
1037
+ // plan the verdict was written against demotes it exactly like a worktree change would.
1038
+ const stampVoided = await voidStaleVerifyStamp(root, state!);
1039
+ if (staleAtGate.length || stampVoided) writeState(root, state!);
1040
+ // An independent checker has to have looked at THIS tree before the operator is asked to approve it:
1041
+ // the verify worker's PASS is a precondition of the gate, refused before any command runs so a long
1042
+ // suite is never spent on a run that cannot pass. The stamp lives in state.checks, so a worktree edit
1043
+ // or a moved fingerprint drops it exactly like a tier-1 record — one fresh verify worker per change,
1044
+ // precise friction rather than a sticky lock. docs mode is exempt (nothing there to check).
1045
+ if (verifyStampMissing(state!)) {
1046
+ writeState(root, state!);
1047
+ 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 };
1048
+ }
967
1049
  const pending = pendingChecks(state!, cfg);
968
1050
  const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
969
1051
  if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
@@ -979,6 +1061,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
979
1061
  // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
980
1062
  did.push("docs mode: project commands skipped (build/dev/health)");
981
1063
  } else {
1064
+ did.push(`verify worker PASS over this tree (${state!.checks[VERIFY_STAMP]?.at ?? "recorded"})`);
982
1065
  if (cfg.commands.build) {
983
1066
  const res = await sh(cfg.commands.build, gateCwd(root, state!));
984
1067
  state!.checks.build = { ok: res.ok, at: now() };
@@ -1068,6 +1151,15 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1068
1151
  if (yoloWord) return { text: yoloWord, isError: true };
1069
1152
  // prep evidence is read from the worktree: the bump and changelog entry exist on the branch before the PR merges
1070
1153
  const wtCwd = gateCwd(root, state!);
1154
+ // gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix
1155
+ // that never ships. verify shows the operator uncommitted paths; release proves them away. A git
1156
+ // that cannot answer is a measurement failure, never a refusal — same stance as the merge-base probes.
1157
+ const dirtyWt = await sh("git status --porcelain", wtCwd);
1158
+ if (dirtyWt.ok && dirtyWt.out.trim()) {
1159
+ const n = dirtyWt.out.split("\n").filter((l) => l.trim()).length;
1160
+ return { text: `release gate FAILED:\n- ${n} uncommitted path(s) in ${state!.worktree} — a merge ships the branch, not your working tree: commit or discard them, then re-run\n${tail(dirtyWt.out)}`, isError: true };
1161
+ }
1162
+ const branchProof = await branchState(wtCwd, cfg.defaultBranch);
1071
1163
  const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
1072
1164
  ? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
1073
1165
  : null;
@@ -1110,6 +1202,8 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1110
1202
  const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1111
1203
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1112
1204
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1205
+ // a PASS whose worktree-or-plan moved is dead here too — no gate may act on a verdict it cannot prove current
1206
+ if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1113
1207
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
1114
1208
  const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
1115
1209
  if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
@@ -1166,7 +1260,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1166
1260
  if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1167
1261
  clearPendingAsk(state!);
1168
1262
  writeState(root, state!);
1169
- return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${nextHint(state!, cfg)}` };
1263
+ return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
1170
1264
  }
1171
1265
 
1172
1266
  async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
@@ -1368,7 +1462,8 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1368
1462
  const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
1369
1463
  const unmerged = await sh(`git -C ${sq(wt)} log origin/${cfg.defaultBranch}..HEAD --oneline 2>/dev/null || git -C ${sq(wt)} log ${cfg.defaultBranch}..HEAD --oneline`, root);
1370
1464
  const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
1371
- if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}`, isError: true };
1465
+ // the refusal names the paths, not just the count — same proof verify and release print (gh#131)
1466
+ if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}${status.out.trim() ? `:\n${tail(status.out)}` : ""}`, isError: true };
1372
1467
  if (assess.unmerged.length) {
1373
1468
  const policy = cfg.release.merge;
1374
1469
  // "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
@@ -1728,13 +1823,23 @@ async function gateStatus(o: GateCtx): Promise<RunResult> {
1728
1823
  const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
1729
1824
  const slugs = slugArg ? [slugArg] : existsSync(df) ? (await listDirs(df)).filter((s) => readState(root, s)) : [];
1730
1825
  const cur = sess.slug; // only a bound session has a current feature — the lone-unfinished hint would pose unbound sessions as owning it
1826
+ // status (and --json, which feeds worker briefs) must never advertise a PASS the gates would refuse:
1827
+ // reap dead stamps in the copies being rendered — and persist only THIS session's own feature, since
1828
+ // a foreign state.json belongs to its own session (a listing must not write another session's file).
1829
+ const states = new Map<string, FlowState>();
1830
+ for (const s of slugs) {
1831
+ const stV = readState(root, s);
1832
+ if (!stV) continue;
1833
+ if (await voidStaleVerifyStamp(root, stV) && s === sess.slug) writeState(root, stV);
1834
+ states.set(s, stV);
1835
+ }
1731
1836
  if (flag("json")) {
1732
- const sts = slugs.map((s) => readState(root, s)).filter((s): s is FlowState => s !== null);
1837
+ const sts = slugs.map((s) => states.get(s)).filter((s): s is FlowState => s !== undefined);
1733
1838
  return { text: statusJson(sts, cur, cfg) }; // before the prose "no features" answer — an orchestrator must be able to parse the empty case too
1734
1839
  }
1735
1840
  if (!slugs.length) return { text: ["no features — start one: flow start <slug> [--ui] [--patch|--docs --confirmed]", ...warn, ...rmapLine].join("\n") };
1736
1841
  const lines = slugs.flatMap((s) => {
1737
- const st = readState(root, s);
1842
+ const st = states.get(s);
1738
1843
  if (!st) return [];
1739
1844
  return [
1740
1845
  `${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}` : ""}`,
@@ -1911,6 +2016,7 @@ async function gateCheck(o: GateCtx): Promise<RunResult> {
1911
2016
  // flow now gets no test run at all; the mechanical fix is a diff-scope guard at verify if it ever bites
1912
2017
  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)" };
1913
2018
  if (!cfg.checkList.length) return { text: 'no tier-1 checks configured — add ```flow blocks / flow-check blocks to ## implement in project.md', isError: true };
2019
+ if (await voidStaleVerifyStamp(root, state!)) writeState(root, state!);
1914
2020
  const ran = await runChecks(root, state!, cfg, cfg.checkList);
1915
2021
  return { text: `tier-1 checks:\n${ran.lines.join("\n")}`, isError: ran.failed };
1916
2022
  }
@@ -1965,7 +2071,8 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
1965
2071
  rmSync(featDir(root, target), { recursive: true, force: true });
1966
2072
  return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
1967
2073
  }
1968
- return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
2074
+ if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
2075
+ return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
1969
2076
  }
1970
2077
 
1971
2078
 
@@ -2138,27 +2245,79 @@ export default function devFlow(pi: ExtensionAPI) {
2138
2245
  });
2139
2246
  pi.registerTool(flowTool);
2140
2247
 
2141
- // ---- stage worker (flow_stage): a stage's heavy work in a disposable sub-session ----------
2248
+ /** The text a worker's finished tool call carried (first text part, else an error string) — the live
2249
+ * ✓/✗ line is built from it, so a worker that gets an error back shows it, not just the tool name. */
2250
+ function resultText(result: unknown): string {
2251
+ const r = result as { content?: unknown; text?: string; errorMessage?: string } | undefined;
2252
+ const parts = Array.isArray(r?.content) ? (r!.content as { type?: string; text?: string }[]) : [];
2253
+ return parts.find((p) => p?.type === "text")?.text ?? r?.text ?? r?.errorMessage ?? "";
2254
+ }
2255
+
2256
+ /** The assistant prose of a worker turn — text parts only, thinking and tool calls have their own lines. */
2257
+ function assistantText(content: unknown): string {
2258
+ if (typeof content === "string") return content;
2259
+ if (!Array.isArray(content)) return "";
2260
+ return (content as { type?: string; text?: string }[]).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n");
2261
+ }
2262
+
2263
+ /** Last non-empty line: the end of a tool dump is the verdict-bearing part ("251 pass", "exit 1",
2264
+ * the error), its head is almost never the news. */
2265
+ function lastLineOf(text: string): string {
2266
+ return (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
2267
+ }
2268
+
2269
+ // ---- stage worker (flow_stage): one stage's work, its check and its review in a disposable sub-session --
2142
2270
  // The child stays UNBOUND on purpose: writeGuard attributes worktree writes to the owning
2143
- // feature's stage and bashFlowGuard stops only default-branch git ops, so an unbound worker may
2144
- // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and
2145
- // the parent holds the live claim) — and its tool list holds no flow tool at all. The claim,
2146
- // every gate and every checkpoint stay with the driving session; the worker owes one report.
2271
+ // feature's stage and bashFlowGuard stops only default-branch git ops, so an implement worker may
2272
+ // edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and the
2273
+ // parent holds the live claim) — and its tool list holds no flow tool at all. The claim, every gate
2274
+ // and every checkpoint stay with the driving session; the worker owes one report.
2275
+ // Three ops share this one mechanism on purpose: `run` (a stage's work), `verify` (an independent
2276
+ // read-only checker whose PASS the verify gate demands) and `reflect` (an independent review of the
2277
+ // whole finished flow). Only the brief, the toolset, the budget default and the closing contract
2278
+ // differ — the unbound-worker safety story is identical, and a second mechanism would drift.
2147
2279
  const stageWorkerTool = defineTool({
2148
2280
  name: "flow_stage",
2149
2281
  label: "Stage worker",
2150
2282
  description:
2151
- "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.",
2152
- 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',
2283
+ '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.',
2284
+ promptSnippet:
2285
+ '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',
2153
2286
  parameters: Type.Object({
2154
- op: Type.Optional(Type.String({ description: '"run" (default) delegates the stage work; "status" reports the live worker run in this session' })),
2155
- stage: Type.Optional(Type.String({ description: "Stage to delegate the work for — must match the bound feature's current stage" })),
2287
+ 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' })),
2288
+ 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.' })),
2156
2289
  note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
2157
- 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." })),
2290
+ 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." })),
2291
+ 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.' })),
2158
2292
  }),
2293
+ // The card is the guaranteed worker-visibility surface: it renders inside the driver's own
2294
+ // transcript, in TUI and in pi-web alike, because every line also travels as the update's text.
2295
+ renderCall: (args, theme) => {
2296
+ const op = String(args.op ?? "run");
2297
+ const what = op === "run" ? `run ${args.stage ?? "?"}` : op;
2298
+ return new Text(theme.fg("toolTitle", `flow_stage ${what}`) + (args.note ? ` ${theme.fg("muted", liveClip(String(args.note), 70))}` : ""), 0, 0);
2299
+ },
2300
+ renderResult: (result, options, theme) => {
2301
+ const d = result.details as { card?: string[]; cardFull?: string[]; verdict?: string | null } | undefined;
2302
+ const lines = (options.expanded ? d?.cardFull ?? d?.card : d?.card) ?? [];
2303
+ if (!lines.length) return new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n") || "(no output)", 0, 0);
2304
+ const box = new Container();
2305
+ for (const line of lines) {
2306
+ const text = options.expanded ? line : liveClip(line, 120);
2307
+ 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));
2308
+ }
2309
+ if (options.expanded) {
2310
+ box.addChild(new Text(theme.fg("dim", "─── report ───"), 0, 0));
2311
+ box.addChild(new Text((result.content ?? []).map((c) => ("text" in c ? c.text : "")).join("\n"), 0, 0));
2312
+ }
2313
+ return box;
2314
+ },
2159
2315
  execute: async (_id, params, signal, onUpdate, ctx) => {
2160
2316
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2161
- if (String(params.op ?? "run") === "status") {
2317
+ const opRaw = String(params.op ?? "run").trim().toLowerCase();
2318
+ 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)`);
2319
+ const op: WorkerOp = opRaw;
2320
+ if (op === "status") {
2162
2321
  const run = stageRuns.get(sessionKey(ctx));
2163
2322
  if (!run) return { content: [{ type: "text", text: "no stage worker is running in this session" }], details: { running: false } };
2164
2323
  const elapsed = Date.now() - run.startedAt;
@@ -2166,71 +2325,141 @@ export default function devFlow(pi: ExtensionAPI) {
2166
2325
  const logNow = await sh("git log --oneline -5", run.work);
2167
2326
  const text = [
2168
2327
  `stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
2169
- ...run.lastLines.slice(-10),
2328
+ ...liveTail(run.lastLines),
2329
+ stageUsageLine(run.usage, run.turns),
2170
2330
  `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2171
2331
  `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2172
2332
  ].join("\n");
2173
- return { content: [{ type: "text", text }], details: { running: true, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired } };
2333
+ 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 } };
2174
2334
  }
2175
- const stageArg = String(params.stage ?? "");
2176
- 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)`);
2177
2335
  if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2178
2336
  const st = boundFeature(ctx.cwd, sessionKey(ctx));
2179
2337
  if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2180
- 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`);
2338
+ const stageArg = String(params.stage ?? "");
2339
+ if (op === "run") {
2340
+ 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)`);
2341
+ 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`);
2342
+ } else {
2343
+ const why = workerOpError(op, st);
2344
+ if (why) return err(why);
2345
+ 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`);
2346
+ }
2181
2347
  const key = sessionKey(ctx);
2182
2348
  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`);
2183
- const budgetMin = clampStageBudgetMin(params.budgetMin);
2349
+ const budgetMin = clampStageBudgetMin(params.budgetMin ?? WORKER_OP_BUDGET_MIN[op]);
2184
2350
  const budgetMs = budgetMin * 60_000;
2185
2351
  const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
2186
2352
  const hardMs = stageTimingOverride.hardMs ?? budgetMs;
2187
- const run: StageRun = { startedAt: Date.now(), budgetMin, softFired: false, work: gateCwd(ctx.cwd, st), lastLines: [] };
2353
+ const glyph = WORKER_OP_GLYPH[op];
2354
+ const label = typeof params.label === "string" ? sanitizeWorkerLabel(params.label) : "";
2355
+ // the card/beats keep the descriptive kind (the card line has no other stage context); the
2356
+ // session NAMES are compact — glyph, ordinal, purpose (see workerName)
2357
+ const kind = op === "run" ? `${glyph} ${st.stage}` : `${glyph} ${op}`;
2358
+ const kindCard = label ? `${kind} · ${label}` : kind;
2359
+ const work = gateCwd(ctx.cwd, st);
2360
+ const run: StageRun = {
2361
+ startedAt: Date.now(), budgetMin, softFired: false, work, lastLines: [],
2362
+ 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,
2363
+ };
2188
2364
  stageRuns.set(key, run);
2189
- const work = run.work;
2365
+ const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2190
2366
  const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2367
+ const transcriptLog = path.join(featDir(ctx.cwd, st.slug), "stage-sessions", TRANSCRIPTS_FILE);
2191
2368
  let child: AgentSession | undefined;
2192
2369
  let crash: string | null = null;
2193
2370
  let timedOut = false;
2194
- const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
2371
+ /** The card frame for this instant — one place so the streamed text, the TUI card and
2372
+ * op:"status" can never disagree about what the worker is doing. */
2373
+ const cardView = (state: "running" | "done" | "failed", extra: { verdict?: "pass" | "fail" | null; transcript?: string } = {}) =>
2374
+ 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 });
2375
+ const emit = (event: string, data: Record<string, unknown>) => {
2376
+ try { pi.events.emit(event, { slug: st.slug, op, stage: st.stage, ...data }); } catch { /* the bus is visibility, never function */ }
2377
+ };
2195
2378
  try {
2196
- writeFileSync(logFile, `${stageLiveLine(0, "worker", `started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2197
- const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ stage worker ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName} · ${st.slug}`); };
2379
+ writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2380
+ const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2381
+ // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2382
+ // read #2, #3 in the list instead of identical rows (only run gets a seq; a verify is known
2383
+ // by its verdict, a reflect is one per flow)
2384
+ const seq = op === "run" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2198
2385
  const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2199
2386
  const git = await sh("git status --porcelain -b", work);
2200
- const refRel = stageReference(st.stage);
2201
- let refText = "";
2202
- if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2203
- const brief = buildStageBrief({
2204
- slug: st.slug,
2205
- stage: st.stage as DelegableStage,
2206
- workDir: work,
2207
- planFile: path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md"),
2208
- referenceText: refText,
2209
- statusJson: statusJsonText,
2210
- gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2211
- note: typeof params.note === "string" ? params.note : undefined,
2212
- });
2387
+ const note = typeof params.note === "string" ? params.note : undefined;
2388
+ const planFile = path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md");
2389
+ let brief: string;
2390
+ if (op === "verify") {
2391
+ // the reviewer reads the full diff itself; the stat is only the shape of what it is in for
2392
+ const stat = await sh(`git diff --shortstat ${sq(`origin/${cfg.defaultBranch}`)}...HEAD 2>/dev/null || git diff --shortstat ${sq(cfg.defaultBranch)}...HEAD`, work);
2393
+ const tier1 = [...cfg.checkList];
2394
+ if (cfg.commands.test && !tier1.some((c) => c.name === "test")) tier1.push({ name: "test", cmd: cfg.commands.test });
2395
+ brief = buildVerifyBrief({
2396
+ slug: st.slug, workDir: work, planFile, statusJson: statusJsonText,
2397
+ gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2398
+ diffStat: stat.ok ? stat.out.trim() : "(no diff stat)",
2399
+ defaultBranch: cfg.defaultBranch, checks: tier1, note,
2400
+ });
2401
+ } else if (op === "reflect") {
2402
+ const transcripts = existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")) : [];
2403
+ let driverSession: string | null = null;
2404
+ try { driverSession = ctx.sessionManager.getSessionFile() ?? null; } catch { /* a host without a file-backed session says so in the brief */ }
2405
+ brief = buildReflectBrief({
2406
+ slug: st.slug, planFile, statusJson: statusJsonText, driverSession, transcripts,
2407
+ openReflections: readReflections(ctx.cwd).map((r) => r.line), note,
2408
+ });
2409
+ } else {
2410
+ const refRel = stageReference(st.stage);
2411
+ let refText = "";
2412
+ if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
2413
+ 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 });
2414
+ }
2415
+ // the tree identity a verify verdict belongs to, before anything runs: the same comparison
2416
+ // the tier-1 fingerprint makes, done here because a reviewer must not be the one who edited.
2417
+ // HEAD is captured too: a reviewer that commits or moves a ref leaves `git status` clean while
2418
+ // reading a different tree, so a porcelain-only diff would stamp a PASS for a HEAD it never saw.
2419
+ const statusBefore = await sh("git status --porcelain", work);
2420
+ const headBefore = await sh("git rev-parse HEAD", work);
2421
+ const refBefore = await sh("git symbolic-ref -q HEAD || true", work);
2422
+ // the plan is an input the reviewer reads from OUTSIDE the worktree — it belongs in the
2423
+ // before/after proof too, or a reviewer could rewrite the ground it is judging mid-run
2424
+ const planDir = path.join(ctx.cwd, ".dev-flow", st.slug, "plan");
2425
+ const planBefore = planFingerprint(planDir);
2213
2426
  // the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
2214
- // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2215
- // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2216
- const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ stage worker · ${st.stage} · ${st.slug}` });
2217
- child = worker.session;
2427
+ // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2428
+ // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2429
+ const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: workerName("⏳", glyph, seq, label), tools: [...WORKER_OP_TOOLS[op]] });
2430
+ child = worker.session;
2431
+ emit("dev-flow:worker-started", { budgetMin, startedAt: new Date().toISOString() });
2218
2432
  let lastBeat = 0;
2433
+ /** One live line: ledger, durable log, and the streamed card — same text on every host. */
2434
+ const pushLine = (line: string) => {
2435
+ if (!line) return;
2436
+ run.lastLines.push(line);
2437
+ if (run.lastLines.length > 50) run.lastLines.shift();
2438
+ try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2439
+ const card = cardView("running");
2440
+ 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) } });
2441
+ };
2219
2442
  const unsub = child.subscribe((ev: unknown) => {
2220
- const e = ev as { type?: string; toolName?: string; args?: unknown; message?: { role?: string; usage?: Record<string, number> & { cost?: Record<string, number> } } };
2443
+ 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> } } };
2444
+ const elapsed = () => Date.now() - run.startedAt;
2221
2445
  if (e.type === "tool_execution_start") {
2222
- const line = stageLiveLine(Date.now() - run.startedAt, e.toolName ?? "?", summarizeToolArgs(e.args));
2223
- run.lastLines.push(line);
2224
- if (run.lastLines.length > 50) run.lastLines.shift();
2225
- try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
2226
- onUpdate?.({ content: [{ type: "text", text: `stage worker ${stageElapsedLabel(Date.now() - run.startedAt)} · ${e.toolName ?? "?"}` }], details: undefined });
2446
+ pushLine(stageLiveLine(elapsed(), e.toolName ?? "?", summarizeToolArgs(e.args)));
2227
2447
  const now = Date.now();
2228
2448
  if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
2229
2449
  }
2230
- if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
2450
+ if (e.type === "tool_execution_end") {
2451
+ // the last line of the result is the verdict-bearing one ("251 pass", "exit 1",
2452
+ // the error) — the head of a tool dump is almost never the news
2453
+ pushLine(stageLiveResultLine(elapsed(), e.toolName ?? "?", !e.isError, lastLineOf(resultText(e.result))));
2454
+ }
2455
+ if (e.type === "message_end" && e.message?.role === "assistant") {
2456
+ run.turns++;
2231
2457
  const u = e.message.usage;
2232
- for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) usage[f] += Number(u[f] ?? 0);
2233
- if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) usage.cost[f] += Number(u.cost[f] ?? 0);
2458
+ if (u) {
2459
+ for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) run.usage[f] += Number(u[f] ?? 0);
2460
+ if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) run.usage.cost[f] += Number(u.cost[f] ?? 0);
2461
+ }
2462
+ pushLine(stageLiveAssistantLine(elapsed(), assistantText(e.message.content)));
2234
2463
  }
2235
2464
  });
2236
2465
  const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
@@ -2252,9 +2481,45 @@ export default function devFlow(pi: ExtensionAPI) {
2252
2481
  unsub();
2253
2482
  }
2254
2483
  const clean = !crash && !timedOut;
2255
- worker.rename(`${clean ? "✓" : "✗"} stage worker · ${st.stage} · ${st.slug}`);
2256
2484
  const transcript = child.sessionManager.getSessionFile() ?? "";
2257
- const report = parseStageReport(child.getLastAssistantText() ?? "");
2485
+ // the durable worker index: until now a transcript path lived only in this call's result,
2486
+ // i.e. only as long as the driver kept it in context — the reflect worker needs the list
2487
+ if (transcript) {
2488
+ try {
2489
+ mkdirSync(path.dirname(transcriptLog), { recursive: true });
2490
+ appendFileSync(transcriptLog, `${workerTranscriptLine(now(), op, transcript)}\n`);
2491
+ } catch { /* an index that failed to append is never a reason to lose the run */ }
2492
+ }
2493
+ const report = op === "run" ? parseStageReport(child.getLastAssistantText() ?? "") : null;
2494
+ const verify = op === "verify" ? parseVerifyReport(child.getLastAssistantText() ?? "") : null;
2495
+ const findings = op === "reflect" ? parseReflectFindings(child.getLastAssistantText() ?? "") : null;
2496
+ // A check-only worker must leave the tree exactly as it found it: the verdict is a claim
2497
+ // about THIS tree, so a reviewer that touched anything voids its own report. Computed before
2498
+ // the rename and the stamp so both readers agree on one verdict of "did the ground move".
2499
+ // (The gate's own uncommitted-path policy stays unchanged — a tree already dirty is not the
2500
+ // worker's fault; only movement counts.)
2501
+ const statusAfter = await sh("git status --porcelain", work);
2502
+ const headAfter = await sh("git rev-parse HEAD", work);
2503
+ const refAfter = await sh("git symbolic-ref -q HEAD || true", work);
2504
+ // four legs, because each alone has a clean-tree bypass: porcelain misses ref moves,
2505
+ // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2506
+ // and all three miss the plan the verdict was written against living outside the worktree
2507
+ 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);
2508
+ // the outcome goes INTO the final name — a picker row like `✓ 🔍 · PASS · stamp attack` or
2509
+ // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2510
+ let outcome: string | null = null;
2511
+ if (clean) {
2512
+ if (op === "run" && headBefore.ok) {
2513
+ const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
2514
+ const n = c.ok ? c.out.trim() : "0";
2515
+ if (n !== "0") outcome = `${n} commit${n === "1" ? "" : "s"}`;
2516
+ }
2517
+ if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
2518
+ if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
2519
+ } else {
2520
+ outcome = timedOut ? "hard-cut" : "crashed";
2521
+ }
2522
+ worker.rename(workerName(clean ? "✓" : "✗", glyph, seq, label, outcome));
2258
2523
  // never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
2259
2524
  // via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
2260
2525
  let snapshot: string | null = null;
@@ -2263,26 +2528,79 @@ export default function devFlow(pi: ExtensionAPI) {
2263
2528
  const snapDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
2264
2529
  mkdirSync(snapDir, { recursive: true });
2265
2530
  const stamp = Date.now();
2266
- const diffFile = path.join(snapDir, `${st.stage}-${stamp}.diff`);
2531
+ const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
2267
2532
  const idx = path.join(snapDir, `.snap-index-${stamp}`);
2268
2533
  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);
2269
2534
  if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
2270
2535
  }
2271
- // the worker dirtied tier-1 records through the same hooks any edit dirties them — the
2272
- // driving session re-greens after the stage: the check runs on its binding, verdict rides along.
2273
- const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
2274
- const parts = [renderStageReport(report)];
2536
+ // An implement worker dirtied tier-1 records through the same hooks any edit dirties them, so
2537
+ // the check reruns here: it runs on the driver's binding and its verdict rides along in the
2538
+ // digest. A check-only op touched nothing (proved below), so its records still stand — and
2539
+ // re-running a whole suite here would spend it twice and hide the gate's own re-run.
2540
+ const check = op === "run" ? await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx)) : null;
2541
+ // the PASS is stamped AFTER the rerun so it belongs to the settled tree, and only over a tree
2542
+ // the reviewer actually left untouched — this stamp is what flow verify demands at the gate
2543
+ let stamped = false;
2544
+ let cleared = false;
2545
+ if (verify?.verdict === "pass" && clean && !moved) {
2546
+ const fresh = readState(ctx.cwd, st.slug);
2547
+ if (fresh) {
2548
+ recordVerifyPass(fresh, now(), await verifyStampFingerprint(ctx.cwd, fresh));
2549
+ writeState(ctx.cwd, fresh);
2550
+ stamped = true;
2551
+ }
2552
+ } else if (verify?.verdict === "fail" && !moved) {
2553
+ // a FAIL over an unmoved tree contradicts any earlier PASS — the gate may not ask
2554
+ // Verified? against a tree its newest checker rejected
2555
+ const fresh = readState(ctx.cwd, st.slug);
2556
+ if (fresh?.checks[VERIFY_STAMP]) {
2557
+ delete fresh.checks[VERIFY_STAMP];
2558
+ writeState(ctx.cwd, fresh);
2559
+ cleared = true;
2560
+ }
2561
+ }
2562
+ const parts: string[] = [];
2563
+ if (report) parts.push(renderStageReport(report));
2564
+ if (verify) {
2565
+ parts.push(renderVerifyReport(verify));
2566
+ 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).`);
2567
+ 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.");
2568
+ 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}` : ""}`);
2569
+ else if (!clean) parts.push("no verdict recorded from a crashed or interrupted run — rerun the verify worker.");
2570
+ 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)" : ""}.`);
2571
+ }
2572
+ if (findings) {
2573
+ 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, "```");
2574
+ else {
2575
+ parts.push(
2576
+ `playbook findings (${findings.playbook.length}):`, ...(findings.playbook.length ? findings.playbook.map((x) => `[playbook] ${x}`) : ["- none"]),
2577
+ `plugin findings (${findings.plugin.length}):`, ...(findings.plugin.length ? findings.plugin.map((x) => `[plugin] ${x}`) : ["- none"]),
2578
+ ...(findings.other.length ? ["other:", ...findings.other.map((x) => `[neither] ${x}`)] : []),
2579
+ "put the findings to the operator (Fold? Fix? Drop?) — queue what they fold with flow reflect --playbook|--plugin; the worker queued nothing.",
2580
+ );
2581
+ }
2582
+ }
2275
2583
  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"}`);
2276
2584
  if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
2277
2585
  if (crash) parts.push(`worker run ended with an error: ${crash}`);
2278
- if (snapshot) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2279
- parts.push(`tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}`);
2280
- parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}`);
2586
+ if (snapshot && !verify) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2587
+ 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.");
2588
+ parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}\nindexed in: ${transcriptLog}`);
2589
+ const failed = !!crash || timedOut || moved;
2590
+ emit(failed ? "dev-flow:worker-failed" : "dev-flow:worker-completed", {
2591
+ elapsedMs: Date.now() - run.startedAt, usage: run.usage, turns: run.turns, budgetMin, softFired: run.softFired, timedOut, crash,
2592
+ verdict: verify?.verdict ?? null, reportMissing: report?.missing ?? findings?.missing ?? false, transcript, snapshot,
2593
+ });
2594
+ const card = cardView(failed ? "failed" : "done", { verdict: verify?.verdict ?? null, transcript });
2281
2595
  return {
2282
2596
  content: [{ type: "text" as const, text: parts.join("\n\n") }],
2283
- 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 },
2284
- usage,
2285
- isError: !!crash || timedOut,
2597
+ details: {
2598
+ 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 }, true),
2599
+ done: report?.done, files: report?.files, notes: report?.notes, blockers: report?.blockers, reportMissing: report?.missing ?? findings?.missing ?? false,
2600
+ verdict: verify?.verdict ?? null, stamped, clearedStamp: cleared, verdictVoided: moved, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot,
2601
+ },
2602
+ usage: run.usage,
2603
+ isError: failed,
2286
2604
  };
2287
2605
  } finally {
2288
2606
  stageRuns.delete(key);
@@ -2520,7 +2838,7 @@ export default function devFlow(pi: ExtensionAPI) {
2520
2838
  const state = boundFeature(ctx.cwd, key);
2521
2839
  if (!state || state.stage === "done") {
2522
2840
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
2523
- let content = "[dev-flow] no flow bound. Every request goes through flow. New work: flow start <slug>; unfinished feature: flow use <slug>.";
2841
+ 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>.";
2524
2842
  const cb = claimBlocker(ctx.cwd, key);
2525
2843
  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.`;
2526
2844
  const curBr = await currentBranch(ctx.cwd);