pi-dev-flow 0.67.0 → 0.68.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,11 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.68.0] - 2026-10-28
8
+
9
+ - **`flow_stage` workers are visible while they run — and they land on their feet (gh#142).** The 45 minutes of silence followed by a mid-edit cliff are gone. The worker is now a real, named pi session — `⏳ stage worker · implement · <slug>` in pi's standard session dir, shown live in the pi/pi-web picker, renamed `✓`/`✗` when it ends; the result names the transcript and its `pi export` command, so no raw-JSONL archaeology remains. The driving session's footer beats `⏳ mm:ss · <tool> · <slug>` while the worker runs, every worker tool call appends one line to `.dev-flow/<slug>/stage-live.log`, and `flow_stage { op: "status" }` answers elapsed, budget, live tail, worktree state and recent commits with no model call — the floor for headless hosts. The budget is per-call (`budgetMin`, 5–120, default 45), and at 75% of it the worker is no longer killed but **steered to a soft landing**: finish the edit in hand, commit everything done (a `wip(stage):` commit is expected), close with the STAGE REPORT — the hard cut is only the backstop for a worker that ignores the steer. Whatever the exit, a dirty worktree is never handed back: it is snapshotted (tracked *and* untracked, via a throwaway index — no WIP commit on the branch) to a `.diff` the result names. The brief now mandates a commit per completed unit, so a cut costs one unit, never a worktree.
10
+
11
+
7
12
  ## [0.67.0] - 2026-10-27
8
13
 
9
14
  - **`flow_stage`: a heavy stage's work runs in a disposable worker session.** A big implement no longer spends the driving session's whole context: `flow_stage` spawns a fresh coding-tools-only sub-session that reads the plan, works the worktree and commits, then returns one bounded `STAGE REPORT` (done / files / notes / blockers). The worker never holds the flow — gates, checkpoint answers and the claim stay with the driving session, which reruns tier-1 checks after the worker and still faces the normal verify gate. A worker that skips the report block or crashes is surfaced, not trusted; every worker transcript persists under `.dev-flow/<slug>/stage-sessions/` for audit. See [docs/stage-agent.md](docs/stage-agent.md).
@@ -22,8 +22,9 @@ the stage you are in. Everything else stays with the driving session:
22
22
  the normal `verify` gate.
23
23
 
24
24
  `plan` is the operator dialogue and `release`/`finish` carry the checkpoint
25
- words — both stay in-session by design. One worker per session at a time;
26
- `flow verify` cannot be delegated.
25
+ words — both stay in-session by design. One worker per session at a time
26
+ (`flow_stage { op: "status" }` reads the live one); sequential re-delegation is
27
+ legal and often right. `flow verify` cannot be delegated.
27
28
 
28
29
  ## Why an unbound worker is safe here
29
30
 
@@ -52,12 +53,46 @@ It closes with a `STAGE REPORT` block — `done` / `files` / `notes` /
52
53
  `blockers` — and the parent digests exactly that (bounded). A worker that skips
53
54
  the block is surfaced loudly (`reportMissing`), never silently trusted.
54
55
 
56
+ The brief also carries a standing order: **commit each completed unit of work
57
+ as you go** (one module, one file-group). If a run is ever cut, that costs one
58
+ unit — never a worktree.
59
+
60
+ ## You can watch it work
61
+
62
+ A worker is a real pi session in pi's standard session directory, named
63
+ `⏳ stage worker · <stage> · <slug>` while it runs and `✓`/`✗ …` when it ends:
64
+ it shows up in the pi-web sidebar and the `/resume` picker with the transcript
65
+ rendering live as turns land (the ⏳ means live — resuming it forks it;
66
+ browsing is safe). `pi export <file>` turns any finished transcript into
67
+ readable HTML; the tool result names the file and the export command.
68
+
69
+ For hosts with no live partial rendering there are two more surfaces:
70
+
71
+ - the driving session's **footer** beats `⏳ stage worker mm:ss · <tool> · <slug>`
72
+ while a worker runs (cleared when it ends);
73
+ - every tool call appends a line to `.dev-flow/<slug>/stage-live.log` —
74
+ tail-able, and `flow_stage { op: "status" }` prints its last lines plus elapsed
75
+ time, budget, the worktree state and recent commits, on any host, no model call.
76
+
77
+ ## The budget, and the soft landing
78
+
79
+ One run gets `budgetMin` minutes (default 45, clamped 5–120). At 75% of the
80
+ budget the worker is not killed — it is **steered**: “stop starting new units,
81
+ finish the edit you are in, commit everything done, close with the STAGE
82
+ REPORT”. A worker that obeys lands its work and reports honestly (the result
83
+ says so). The hard cut at the full budget is the backstop for a worker that
84
+ ignores the steer or wedges; a hard-cut run is marked mid-stage and is an error.
85
+
86
+ Either way, **a dirty worktree is never handed back**: the tool snapshots it
87
+ (tracked *and* untracked) with a throwaway index — no WIP commit on the branch,
88
+ no touching the real index — and names the `.dev-flow/<slug>/stage-sessions/*.diff`
89
+ file to read before deciding what to keep.
90
+
55
91
  ## Transcripts
56
92
 
57
- Each run persists under `.dev-flow/<slug>/stage-sessions/` (gitignored, like
58
- all flow-owned state): a crashed or mid-stage worker is inspectable by the
59
- path the tool result names, not lost. A run that exceeds the in-tool cap is
60
- interrupted and its report marked mid-stage.
93
+ Session JSONL lives where pi keeps sessions (standard dir, discoverable by the
94
+ picker and `pi export`); snapshots live under `.dev-flow/<slug>/stage-sessions/`
95
+ (gitignored, like all flow-owned state).
61
96
 
62
97
  ## Deliberate limits (v1)
63
98
 
@@ -20,11 +20,11 @@
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 { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
24
24
  import path from "node:path";
25
25
  import { promisify } from "node:util";
26
26
  import { Type } from "@earendil-works/pi-ai";
27
- import { compact, createAgentSession, defineTool, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
27
+ import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
28
28
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
29
29
  import {
30
30
  ALLOW_REWRITE,
@@ -45,6 +45,7 @@ import {
45
45
  checklistPending,
46
46
  checkoutTarget,
47
47
  claimBlocks,
48
+ clampStageBudgetMin,
48
49
  classifyMergeHistory,
49
50
  cmpVersions,
50
51
  cleanupAssess,
@@ -109,6 +110,10 @@ import {
109
110
  shouldSelfCompact,
110
111
  shouldTakeOverCompaction,
111
112
  stageGuidance,
113
+ stageElapsedLabel,
114
+ stageInterruptSteer,
115
+ stageLiveLine,
116
+ summarizeToolArgs,
112
117
  stateTamper,
113
118
  statusFor,
114
119
  statusJson,
@@ -399,17 +404,43 @@ function skillCore(): string | null {
399
404
  /** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
400
405
  export const compactionTakeover: { run: typeof compact } = { run: compact };
401
406
 
402
- /** Seam for spawning a stage worker (the SDK's createAgentSession) — the smoke suite replaces
403
- * `.create` with a stub: the worker contract stays testable without spending a model. */
404
- export const stageAgentFactory: { create: typeof createAgentSession } = { create: createAgentSession };
407
+ /** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
408
+ * `.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. */
413
+ 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 }) => {
416
+ let rename: (name: string) => void = () => {};
417
+ const loader = new DefaultResourceLoader({
418
+ cwd: work,
419
+ agentDir: getAgentDir(),
420
+ extensionFactories: [{
421
+ name: "dev-flow-stage-naming",
422
+ hidden: true,
423
+ factory: (childPi: ExtensionAPI) => {
424
+ childPi.on("session_start", () => { try { childPi.setSessionName(name); } catch { /* naming is visibility, not function */ } });
425
+ rename = (n: string) => { try { childPi.setSessionName(n); } catch { /* ditto */ } };
426
+ },
427
+ }],
428
+ });
429
+ 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)
433
+ return { session, rename: (n) => rename(n) };
434
+ },
435
+ };
405
436
 
406
- /** Sessions with a stage worker in flight (one per session): two of the session's own workers on one
407
- * feature would clobber one worktree — the parent is confused before that gets anywhere. */
408
- const stageWorkers = new Set<string>();
437
+ /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
438
+ export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
409
439
 
410
- /** Cap on one stage worker's run. A gate may wait 15 min on a deploy; a stage is bigger than a gate
411
- * but not unbounded — past the cap the worker is interrupted and its report marked mid-stage. */
412
- const STAGE_WORKER_MAX_MS = 45 * 60_000;
440
+ /** 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[] }
443
+ const stageRuns = new Map<string, StageRun>();
413
444
 
414
445
  /** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
415
446
  const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
@@ -2117,29 +2148,53 @@ export default function devFlow(pi: ExtensionAPI) {
2117
2148
  name: "flow_stage",
2118
2149
  label: "Stage worker",
2119
2150
  description:
2120
- "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. When it returns: read its stage report, run flow check yourself, then ask the checkpoint — the report is a handoff, not a verification.",
2121
- promptSnippet: 'flow_stage(stage: "implement"|"pre-release", note) — do the stage\'s work in a fresh disposable worker session; gates and checkpoints stay with you',
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',
2122
2153
  parameters: Type.Object({
2123
- stage: Type.String({ description: "Stage to delegate the work for — must match the bound feature's current stage" }),
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" })),
2124
2156
  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." })),
2125
2158
  }),
2126
2159
  execute: async (_id, params, signal, onUpdate, ctx) => {
2127
- const stageArg = String(params.stage ?? "");
2128
2160
  const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2129
- 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)`);
2161
+ if (String(params.op ?? "run") === "status") {
2162
+ const run = stageRuns.get(sessionKey(ctx));
2163
+ if (!run) return { content: [{ type: "text", text: "no stage worker is running in this session" }], details: { running: false } };
2164
+ const elapsed = Date.now() - run.startedAt;
2165
+ const dirtyNow = await sh("git status --porcelain", run.work);
2166
+ const logNow = await sh("git log --oneline -5", run.work);
2167
+ const text = [
2168
+ `stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
2169
+ ...run.lastLines.slice(-10),
2170
+ `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2171
+ `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2172
+ ].join("\n");
2173
+ return { content: [{ type: "text", text }], details: { running: true, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired } };
2174
+ }
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)`);
2130
2177
  if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2131
2178
  const st = boundFeature(ctx.cwd, sessionKey(ctx));
2132
2179
  if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
2133
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`);
2134
2181
  const key = sessionKey(ctx);
2135
- if (stageWorkers.has(key)) return err(`a stage worker for ${st.slug} is already running in this session — one worker per session (interrupt the running call to stop it)`);
2136
- stageWorkers.add(key);
2137
- const work = gateCwd(ctx.cwd, st);
2182
+ 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);
2184
+ const budgetMs = budgetMin * 60_000;
2185
+ const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
2186
+ const hardMs = stageTimingOverride.hardMs ?? budgetMs;
2187
+ const run: StageRun = { startedAt: Date.now(), budgetMin, softFired: false, work: gateCwd(ctx.cwd, st), lastLines: [] };
2188
+ stageRuns.set(key, run);
2189
+ const work = run.work;
2190
+ const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2138
2191
  let child: AgentSession | undefined;
2139
2192
  let crash: string | null = null;
2140
2193
  let timedOut = false;
2141
2194
  const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
2142
2195
  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}`); };
2143
2198
  const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2144
2199
  const git = await sh("git status --porcelain -b", work);
2145
2200
  const refRel = stageReference(st.stage);
@@ -2155,49 +2210,83 @@ export default function devFlow(pi: ExtensionAPI) {
2155
2210
  gitSummary: git.ok ? git.out.trim() : "(git status failed)",
2156
2211
  note: typeof params.note === "string" ? params.note : undefined,
2157
2212
  });
2158
- const sessDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
2159
- mkdirSync(sessDir, { recursive: true });
2160
- // coding tools only: what a worker cannot reach is a flow it cannot touch — the allowlist picks
2161
- // the defaults, excludeTools is the belt on the extension tools (allowlist semantics for those are ambiguous)
2162
- const created = await stageAgentFactory.create({ cwd: work, model: ctx.model, tools: ["read", "bash", "edit", "write"], excludeTools: ["flow", "flow_stage"], sessionManager: SessionManager.create(work, sessDir) });
2163
- child = created.session;
2213
+ // 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;
2218
+ let lastBeat = 0;
2164
2219
  const unsub = child.subscribe((ev: unknown) => {
2165
- const e = ev as { type?: string; toolName?: string; message?: { role?: string; usage?: Record<string, number> & { cost?: Record<string, number> } } };
2166
- if (e.type === "tool_execution_start") onUpdate?.({ content: [{ type: "text", text: `stage worker running (${st.slug} · ${st.stage}) — tool: ${e.toolName ?? "?"}` }], details: undefined });
2220
+ const e = ev as { type?: string; toolName?: string; args?: unknown; message?: { role?: string; usage?: Record<string, number> & { cost?: Record<string, number> } } };
2221
+ 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 });
2227
+ const now = Date.now();
2228
+ if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
2229
+ }
2167
2230
  if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
2168
2231
  const u = e.message.usage;
2169
2232
  for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) usage[f] += Number(u[f] ?? 0);
2170
2233
  if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) usage.cost[f] += Number(u.cost[f] ?? 0);
2171
2234
  }
2172
2235
  });
2173
- const timer = setTimeout(() => { timedOut = true; void Promise.resolve(child?.abort()).catch(() => {}); }, STAGE_WORKER_MAX_MS);
2174
- signal?.addEventListener("abort", () => void Promise.resolve(child?.abort()).catch(() => {}));
2236
+ const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2237
+ // grace before the cliff: at 75% the worker is told to commit and report — an honest handoff
2238
+ // beats an abort; the hard timer stays the backstop for a worker that ignores the steer
2239
+ const softTimer = setTimeout(() => {
2240
+ run.softFired = true;
2241
+ try { void Promise.resolve(child?.steer(stageInterruptSteer(budgetMin))).catch(() => {}); } catch { /* hard cut follows */ }
2242
+ }, softMs);
2243
+ const hardTimer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2244
+ signal?.addEventListener("abort", abortChild);
2175
2245
  try {
2176
2246
  await child.prompt(brief);
2177
2247
  } catch (e) {
2178
2248
  crash = e instanceof Error ? e.message : String(e);
2179
2249
  } finally {
2180
- clearTimeout(timer);
2250
+ clearTimeout(softTimer);
2251
+ clearTimeout(hardTimer);
2181
2252
  unsub();
2182
2253
  }
2183
- const transcript = child.sessionManager.getSessionFile() ?? sessDir;
2254
+ const clean = !crash && !timedOut;
2255
+ worker.rename(`${clean ? "✓" : "✗"} stage worker · ${st.stage} · ${st.slug}`);
2256
+ const transcript = child.sessionManager.getSessionFile() ?? "";
2184
2257
  const report = parseStageReport(child.getLastAssistantText() ?? "");
2258
+ // never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
2259
+ // via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
2260
+ let snapshot: string | null = null;
2261
+ const dirty = await sh("git status --porcelain", work);
2262
+ if (dirty.ok && dirty.out.trim()) {
2263
+ const snapDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
2264
+ mkdirSync(snapDir, { recursive: true });
2265
+ const stamp = Date.now();
2266
+ const diffFile = path.join(snapDir, `${st.stage}-${stamp}.diff`);
2267
+ const idx = path.join(snapDir, `.snap-index-${stamp}`);
2268
+ 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
+ if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
2270
+ }
2185
2271
  // the worker dirtied tier-1 records through the same hooks any edit dirties them — the
2186
2272
  // driving session re-greens after the stage: the check runs on its binding, verdict rides along.
2187
2273
  const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
2188
2274
  const parts = [renderStageReport(report)];
2189
- if (timedOut) parts.push(`worker was interrupted at the ${Math.round(STAGE_WORKER_MAX_MS / 60000)}-minute cap — treat the report as mid-stage`);
2275
+ 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
+ if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
2190
2277
  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`);
2191
2279
  parts.push(`tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}`);
2192
- parts.push(`worker transcript: ${transcript}`);
2280
+ parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}`);
2193
2281
  return {
2194
2282
  content: [{ type: "text" as const, text: parts.join("\n\n") }],
2195
- details: { slug: st.slug, stage: st.stage, done: report.done, files: report.files, notes: report.notes, blockers: report.blockers, reportMissing: report.missing, timedOut, error: crash, transcript },
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 },
2196
2284
  usage,
2197
2285
  isError: !!crash || timedOut,
2198
2286
  };
2199
2287
  } finally {
2200
- stageWorkers.delete(key);
2288
+ stageRuns.delete(key);
2289
+ if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", undefined);
2201
2290
  try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
2202
2291
  }
2203
2292
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.67.0",
3
+ "version": "0.68.0",
4
4
  "description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -20,8 +20,15 @@ checkpoints and the claim stay with you. When it returns, digest its stage
20
20
  report (done/files/notes/blockers — a handoff, never a verification), rerun
21
21
  `flow check` (its edits invalidated tier-1 records), and close the remaining
22
22
  loose ends yourself. A missing report block or a crashed worker means the
23
- worktree is mid-stage: read the transcript path the result names. Do not
24
- delegate a stage you are about to finish anyway; one worker per session.
23
+ worktree is mid-stage: read the transcript path and (if it names one) the
24
+ snapshot `.diff` the result gives. Delegate a real slice, not the tail: do not
25
+ delegate a stage you are about to finish anyway. One worker per session at a
26
+ time — but **sequential re-delegation is legal and often right**: a second
27
+ worker whose `note` says what the first one proved is how a big stage is
28
+ sliced. While one runs, the footer beats progress, the worker is visible as a
29
+ named session in the picker, and `flow_stage { op: "status" }` answers “how’s it
30
+ going?” without a model call. Size `budgetMin` to the slice (default 45): at 75%
31
+ the worker is steered to commit and report rather than cut off.
25
32
 
26
33
  1. Implement per the approved plan with project conventions and the **stage
27
34
  guidance injected at stage start** (tier-3 prose — your playbook's
package/src/core.ts CHANGED
@@ -2001,7 +2001,7 @@ export function buildStageBrief(i: StageBriefInput): string {
2001
2001
  Boundaries (the guard enforces these; do not work around them):
2002
2002
  - No gate commands, no flow verbs, no questions to the operator — the driving session runs every gate and asks every checkpoint. You owe the work and the report at the end.
2003
2003
  - .dev-flow state files (state.json, claim.json, project.md) are read-only.
2004
- - Commit to the current feature branch when the tree is tidy. Never push, never merge, never touch the default branch, never write outside ${i.workDir}.
2004
+ - Commit to the current feature branch EACH TIME a unit of work is complete (one module, one file-group, one screen) — if you are interrupted, that must cost one unit, never a dirty worktree. Never push, never merge, never touch the default branch, never write outside ${i.workDir}.
2005
2005
 
2006
2006
  Start by reading the plan — ${i.planFile} — and whatever it points to.
2007
2007
 
@@ -2020,3 +2020,46 @@ ${i.note?.trim() || "(none — the plan and the status above are your whole brie
2020
2020
  When you are done — finished OR blocked — stop doing work and close with the report.
2021
2021
  ${STAGE_REPORT_CONTRACT}`;
2022
2022
  }
2023
+
2024
+ /** Stage-worker budget bounds, in minutes. The default is deliberately generous (a gate may wait
2025
+ * 15 min on one deploy; a stage is a whole stage); `budgetMin` is the per-call, operator-visible
2026
+ * override. A playbook knob would move the default project-side — deliberately a later flow. */
2027
+ export const STAGE_BUDGET_DEFAULT_MIN = 45;
2028
+ export const STAGE_BUDGET_MIN_MIN = 5;
2029
+ export const STAGE_BUDGET_MAX_MIN = 120;
2030
+ export function clampStageBudgetMin(raw?: unknown): number {
2031
+ const n = typeof raw === "number" && Number.isFinite(raw) ? Math.round(raw) : STAGE_BUDGET_DEFAULT_MIN;
2032
+ return Math.min(STAGE_BUDGET_MAX_MIN, Math.max(STAGE_BUDGET_MIN_MIN, n));
2033
+ }
2034
+
2035
+ /** `mm:ss` for heartbeat, live-log and status lines. */
2036
+ export function stageElapsedLabel(ms: number): string {
2037
+ const s = Math.max(0, Math.floor(ms / 1000));
2038
+ return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
2039
+ }
2040
+
2041
+ /** One-summarization of a tool call's args for the live line: bash shows the command, edit/write the
2042
+ * path, anything else compact JSON — always capped. */
2043
+ export function summarizeToolArgs(args: unknown): string {
2044
+ const a = args as Record<string, unknown> | undefined;
2045
+ let s = "";
2046
+ if (a && typeof a === "object") {
2047
+ if (typeof a.command === "string") s = a.command;
2048
+ else if (typeof a.path === "string") s = a.path;
2049
+ else { try { s = JSON.stringify(a); } catch { s = ""; } }
2050
+ }
2051
+ s = s.replace(/\s+/g, " ").trim();
2052
+ return s.length > 60 ? `${s.slice(0, 57)}…` : s;
2053
+ }
2054
+
2055
+ /** One appended line of `.dev-flow/<slug>/stage-live.log` — the tail-able activity floor that works
2056
+ * on hosts where no tool partial ever renders. */
2057
+ export function stageLiveLine(elapsedMs: number, toolName: string, argsSummary: string): string {
2058
+ return `[+${stageElapsedLabel(elapsedMs)}] ${toolName}${argsSummary ? ` — ${argsSummary}` : ""}`;
2059
+ }
2060
+
2061
+ /** The soft-landing order steered into a worker at 75% of its budget: commit what is done, report
2062
+ * the truth, stop starting new units. Beats an abort by one clean commit. */
2063
+ export function stageInterruptSteer(budgetMin: number): string {
2064
+ return `Budget spent (${budgetMin} min) — stop planning new work now. Finish only the edit you are mid-way through, commit everything that is done to the feature branch (a "wip(stage): …" commit is fine and expected), then close with the STAGE REPORT block: done lists what is committed, notes says what was never started and what may not compile, blockers says "interrupted at budget". Do not start new units.`;
2065
+ }