pi-dev-flow 0.65.1 → 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 +10 -1
- package/README.md +1 -0
- package/docs/gates.md +2 -2
- package/docs/stage-agent.md +66 -0
- package/extensions/dev-flow.ts +138 -4
- package/package.json +1 -1
- package/skills/dev-flow/references/implement.md +19 -2
- package/skills/dev-flow/references/plan.md +8 -2
- package/skills/dev-flow/references/pre-release.md +5 -0
- package/src/core.ts +156 -5
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,16 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
-
## [0.
|
|
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
|
+
|
|
11
|
+
## [0.66.0] - 2026-10-27
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- **The approve gate now proves what the plan prose always demanded.** A regular feature needs `plan/plan.md` **by name** — a preliminary direction belongs inside plan.md (marked draft); a separate `pre-plan`/`direction.md` file no longer opens the gate (the old check accepted any `*.md`, which let a direction draft stand in for the plan). For `--ui` features the gate opens plan.md itself and refuses every render file under `plan/` that is not embedded with `` and every `mockups/<screen>.html` that carries no embedded `<screen>-<width>.` shot — an unrendered or unembedded screenshot is one the operator never saw. Glob matching (incl. `mockupGlobs`) is case-insensitive, so `Screenshot.PNG` can no longer slip the `*.png` proof.
|
|
16
|
+
- **`flow verify` proves a live app before asking Verified?.** With a `health` command configured and no `dev` deploy, verify now re-probes the app itself (`health: live re-probe PASS`) instead of trusting the `flow check` record — a green record survives a killed server (process death dirties no worktree fingerprint), so a dead app now refuses with `live probe FAILED … start it and rerun` rather than letting the operator be asked to review nothing. With `dev` configured the existing post-deploy probe still proves liveness. The implement nextHint and stage reference state the rule the gates now enforce: keep the app running until the checkpoint is answered.
|
|
8
17
|
|
|
9
18
|
### Changed
|
|
10
19
|
|
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` |
|
package/docs/gates.md
CHANGED
|
@@ -11,11 +11,11 @@ so it needs no `--confirmed`.
|
|
|
11
11
|
|---|---|---|
|
|
12
12
|
| `start <slug> [--ui] [--patch|--docs --confirmed] [--merge=squash\|merge\|rebase\|any] [--check-upstream]` | → plan | slug is new (binds the session); relaxed modes are operator-granted in chat, anchored by `--confirmed`: `--patch` = chore release, no plan document, every gate unchanged; `--docs` = docs-only, no plan document and no tier-1 checks (worktree and release intact). Start prints the dev-flow build and stamps it into the feature state (`flow status` shows `flow=<ver>`), warns when **this session runs an older build than the checkout** (`--check-upstream` also asks npm for the published one), prints the playbook gaps `flow doctor` would report — and **refuses while the playbook has no `merge` policy**: it names the question (squash / merge / rebase / any), the style its own history suggests, and the re-run `--merge=<style> --confirmed`, which writes the answer into `## release` (single-line insert, validated, `.bak` kept, committed as a playbook chore only when the playbook is the only dirty path) and never asks again |
|
|
13
13
|
| `use <slug>` | — (binds this session to a feature) | slug unfinished — the binding is persisted to disk as a claim (`flow version` lists every dev-flow copy registered in the process, and a copy whose in-memory bindings never saw the bind attributes commands from the claim, so a two-sources setup does not misjudge your git) |
|
|
14
|
-
| `approve [--yolo]` | plan → implement (creates worktree + branch) | `plan
|
|
14
|
+
| `approve [--yolo]` | plan → implement (creates worktree + branch) | `plan/plan.md` exists **by name** (a separate pre-plan/direction file does not open the gate — a preliminary direction belongs inside plan.md); if `--ui`, rendered mockup screenshots (per `mockupGlobs`, default `*.png`) exist under `plan/` — headless chromium renders embedded in plan.md, and the gate opens plan.md to prove it: every image file under `plan/` must appear in an embed (``, case-insensitive) and every `mockups/<screen>.html` must carry an embedded `<screen>-<width>.` shot; **one question** — or `--confirmed` after you answered in chat; **yolo** (your chat answer at **any** checkpoint question) → run that gate with `--yolo --confirmed` (`approve`/`verify`/`release`/`finish`): that question is answered and every later one (Verified?/Release?/Finish?) is pre-confirmed — the agent then runs the remaining gates back to back, honoring guidance attached to the yolo word (e.g. "yolo, create a patch version release") — checks and guardrails stay fully enforced. `commands.setup` runs in the worktree and is retried until it succeeds once (a worktree left behind by a failed setup is set up on the next `approve`, never silently reused); a `--docs` feature runs no project command at all and says `setup skipped (docs mode)` |
|
|
15
15
|
| `test` | records a check | — (runs the `test` command/check, records pass/fail) |
|
|
16
16
|
| `check` | records all tier-1 checks | — (runs every `flow-check`/test/health from project.md `## implement`); a `--docs` feature runs none of them and says `docs mode: project commands skipped` — a docs flow builds nothing, so a fresh checkout must not read as a failed deploy (#96) |
|
|
17
17
|
| `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
|
|
18
|
-
| `verify [--yolo]` | implement → pre-release | all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
|
|
18
|
+
| `verify [--yolo]` | implement → pre-release | all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`); with **no `dev` command but a `health` probe configured the gate live-re-probes the app before asking** (`health: live re-probe PASS` — a killed server refuses with `live probe FAILED`, because process death dirties no worktree fingerprint and a green record alone cannot prove liveness: start the app and rerun), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
|
|
19
19
|
| `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; with `versioning.file`: the manifest version parses and is **not tagged yet** (the bump must be ahead of the last release); with `release.changelog` the gate **proves the entry mechanically** (#97): a **heading names the version** (prose that mentions it, or a `1.2.0-beta` section when releasing `1.2.0`, is not an entry), **this branch touched the file** (an inherited changelog is not release prep), **every entry that was pending before the release survives inside the new section** — compared on normalized lines, so re-indenting a fold is free while rewording or deleting one is refused by naming the line — and **nothing is left under `Unreleased`**. The proofs guard the **baseline's** pending lines — they do not freeze the wording of the entry this flow writes, so a branch that landed as several iteration commits is free to state its result as one entry (see the changelog-writer rule in the pre-release reference). The pending baseline is the newest tag's changelog (what actually shipped), else the branch's merge base; when neither resolves, the two git-dependent proofs are skipped **with a printed advisory** rather than refusing a legal release for a topology reason, and the content proofs (the heading, its body) always run; tier-2 `## pre-release` checklist confirmed; the manifest version it validates is **stamped as the release's version of record** (`release-done` publishes that, whatever the checkouts say later); **one question** (Release?) — or `--confirmed`; `--no-version` (your call at Release?) ships this flow as **merge + changelog** — the bump/tag requirements and the tag checks at `release-done` are skipped for it, but the branch must still add its **own line under `Unreleased`** (editing an older section releases nothing) and it rides there until the next versioned release folds it (default: versioned); `--no-fold-check` is the operator-granted escape from the line-level fold proofs — one flow, stamped in the gate output, the heading and touched proofs stay; **stale session build** (loaded build behind the checkout): the gate prints both builds, lists what shipped between them (those proofs will not run this release) and folds *update (/reload, then re-run) or proceed with the old release?* into the Release? question — the operator's word, recorded in the release output, **never a block**: publishing under an older gate is a legitimate choice (hotfix, offline reload) |
|
|
20
20
|
| `release-done` | records the release (the stage stays `release`) | **no question — the Release? answer covered the publication**; verify approval; the version published is the one `release` **stamped** from the manifest it validated (a main checkout still behind cannot republish the previous version), and it must not be older than the newest matching tag **on origin** (tag lists come from `git ls-remote`, so an unfetched clone does not decide what exists; when an origin exists but cannot be asked (offline, no ssh agent) **both release gates refuse** rather than answering with local tags); with `versioning.file`: that tag exists, is reachable from the default branch **and is on origin** (a local-only tag is not a release); with `release.artifact`: the published-artifact check runs (`{version}`/`{tag}` placeholders — the line it prints names the version it verified; skip once with `--no-artifact-check`, operator-instructed only) · creates the forge release from the tag, its body **the `release.changelog` entry for that version** — the changelog is the source of truth, and the tag's annotation stands in only when the changelog has no entry for the version, else nothing (and it says why — a body that is really a shell error is dropped, never shipped) — `gh` for GitHub, `glab` for GitLab) and then **proves the release exists**: it asks the forge (`gh release view <tag>` / `glab release view <tag>`) and refuses when nothing is there, because #51, #60 and #63 were three ways of ending `release recorded as complete` with nothing published — and when the changelog was the body it **reads the stored body back** and refuses a mismatch, so the release page and the changelog cannot drift (#97; normalized before comparing, skipped with a printed note on another forge). Skipping is deliberate and loud — `--no-release-create`, `release.releases = false` or `forge = self` each print that no forge release was created, and the view check is skipped for them; **with a `merge` policy** it also proves the merge that shipped matches it — branch ancestry plus what the forge says (`gh pr view` / `glab api`), so a squash under `merge = merge` (or a merge commit under `merge = squash`) refuses the release record, while a shape it cannot see prints an advisory instead (#97's split: an invisible topology never blocks a legal release); when the release went out on a stale build the operator acknowledged at the release gate, it prints that acknowledgement in place of the after-the-fact version-skew warning, and that warning prints the session vs disk version pair plus the duplicate-copy note when a second copy is registered (#117) |
|
|
21
21
|
| `finish [--yolo] [slug]` | release → done (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes; when the clean checkout trails `origin/<default>` the gate **fast-forwards local main** as it closes out (never a merge — anything that cannot fast-forward prints the operator's exact `git pull --ff-only` command); **one question** (Finish? — mentions unmerged-looking commits with the playbook's `merge` policy in mind, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; under `merge = merge`, commits that never reached the default branch are a **policy violation**: `yolo` does not answer it, only your explicit answer does; to abandon an unreleased feature use `abort` |
|
|
@@ -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
|
|
|
@@ -938,6 +956,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
938
956
|
did.push(`build ran (${cfg.commands.build})`);
|
|
939
957
|
}
|
|
940
958
|
// deploy to dev before asking — the operator reviews the running dev app, not a promise
|
|
959
|
+
const probe = healthProbe(cfg);
|
|
941
960
|
if (cfg.commands.dev) {
|
|
942
961
|
const res = await sh(cfg.commands.dev, gateCwd(root, state!));
|
|
943
962
|
state!.checks.dev = { ok: res.ok, at: now() };
|
|
@@ -948,7 +967,6 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
948
967
|
// still serves the previous build, must not pass on a health PASS recorded before it was
|
|
949
968
|
// recreated. What "the expected version" means is the project's business — the probe runs in
|
|
950
969
|
// the worktree cwd, so it can compare the served build stamp with `git rev-parse HEAD`.
|
|
951
|
-
const probe = healthProbe(cfg);
|
|
952
970
|
if (!probe) did.push("health: none configured");
|
|
953
971
|
else {
|
|
954
972
|
const seedFail = await seedStep(root, state!, cfg);
|
|
@@ -962,7 +980,22 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
962
980
|
if (!probed.ok) return { text: `post-deploy probe FAILED (${probe}) — the deploy is not healthy / not serving this build (gave up after ${probed.attempts} attempt(s), healthWait ${cfg.healthWait}s):\n${tail(probed.out)}`, isError: true };
|
|
963
981
|
did.push(`health: PASS (${probe}${tried})`);
|
|
964
982
|
}
|
|
965
|
-
} else did.push("dev: none configured");
|
|
983
|
+
} else if (!probe) did.push("dev: none configured");
|
|
984
|
+
else {
|
|
985
|
+
// no deploy to prove, but the operator still reviews a live app — and a green health record
|
|
986
|
+
// survives a killed server (process death dirties no worktree fingerprint), so the record
|
|
987
|
+
// cannot stand for liveness: re-probe, before anyone is asked.
|
|
988
|
+
const seedFail = await seedStep(root, state!, cfg);
|
|
989
|
+
if (seedFail) return seedFail;
|
|
990
|
+
const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
|
|
991
|
+
state!.checks.health = { ok: probed.ok, at: now() };
|
|
992
|
+
await stampChecks(root, state!, ["health"]);
|
|
993
|
+
writeState(root, state!);
|
|
994
|
+
const tried = probed.attempts > 1 ? `, ${probed.attempts} attempts` : "";
|
|
995
|
+
if (!probed.ok)
|
|
996
|
+
return { text: `live probe FAILED (${probe}) — nothing is answering and no dev deploy is configured: the app the operator must review has to be running before verify — start it and rerun (gave up after ${probed.attempts} attempt(s), healthWait ${cfg.healthWait}s):\n${tail(probed.out)}`, isError: true };
|
|
997
|
+
did.push(`health: live re-probe PASS (${probe}${tried})`);
|
|
998
|
+
}
|
|
966
999
|
}
|
|
967
1000
|
const ran = [branchLine, ...did].join("; ");
|
|
968
1001
|
// yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
|
|
@@ -1598,7 +1631,11 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
|
|
|
1598
1631
|
const { root, ui, sess, cfg, flag, slugArg } = o;
|
|
1599
1632
|
const { state, err } = needState(root, sess, slugArg);
|
|
1600
1633
|
if (err) return err;
|
|
1601
|
-
const
|
|
1634
|
+
const planDir = path.join(featDir(root, state!.slug), "plan");
|
|
1635
|
+
// the embed proofs read the plan document itself: a render that exists on disk but is not
|
|
1636
|
+
// embedded in plan.md is one the operator would never be shown
|
|
1637
|
+
const planMd = path.join(planDir, "plan.md");
|
|
1638
|
+
const errs = approveGate(state!, cfg, listFiles(planDir), existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined);
|
|
1602
1639
|
if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
|
|
1603
1640
|
const planItems = applicableItems(cfg, state!, "plan");
|
|
1604
1641
|
if (flag("yolo")) state!.yolo = true; // operator's word at Approve? — every later gate question is pre-confirmed; checks and guardrails stay
|
|
@@ -2070,6 +2107,103 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2070
2107
|
});
|
|
2071
2108
|
pi.registerTool(flowTool);
|
|
2072
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
|
+
|
|
2073
2207
|
// Agent-run gates refresh at turn_end (tool ctx lacks setStatus; turn_end catches them).
|
|
2074
2208
|
pi.on("session_start", async (_event, ctx) => {
|
|
2075
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
|
|
@@ -35,8 +49,11 @@ feature).
|
|
|
35
49
|
up to `healthWait` (default 30s) — a service needing a moment after its
|
|
36
50
|
container starts is not a failed deploy; say so rather than declaring a
|
|
37
51
|
healthy deploy broken. Walk the **tier-2 checklist** (`- [ ]`) with the
|
|
38
|
-
operator honestly — it cannot be scripted.
|
|
39
|
-
`flow verify --confirmed
|
|
52
|
+
operator honestly — it cannot be scripted. Keep the app **running** when
|
|
53
|
+
you ask **Verified?** → `flow verify --confirmed` — the operator reviews
|
|
54
|
+
the live app, so never tear the test server down before the checkpoint is
|
|
55
|
+
answered (with no `dev` deploy configured, `flow verify` live-re-probes
|
|
56
|
+
`health` itself and refuses while nothing is answering). Checkpoint report: stage line **🔨 implement ·
|
|
40
57
|
`<slug>`** — commits `N ahead, M uncommitted` · tier-1 · tier-2 · deploy/
|
|
41
58
|
health · `branch@sha`, then `Done:`/`Next steps:` per the Stage reports rule. Fixes = iterate and re-verify; that loop is
|
|
42
59
|
free.
|
|
@@ -13,7 +13,11 @@
|
|
|
13
13
|
keep it current**: create the file the moment the direction is confirmed —
|
|
14
14
|
don't wait for the finished plan — and amend it in the file as the discussion
|
|
15
15
|
continues. Plan talk held only in the conversation is gone when pi
|
|
16
|
-
auto-compacts mid-stage; the gate reviews the file, not the memory.
|
|
16
|
+
auto-compacts mid-stage; the gate reviews the file, not the memory. The file
|
|
17
|
+
name is itself the gate's proof: **plan.md** — a preliminary direction
|
|
18
|
+
belongs *inside* plan.md (marked draft), never a separate
|
|
19
|
+
`pre-plan`/`direction.md` file: the approve gate requires plan.md by name.
|
|
20
|
+
First check
|
|
17
21
|
`git log origin/<default>..<default> --oneline`: local-only default-branch
|
|
18
22
|
commits fall out of the worktree's base (push them or re-plan).
|
|
19
23
|
4. **UI flag set?** Mockups live in `plan/mockups/`, one HTML per screen/state
|
|
@@ -29,7 +33,9 @@
|
|
|
29
33
|
- Embed every render in plan.md under its section —
|
|
30
34
|
``. Image syntax only (a
|
|
31
35
|
filename in prose is a broken link); before Approve? re-check that every
|
|
32
|
-
tag points at an existing file.
|
|
36
|
+
tag points at an existing file. The approve gate proves this: it opens
|
|
37
|
+
plan.md and refuses every render file that is not embedded, and every
|
|
38
|
+
`mockups/<screen>.html` with no embedded `<screen>-<width>.` shot.
|
|
33
39
|
- No chromium anywhere → tell the operator and ask; `*.html`-only plans
|
|
34
40
|
only with their OK (knob: `mockupGlobs`); never fake or skip silently.
|
|
35
41
|
- Gotchas: for a component question prefer a **static strip** — standalone
|
|
@@ -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
|
@@ -227,16 +227,43 @@ export function listFiles(dir: string): string[] {
|
|
|
227
227
|
}
|
|
228
228
|
|
|
229
229
|
function matchesGlob(file: string, globs: string[]): boolean {
|
|
230
|
-
|
|
230
|
+
const f = file.toLowerCase();
|
|
231
|
+
return globs.some((g) => {
|
|
232
|
+
const glob = g.toLowerCase();
|
|
233
|
+
return glob.startsWith("*.") ? f.endsWith(glob.slice(1)) : f.includes(glob);
|
|
234
|
+
});
|
|
231
235
|
}
|
|
232
236
|
|
|
233
|
-
/**
|
|
234
|
-
|
|
237
|
+
/** Image extensions the embed proof keys on — independent of mockupGlobs: whatever the operator
|
|
238
|
+
* configured as the render proof, a render nobody embedded is one the operator never saw. */
|
|
239
|
+
const IMG_EXT = /\.(?:png|jpe?g|webp|gif)$/i;
|
|
240
|
+
|
|
241
|
+
/** Gate: plan → implement. Returns reasons it cannot advance (empty = pass).
|
|
242
|
+
* planDoc is the text of plan/plan.md (undefined = absent) — the embed proofs read the plan
|
|
243
|
+
* document itself. Before it, the gate checked only that *a* *.md and *a* *.png existed, which
|
|
244
|
+
* let a pre-plan/direction file with unembedded screenshots walk through Approve. */
|
|
245
|
+
export function approveGate(state: FlowState, cfg: Config, planFiles: string[], planDoc?: string): string[] {
|
|
235
246
|
const errs: string[] = [];
|
|
236
247
|
if (state.stage !== "plan") errs.push(`stage is "${state.stage}", approval only applies to "plan"`);
|
|
237
|
-
if (!state.patch && !state.docs && !planFiles.
|
|
248
|
+
if (!state.patch && !state.docs && !planFiles.includes("plan.md"))
|
|
249
|
+
errs.push("plan/plan.md is missing — the plan IS plan.md (a preliminary direction belongs inside it, marked draft; a separate pre-plan/direction file does not open the gate)");
|
|
238
250
|
if (state.ui && !planFiles.some((f) => matchesGlob(f, cfg.mockupGlobs)))
|
|
239
251
|
errs.push(`UI feature: plan/mockups/ must contain rendered screenshots matching ${cfg.mockupGlobs.join(", ")} (headless chromium, embedded in plan.md)`);
|
|
252
|
+
if (state.ui && planDoc !== undefined) {
|
|
253
|
+
//  with an optional "title" tolerated; matching is case-insensitive
|
|
254
|
+
const embeds = [...planDoc.matchAll(/!\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)].map((m) => m[1].toLowerCase());
|
|
255
|
+
const unembedded = planFiles.filter((f) => IMG_EXT.test(f) && !embeds.some((e) => e === f.toLowerCase() || e.endsWith("/" + f.toLowerCase())));
|
|
256
|
+
if (unembedded.length) errs.push(`plan.md must embed every render — missing embed: ${unembedded.join(", ")} (write  under the screen's section)`);
|
|
257
|
+
// the naming plan.md prescribes (screen.html → screen-<width>.png): a mockups/*.html with no
|
|
258
|
+
// embedded shot of its own was never rendered
|
|
259
|
+
const unrendered = planFiles
|
|
260
|
+
.filter((f) => /^mockups\/[^/]+\.html$/i.test(f))
|
|
261
|
+
.filter((f) => {
|
|
262
|
+
const stem = f.toLowerCase().replace(/\.html$/, "").split("/").pop()!;
|
|
263
|
+
return !embeds.some((e) => (e.split("/").pop() ?? "").startsWith(stem) && IMG_EXT.test(e));
|
|
264
|
+
});
|
|
265
|
+
if (unrendered.length) errs.push(`mockups without an embedded render — ${unrendered.join(", ")} (render each screen and name the shot after it: <screen>-<width>.png)`);
|
|
266
|
+
}
|
|
240
267
|
return errs;
|
|
241
268
|
}
|
|
242
269
|
|
|
@@ -1776,7 +1803,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
1776
1803
|
return `investigate, present your direction and proposed mode to the operator and clarify in chat, then write the plan into .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask the operator Approve? in chat and run flow approve --confirmed when they answer`;
|
|
1777
1804
|
case "implement":
|
|
1778
1805
|
if (state.docs) return `implement in the worktree ${state.worktree} — docs mode runs no project command (no build, no dev deploy, no health probe); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
|
|
1779
|
-
return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
|
|
1806
|
+
return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
|
|
1780
1807
|
case "pre-release":
|
|
1781
1808
|
return `${cfg.release.review} → fix must-have/should-have → update docs${cfg.release.changelog ? ` → prepare ${cfg.release.changelog} (a heading for the new version, carrying every pending Unreleased line over as it stands)` : ""}${cfg.versioning.file ? ` → bump version in ${cfg.versioning.file}` : ""}, re-run flow check, then show the operator the PR summary, version and changelog, ask Release? and run flow release`;
|
|
1782
1809
|
case "release":
|
|
@@ -1869,3 +1896,127 @@ export function applyAnswer(partial: Record<string, unknown>, key: string, value
|
|
|
1869
1896
|
}
|
|
1870
1897
|
}
|
|
1871
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
|
+
}
|