pi-dev-flow 0.66.0 → 0.67.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 +4 -0
- package/README.md +1 -0
- package/docs/stage-agent.md +66 -0
- package/extensions/dev-flow.ts +116 -1
- package/package.json +1 -1
- package/skills/dev-flow/references/implement.md +14 -0
- package/skills/dev-flow/references/pre-release.md +5 -0
- package/src/core.ts +124 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,10 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.67.0] - 2026-10-27
|
|
8
|
+
|
|
9
|
+
- **`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).
|
|
10
|
+
|
|
7
11
|
## [0.66.0] - 2026-10-27
|
|
8
12
|
|
|
9
13
|
### 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,66 @@
|
|
|
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 verify` cannot be delegated.
|
|
27
|
+
|
|
28
|
+
## Why an unbound worker is safe here
|
|
29
|
+
|
|
30
|
+
The guards already judge a second session by attribution, so a helper needs no
|
|
31
|
+
binding of its own:
|
|
32
|
+
|
|
33
|
+
- worktree writes are judged by the **owning feature's stage** — the worker may
|
|
34
|
+
edit and commit on the feature branch exactly while the flow allows it, and
|
|
35
|
+
nothing else;
|
|
36
|
+
- default-branch discipline (no commit/merge/push on main) is enforced on every
|
|
37
|
+
session's git calls alike;
|
|
38
|
+
- `.dev-flow/state.json` and `claim.json` stay flow-owned — a worker cannot
|
|
39
|
+
forge a stage or a claim, and it runs no gates because its toolset holds
|
|
40
|
+
coding tools only.
|
|
41
|
+
|
|
42
|
+
## The handoff
|
|
43
|
+
|
|
44
|
+
The worker receives a brief assembled by the tool: the stage's playbook
|
|
45
|
+
reference, `flow status --json`, live `git status` in the worktree, the plan
|
|
46
|
+
file, and the driving session's `note`. The note is the only channel for
|
|
47
|
+
conversation-only context — operator answers not yet recorded by a gate,
|
|
48
|
+
decisions, warnings, the exact next action. Everything else the worker re-reads
|
|
49
|
+
from disk.
|
|
50
|
+
|
|
51
|
+
It closes with a `STAGE REPORT` block — `done` / `files` / `notes` /
|
|
52
|
+
`blockers` — and the parent digests exactly that (bounded). A worker that skips
|
|
53
|
+
the block is surfaced loudly (`reportMissing`), never silently trusted.
|
|
54
|
+
|
|
55
|
+
## Transcripts
|
|
56
|
+
|
|
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.
|
|
61
|
+
|
|
62
|
+
## Deliberate limits (v1)
|
|
63
|
+
|
|
64
|
+
Same model for worker and driver (a per-stage model/tool policy is a playbook
|
|
65
|
+
conversation for later); no delegating of verify's fix loop; the worker cannot
|
|
66
|
+
ask you anything — if it needed to, the note was too thin.
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -24,7 +24,7 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameS
|
|
|
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, defineTool, isToolCallEventType, SessionManager, 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,11 +33,14 @@ 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,
|
|
@@ -57,6 +60,8 @@ import {
|
|
|
57
60
|
gateHelpJson,
|
|
58
61
|
gitInvocation,
|
|
59
62
|
githubSlug,
|
|
63
|
+
DELEGABLE_STAGES,
|
|
64
|
+
isDelegableStage,
|
|
60
65
|
guardBash,
|
|
61
66
|
guardPath,
|
|
62
67
|
healthProbe,
|
|
@@ -121,6 +126,7 @@ import {
|
|
|
121
126
|
type StageCheck,
|
|
122
127
|
type PushRef,
|
|
123
128
|
type SessionClaim,
|
|
129
|
+
type DelegableStage,
|
|
124
130
|
} from "../src/core.ts";
|
|
125
131
|
import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
126
132
|
import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
|
|
@@ -393,6 +399,18 @@ function skillCore(): string | null {
|
|
|
393
399
|
/** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
|
|
394
400
|
export const compactionTakeover: { run: typeof compact } = { run: compact };
|
|
395
401
|
|
|
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 };
|
|
405
|
+
|
|
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>();
|
|
409
|
+
|
|
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;
|
|
413
|
+
|
|
396
414
|
/** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
|
|
397
415
|
const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
|
|
398
416
|
|
|
@@ -2089,6 +2107,103 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2089
2107
|
});
|
|
2090
2108
|
pi.registerTool(flowTool);
|
|
2091
2109
|
|
|
2110
|
+
// ---- stage worker (flow_stage): a stage's heavy work in a disposable sub-session ----------
|
|
2111
|
+
// The child stays UNBOUND on purpose: writeGuard attributes worktree writes to the owning
|
|
2112
|
+
// feature's stage and bashFlowGuard stops only default-branch git ops, so an unbound worker may
|
|
2113
|
+
// edit and commit on the feature branch, while every state-gate verb refuses it (unbound, and
|
|
2114
|
+
// the parent holds the live claim) — and its tool list holds no flow tool at all. The claim,
|
|
2115
|
+
// every gate and every checkpoint stay with the driving session; the worker owes one report.
|
|
2116
|
+
const stageWorkerTool = defineTool({
|
|
2117
|
+
name: "flow_stage",
|
|
2118
|
+
label: "Stage worker",
|
|
2119
|
+
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',
|
|
2122
|
+
parameters: Type.Object({
|
|
2123
|
+
stage: Type.String({ description: "Stage to delegate the work for — must match the bound feature's current stage" }),
|
|
2124
|
+
note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
|
|
2125
|
+
}),
|
|
2126
|
+
execute: async (_id, params, signal, onUpdate, ctx) => {
|
|
2127
|
+
const stageArg = String(params.stage ?? "");
|
|
2128
|
+
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)`);
|
|
2130
|
+
if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
|
|
2131
|
+
const st = boundFeature(ctx.cwd, sessionKey(ctx));
|
|
2132
|
+
if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
|
|
2133
|
+
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
|
+
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);
|
|
2138
|
+
let child: AgentSession | undefined;
|
|
2139
|
+
let crash: string | null = null;
|
|
2140
|
+
let timedOut = false;
|
|
2141
|
+
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
|
|
2142
|
+
try {
|
|
2143
|
+
const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
|
|
2144
|
+
const git = await sh("git status --porcelain -b", work);
|
|
2145
|
+
const refRel = stageReference(st.stage);
|
|
2146
|
+
let refText = "";
|
|
2147
|
+
if (refRel) { try { refText = readFileSync(path.join(SKILL_DIR, refRel), "utf8"); } catch { refText = ""; } }
|
|
2148
|
+
const brief = buildStageBrief({
|
|
2149
|
+
slug: st.slug,
|
|
2150
|
+
stage: st.stage as DelegableStage,
|
|
2151
|
+
workDir: work,
|
|
2152
|
+
planFile: path.join(featDir(ctx.cwd, st.slug), "plan", "plan.md"),
|
|
2153
|
+
referenceText: refText,
|
|
2154
|
+
statusJson: statusJsonText,
|
|
2155
|
+
gitSummary: git.ok ? git.out.trim() : "(git status failed)",
|
|
2156
|
+
note: typeof params.note === "string" ? params.note : undefined,
|
|
2157
|
+
});
|
|
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;
|
|
2164
|
+
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 });
|
|
2167
|
+
if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
|
|
2168
|
+
const u = e.message.usage;
|
|
2169
|
+
for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) usage[f] += Number(u[f] ?? 0);
|
|
2170
|
+
if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) usage.cost[f] += Number(u.cost[f] ?? 0);
|
|
2171
|
+
}
|
|
2172
|
+
});
|
|
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(() => {}));
|
|
2175
|
+
try {
|
|
2176
|
+
await child.prompt(brief);
|
|
2177
|
+
} catch (e) {
|
|
2178
|
+
crash = e instanceof Error ? e.message : String(e);
|
|
2179
|
+
} finally {
|
|
2180
|
+
clearTimeout(timer);
|
|
2181
|
+
unsub();
|
|
2182
|
+
}
|
|
2183
|
+
const transcript = child.sessionManager.getSessionFile() ?? sessDir;
|
|
2184
|
+
const report = parseStageReport(child.getLastAssistantText() ?? "");
|
|
2185
|
+
// the worker dirtied tier-1 records through the same hooks any edit dirties them — the
|
|
2186
|
+
// driving session re-greens after the stage: the check runs on its binding, verdict rides along.
|
|
2187
|
+
const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
|
|
2188
|
+
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`);
|
|
2190
|
+
if (crash) parts.push(`worker run ended with an error: ${crash}`);
|
|
2191
|
+
parts.push(`tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}`);
|
|
2192
|
+
parts.push(`worker transcript: ${transcript}`);
|
|
2193
|
+
return {
|
|
2194
|
+
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 },
|
|
2196
|
+
usage,
|
|
2197
|
+
isError: !!crash || timedOut,
|
|
2198
|
+
};
|
|
2199
|
+
} finally {
|
|
2200
|
+
stageWorkers.delete(key);
|
|
2201
|
+
try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
|
|
2202
|
+
}
|
|
2203
|
+
},
|
|
2204
|
+
});
|
|
2205
|
+
pi.registerTool(stageWorkerTool);
|
|
2206
|
+
|
|
2092
2207
|
// Agent-run gates refresh at turn_end (tool ctx lacks setStatus; turn_end catches them).
|
|
2093
2208
|
pi.on("session_start", async (_event, ctx) => {
|
|
2094
2209
|
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.67.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,20 @@ 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 the result names. Do not
|
|
24
|
+
delegate a stage you are about to finish anyway; one worker per session.
|
|
25
|
+
|
|
12
26
|
1. Implement per the approved plan with project conventions and the **stage
|
|
13
27
|
guidance injected at stage start** (tier-3 prose — your playbook's
|
|
14
28
|
`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,127 @@ 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 when the tree is tidy. 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
|
+
}
|