pi-dev-flow 0.66.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 +9 -0
- package/README.md +1 -0
- package/docs/stage-agent.md +101 -0
- package/extensions/dev-flow.ts +206 -2
- package/package.json +1 -1
- package/skills/dev-flow/references/implement.md +21 -0
- package/skills/dev-flow/references/pre-release.md +5 -0
- package/src/core.ts +167 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,15 @@ 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
|
+
|
|
12
|
+
## [0.67.0] - 2026-10-27
|
|
13
|
+
|
|
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).
|
|
15
|
+
|
|
7
16
|
## [0.66.0] - 2026-10-27
|
|
8
17
|
|
|
9
18
|
### Changed
|
package/README.md
CHANGED
|
@@ -244,5 +244,6 @@ shipped feature checks off the item it was picked from.
|
|
|
244
244
|
| [docs/gates.md](docs/gates.md) | every gate and flag, what makes each refuse |
|
|
245
245
|
| [docs/guardrails.md](docs/guardrails.md) | everything enforced, and the deliberate limits |
|
|
246
246
|
| [docs/concurrency.md](docs/concurrency.md) | several agents, one repo: bindings, claims, attribution |
|
|
247
|
+
| [docs/stage-agent.md](docs/stage-agent.md) | `flow_stage`: run a heavy stage in a disposable worker session |
|
|
247
248
|
| [docs/headless.md](docs/headless.md) | driving a session from a bot/UI/queue: `NEEDS-OPERATOR`, `--json` surfaces |
|
|
248
249
|
| [docs/development.md](docs/development.md) | hacking on dev-flow itself: tests, self-hosting, `/reload` |
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Stage worker: one stage's work in a disposable sub-session
|
|
2
|
+
|
|
3
|
+
A big `implement` costs more context than the rest of the flow will ever need:
|
|
4
|
+
the driving session carries those hundred tool calls into every later gate and
|
|
5
|
+
checkpoint. `flow_stage` runs that work in a fresh, disposable session
|
|
6
|
+
instead, and hands back one bounded report. The conversation that talks to you
|
|
7
|
+
stays lean.
|
|
8
|
+
|
|
9
|
+
## What delegates, what does not
|
|
10
|
+
|
|
11
|
+
`flow_stage(stage: "implement" | "pre-release", note)` runs the **work** of
|
|
12
|
+
the stage you are in. Everything else stays with the driving session:
|
|
13
|
+
|
|
14
|
+
- **every gate and every checkpoint** — the worker holds no flow tool; Approve?/
|
|
15
|
+
Verified?/Release?/Finish? are still your chat, answered by you, run by the
|
|
16
|
+
bound session;
|
|
17
|
+
- **the claim** — the driving session binds the feature and keeps the live
|
|
18
|
+
claim the whole time; nothing is taken over;
|
|
19
|
+
- **verification** — the worker's stage report is a handoff, never a check:
|
|
20
|
+
after a worker run the driving session reruns `flow check` (the worker's
|
|
21
|
+
edits invalidated the tier-1 records like any other edit) and still faces
|
|
22
|
+
the normal `verify` gate.
|
|
23
|
+
|
|
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_stage { op: "status" }` reads the live one); sequential re-delegation is
|
|
27
|
+
legal and often right. `flow verify` cannot be delegated.
|
|
28
|
+
|
|
29
|
+
## Why an unbound worker is safe here
|
|
30
|
+
|
|
31
|
+
The guards already judge a second session by attribution, so a helper needs no
|
|
32
|
+
binding of its own:
|
|
33
|
+
|
|
34
|
+
- worktree writes are judged by the **owning feature's stage** — the worker may
|
|
35
|
+
edit and commit on the feature branch exactly while the flow allows it, and
|
|
36
|
+
nothing else;
|
|
37
|
+
- default-branch discipline (no commit/merge/push on main) is enforced on every
|
|
38
|
+
session's git calls alike;
|
|
39
|
+
- `.dev-flow/state.json` and `claim.json` stay flow-owned — a worker cannot
|
|
40
|
+
forge a stage or a claim, and it runs no gates because its toolset holds
|
|
41
|
+
coding tools only.
|
|
42
|
+
|
|
43
|
+
## The handoff
|
|
44
|
+
|
|
45
|
+
The worker receives a brief assembled by the tool: the stage's playbook
|
|
46
|
+
reference, `flow status --json`, live `git status` in the worktree, the plan
|
|
47
|
+
file, and the driving session's `note`. The note is the only channel for
|
|
48
|
+
conversation-only context — operator answers not yet recorded by a gate,
|
|
49
|
+
decisions, warnings, the exact next action. Everything else the worker re-reads
|
|
50
|
+
from disk.
|
|
51
|
+
|
|
52
|
+
It closes with a `STAGE REPORT` block — `done` / `files` / `notes` /
|
|
53
|
+
`blockers` — and the parent digests exactly that (bounded). A worker that skips
|
|
54
|
+
the block is surfaced loudly (`reportMissing`), never silently trusted.
|
|
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
|
+
|
|
91
|
+
## Transcripts
|
|
92
|
+
|
|
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).
|
|
96
|
+
|
|
97
|
+
## Deliberate limits (v1)
|
|
98
|
+
|
|
99
|
+
Same model for worker and driver (a per-stage model/tool policy is a playbook
|
|
100
|
+
conversation for later); no delegating of verify's fix loop; the worker cannot
|
|
101
|
+
ask you anything — if it needed to, the note was too thin.
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -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, defineTool, isToolCallEventType, SettingsManager, 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,
|
|
@@ -33,15 +33,19 @@ import {
|
|
|
33
33
|
appendReflection,
|
|
34
34
|
appendRoadmapItem,
|
|
35
35
|
bashFlowGuard,
|
|
36
|
+
buildStageBrief,
|
|
36
37
|
checkFingerprint,
|
|
37
38
|
changelogVersionsBetween,
|
|
38
39
|
normalizeReleaseBody,
|
|
39
40
|
pendingEntryLines,
|
|
40
41
|
pickReleaseNotes,
|
|
42
|
+
parseStageReport,
|
|
43
|
+
renderStageReport,
|
|
41
44
|
checklistHash,
|
|
42
45
|
checklistPending,
|
|
43
46
|
checkoutTarget,
|
|
44
47
|
claimBlocks,
|
|
48
|
+
clampStageBudgetMin,
|
|
45
49
|
classifyMergeHistory,
|
|
46
50
|
cmpVersions,
|
|
47
51
|
cleanupAssess,
|
|
@@ -57,6 +61,8 @@ import {
|
|
|
57
61
|
gateHelpJson,
|
|
58
62
|
gitInvocation,
|
|
59
63
|
githubSlug,
|
|
64
|
+
DELEGABLE_STAGES,
|
|
65
|
+
isDelegableStage,
|
|
60
66
|
guardBash,
|
|
61
67
|
guardPath,
|
|
62
68
|
healthProbe,
|
|
@@ -104,6 +110,10 @@ import {
|
|
|
104
110
|
shouldSelfCompact,
|
|
105
111
|
shouldTakeOverCompaction,
|
|
106
112
|
stageGuidance,
|
|
113
|
+
stageElapsedLabel,
|
|
114
|
+
stageInterruptSteer,
|
|
115
|
+
stageLiveLine,
|
|
116
|
+
summarizeToolArgs,
|
|
107
117
|
stateTamper,
|
|
108
118
|
statusFor,
|
|
109
119
|
statusJson,
|
|
@@ -121,6 +131,7 @@ import {
|
|
|
121
131
|
type StageCheck,
|
|
122
132
|
type PushRef,
|
|
123
133
|
type SessionClaim,
|
|
134
|
+
type DelegableStage,
|
|
124
135
|
} from "../src/core.ts";
|
|
125
136
|
import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
126
137
|
import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
|
|
@@ -393,6 +404,44 @@ function skillCore(): string | null {
|
|
|
393
404
|
/** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
|
|
394
405
|
export const compactionTakeover: { run: typeof compact } = { run: compact };
|
|
395
406
|
|
|
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
|
+
};
|
|
436
|
+
|
|
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 } = {};
|
|
439
|
+
|
|
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>();
|
|
444
|
+
|
|
396
445
|
/** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
|
|
397
446
|
const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
|
|
398
447
|
|
|
@@ -2089,6 +2138,161 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2089
2138
|
});
|
|
2090
2139
|
pi.registerTool(flowTool);
|
|
2091
2140
|
|
|
2141
|
+
// ---- stage worker (flow_stage): a stage's heavy work in a disposable sub-session ----------
|
|
2142
|
+
// 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.
|
|
2147
|
+
const stageWorkerTool = defineTool({
|
|
2148
|
+
name: "flow_stage",
|
|
2149
|
+
label: "Stage worker",
|
|
2150
|
+
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',
|
|
2153
|
+
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" })),
|
|
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." })),
|
|
2158
|
+
}),
|
|
2159
|
+
execute: async (_id, params, signal, onUpdate, ctx) => {
|
|
2160
|
+
const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
|
|
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)`);
|
|
2177
|
+
if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
|
|
2178
|
+
const st = boundFeature(ctx.cwd, sessionKey(ctx));
|
|
2179
|
+
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`);
|
|
2181
|
+
const key = sessionKey(ctx);
|
|
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");
|
|
2191
|
+
let child: AgentSession | undefined;
|
|
2192
|
+
let crash: string | null = null;
|
|
2193
|
+
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 } };
|
|
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}`); };
|
|
2198
|
+
const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
|
|
2199
|
+
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
|
+
});
|
|
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;
|
|
2219
|
+
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> } } };
|
|
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
|
+
}
|
|
2230
|
+
if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
|
|
2231
|
+
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);
|
|
2234
|
+
}
|
|
2235
|
+
});
|
|
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);
|
|
2245
|
+
try {
|
|
2246
|
+
await child.prompt(brief);
|
|
2247
|
+
} catch (e) {
|
|
2248
|
+
crash = e instanceof Error ? e.message : String(e);
|
|
2249
|
+
} finally {
|
|
2250
|
+
clearTimeout(softTimer);
|
|
2251
|
+
clearTimeout(hardTimer);
|
|
2252
|
+
unsub();
|
|
2253
|
+
}
|
|
2254
|
+
const clean = !crash && !timedOut;
|
|
2255
|
+
worker.rename(`${clean ? "✓" : "✗"} stage worker · ${st.stage} · ${st.slug}`);
|
|
2256
|
+
const transcript = child.sessionManager.getSessionFile() ?? "";
|
|
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
|
+
}
|
|
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)];
|
|
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`);
|
|
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`);
|
|
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}` : ""}`);
|
|
2281
|
+
return {
|
|
2282
|
+
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,
|
|
2286
|
+
};
|
|
2287
|
+
} finally {
|
|
2288
|
+
stageRuns.delete(key);
|
|
2289
|
+
if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", undefined);
|
|
2290
|
+
try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
|
|
2291
|
+
}
|
|
2292
|
+
},
|
|
2293
|
+
});
|
|
2294
|
+
pi.registerTool(stageWorkerTool);
|
|
2295
|
+
|
|
2092
2296
|
// Agent-run gates refresh at turn_end (tool ctx lacks setStatus; turn_end catches them).
|
|
2093
2297
|
pi.on("session_start", async (_event, ctx) => {
|
|
2094
2298
|
if (!guardsAreMine()) return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "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": [
|
|
@@ -9,6 +9,27 @@ or the injection line) — writes elsewhere are blocked; other sessions'
|
|
|
9
9
|
worktrees are theirs (attribution guards judge every path by its owning
|
|
10
10
|
feature).
|
|
11
11
|
|
|
12
|
+
**Delegating the stage's work.** When the implement work will cost far more
|
|
13
|
+
context than the rest of the flow needs (big multi-file features), run it in
|
|
14
|
+
a disposable worker session with `flow_stage` (`stage: "implement"`). The
|
|
15
|
+
worker gets a fresh context holding the plan, live git and `flow status
|
|
16
|
+
--json` — it keeps nothing from this conversation, so put every operator
|
|
17
|
+
answer, decision, warning and the exact next action into `note`. The worker
|
|
18
|
+
may edit and commit in the worktree but holds no flow tool: gates,
|
|
19
|
+
checkpoints and the claim stay with you. When it returns, digest its stage
|
|
20
|
+
report (done/files/notes/blockers — a handoff, never a verification), rerun
|
|
21
|
+
`flow check` (its edits invalidated tier-1 records), and close the remaining
|
|
22
|
+
loose ends yourself. A missing report block or a crashed worker means the
|
|
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.
|
|
32
|
+
|
|
12
33
|
1. Implement per the approved plan with project conventions and the **stage
|
|
13
34
|
guidance injected at stage start** (tier-3 prose — your playbook's
|
|
14
35
|
`prose.implement`, or dev-flow's built-in senior-discipline guidance when
|
|
@@ -6,6 +6,11 @@
|
|
|
6
6
|
|
|
7
7
|
Implemented, tested, running locally; prepare the release entirely in the
|
|
8
8
|
worktree — main-repo git state stays off-limits until this gate hands over.
|
|
9
|
+
Prep that is mostly review and judgment (the review itself, changelog wording,
|
|
10
|
+
the version decision) stays in-session; `flow_stage` (`stage: "pre-release"`)
|
|
11
|
+
can take heavy mechanical work on the same terms as the implement stage —
|
|
12
|
+
operator words travel in `note`, gates and checkpoints stay with you, rerun
|
|
13
|
+
`flow check` after the worker returns (see implement.md).
|
|
9
14
|
**Versioning:** the `versioning.file` manifest is the single source of truth
|
|
10
15
|
and tags are `versioning.pattern` rendered from it — one number everywhere. If
|
|
11
16
|
`versioning.file` is unset, stop and clarify the scheme with the user; never
|
package/src/core.ts
CHANGED
|
@@ -1896,3 +1896,170 @@ export function applyAnswer(partial: Record<string, unknown>, key: string, value
|
|
|
1896
1896
|
}
|
|
1897
1897
|
}
|
|
1898
1898
|
|
|
1899
|
+
|
|
1900
|
+
// ------------------------------------------------------- stage worker (flow_stage)
|
|
1901
|
+
|
|
1902
|
+
/** Stages whose *work* `flow_stage` may delegate to a disposable sub-session. plan is the
|
|
1903
|
+
* operator dialogue; release/finish carry the Release?/Finish? words — only the heavy middle
|
|
1904
|
+
* stages are delegated, and gates are never delegated: the driving session keeps every gate,
|
|
1905
|
+
* every checkpoint and the claim, so gate integrity never depends on a worker behaving. */
|
|
1906
|
+
export const DELEGABLE_STAGES = ["implement", "pre-release"] as const;
|
|
1907
|
+
export type DelegableStage = (typeof DELEGABLE_STAGES)[number];
|
|
1908
|
+
export function isDelegableStage(s: string): s is DelegableStage {
|
|
1909
|
+
return (DELEGABLE_STAGES as readonly string[]).includes(s);
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
/** Sentinel line that ends a stage worker's final message — the parent digests exactly this,
|
|
1913
|
+
* not the whole run, so one stage's hundred tool calls cost the driving session one bounded block. */
|
|
1914
|
+
export const STAGE_REPORT_HEAD = "STAGE REPORT";
|
|
1915
|
+
|
|
1916
|
+
/** The sections of the report block. The preserve-list mirrors flowCompactInstructions' demands:
|
|
1917
|
+
* a worker's nuance lives nowhere else, so what is not written here is lost on purpose. */
|
|
1918
|
+
export const STAGE_REPORT_CONTRACT = `Write, as the very last lines of your final message, exactly this block (empty sections say \`none\`):
|
|
1919
|
+
${STAGE_REPORT_HEAD}
|
|
1920
|
+
done:
|
|
1921
|
+
- <what you actually did, one line per item>
|
|
1922
|
+
files:
|
|
1923
|
+
- <path> — <what changed there>
|
|
1924
|
+
notes:
|
|
1925
|
+
- <operator answers/decisions not yet recorded by a gate · reasons for uncommitted changes · the exact next action>
|
|
1926
|
+
blockers:
|
|
1927
|
+
- <what would fail Verified? right now> (or: none)`;
|
|
1928
|
+
|
|
1929
|
+
export interface StageReport {
|
|
1930
|
+
done: string[];
|
|
1931
|
+
files: string[];
|
|
1932
|
+
notes: string[];
|
|
1933
|
+
blockers: string[];
|
|
1934
|
+
/** true when the worker never emitted the block — the caller must treat the raw tail as suspect. */
|
|
1935
|
+
missing: boolean;
|
|
1936
|
+
/** bounded tail of the worker's final message (kept for the digest when missing, else for reference). */
|
|
1937
|
+
rawTail: string;
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
/** Digest a stage worker's final message into the report contract. Lenient by design: a worker
|
|
1941
|
+
* that skipped the block yields `missing: true` plus its tail, never a throw at the end of a long stage. */
|
|
1942
|
+
export function parseStageReport(text: string): StageReport {
|
|
1943
|
+
const lines = (text ?? "").split("\n");
|
|
1944
|
+
let start = -1;
|
|
1945
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1946
|
+
if (/^\s*[*_#>\s]*STAGE\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
|
|
1947
|
+
}
|
|
1948
|
+
const rep: StageReport = {
|
|
1949
|
+
done: [], files: [], notes: [], blockers: [],
|
|
1950
|
+
missing: start < 0,
|
|
1951
|
+
rawTail: lines.slice(-15).join("\n").slice(-600),
|
|
1952
|
+
};
|
|
1953
|
+
if (start < 0) return rep;
|
|
1954
|
+
type Section = "done" | "files" | "notes" | "blockers";
|
|
1955
|
+
let section: Section | null = null;
|
|
1956
|
+
for (const line of lines.slice(start + 1)) {
|
|
1957
|
+
const h = /^(done|files|notes|blockers)\s*[::]\s*$/i.exec(line.trim());
|
|
1958
|
+
if (h) { section = h[1].toLowerCase() as Section; continue; }
|
|
1959
|
+
const b = /^\s*[-*]\s+(.+)$/.exec(line);
|
|
1960
|
+
if (b && section) rep[section].push(b[1].trim());
|
|
1961
|
+
}
|
|
1962
|
+
rep.blockers = rep.blockers.filter((b) => !/^(none|no blockers?|n\/a|nothing)[-.\s]*$/i.test(b));
|
|
1963
|
+
return rep;
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
/** Bounded, parent-facing digest of a worker run. `cap` exists so one delegation cannot spend
|
|
1967
|
+
* the context it just saved; the full transcript stays on disk, named in the caller's output. */
|
|
1968
|
+
export function renderStageReport(r: StageReport, cap = 4000): string {
|
|
1969
|
+
const parts: string[] = [];
|
|
1970
|
+
if (r.missing) parts.push("worker ended WITHOUT the STAGE REPORT block — digesting its raw tail, verify before trusting it:", "```", r.rawTail, "```");
|
|
1971
|
+
for (const s of ["done", "files", "notes"] as const)
|
|
1972
|
+
if (r[s].length) parts.push(`${s}:`, ...r[s].map((x) => `- ${x}`));
|
|
1973
|
+
if (r.blockers.length) parts.push("BLOCKERS:", ...r.blockers.map((x) => `- ${x}`));
|
|
1974
|
+
if (!parts.length) parts.push("(report block was empty)");
|
|
1975
|
+
const out = parts.join("\n");
|
|
1976
|
+
return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
export interface StageBriefInput {
|
|
1980
|
+
slug: string;
|
|
1981
|
+
stage: DelegableStage;
|
|
1982
|
+
/** absolute path of the feature worktree — the worker's whole world. */
|
|
1983
|
+
workDir: string;
|
|
1984
|
+
/** absolute path of plan/plan.md in the main checkout (the worktree does not carry it). */
|
|
1985
|
+
planFile: string;
|
|
1986
|
+
/** the stage playbook reference contents ("" when the stage has none). */
|
|
1987
|
+
referenceText: string;
|
|
1988
|
+
/** truth as the driving session saw it: `flow status --json` output. */
|
|
1989
|
+
statusJson: string;
|
|
1990
|
+
/** `git status --porcelain -b` taken in the worktree before the worker starts. */
|
|
1991
|
+
gitSummary: string;
|
|
1992
|
+
/** what the parent session passes on: operator answers, decisions, warnings, the next action. */
|
|
1993
|
+
note?: string;
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
/** The worker's complete brief: role, boundaries, on-disk truth, stage playbook, handoff note,
|
|
1997
|
+
* and the closing contract. Pure — the wiring reads the files and runs the git/status calls. */
|
|
1998
|
+
export function buildStageBrief(i: StageBriefInput): string {
|
|
1999
|
+
return `You are a dev-flow stage worker: you do the ${i.stage} work for feature "${i.slug}" and then report back. The flow itself belongs to a DIFFERENT session (the driving session): it owns the gates, the operator's checkpoint answers, and the claim. Work only inside ${i.workDir} (the feature worktree, on its branch).
|
|
2000
|
+
|
|
2001
|
+
Boundaries (the guard enforces these; do not work around them):
|
|
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
|
+
- .dev-flow state files (state.json, claim.json, project.md) are read-only.
|
|
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
|
+
|
|
2006
|
+
Start by reading the plan — ${i.planFile} — and whatever it points to.
|
|
2007
|
+
|
|
2008
|
+
Flow truth (\`flow status --json\` from the driving session):
|
|
2009
|
+
${i.statusJson}
|
|
2010
|
+
|
|
2011
|
+
Worktree state (\`git status --porcelain -b\`):
|
|
2012
|
+
${i.gitSummary || "(clean)"}
|
|
2013
|
+
|
|
2014
|
+
The stage playbook — what this stage owes when it exits (the gates you cannot see):
|
|
2015
|
+
${i.referenceText || "(this stage has no playbook reference)"}
|
|
2016
|
+
|
|
2017
|
+
Handoff note from the driving session (operator answers, decisions, warnings, the exact next action):
|
|
2018
|
+
${i.note?.trim() || "(none — the plan and the status above are your whole brief)"}
|
|
2019
|
+
|
|
2020
|
+
When you are done — finished OR blocked — stop doing work and close with the report.
|
|
2021
|
+
${STAGE_REPORT_CONTRACT}`;
|
|
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
|
+
}
|