pi-dev-flow 0.67.0 → 0.68.1
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 +11 -0
- package/docs/gates.md +3 -3
- package/docs/playbook.md +2 -0
- package/docs/stage-agent.md +41 -6
- package/extensions/dev-flow.ts +141 -39
- package/package.json +1 -1
- package/skills/dev-flow/references/implement.md +9 -2
- package/skills/dev-flow/references/release.md +5 -1
- package/src/core.ts +47 -3
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,17 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.68.1] - 2026-10-28
|
|
8
|
+
|
|
9
|
+
- **`flow abort` leaves no ghost (gh#138).** Aborting a feature whose worktree exists now stamps `aborted` on the kept state, and the doctor's git-consistency sweep skips stamped states — doing the cleanup the abort echo prints (`git worktree remove`, `git branch -D`) no longer becomes a `has no worktree` finding that every later `flow doctor` repeats.
|
|
10
|
+
- **`flow release` proves a clean worktree (gh#131).** A merge ships the branch, not the working tree — an uncommitted fix at the Release gate is a fix that never ships. The gate now refuses while the worktree holds uncommitted paths (listing them), and the approved line prints `commits: N ahead of <default>, M uncommitted path(s)` next to what verify prints; `flow finish`'s worktree-cleanup refusal names the paths too, not just the count.
|
|
11
|
+
- **Merging waits for green CI (gh#134).** The shipped release recipe and the release-stage hint now print `gh pr checks <n> --watch` beside the merge command: a locally-green branch can still fail checks that only CI runs, and merging with them red turns the default branch red.
|
|
12
|
+
|
|
13
|
+
## [0.68.0] - 2026-10-28
|
|
14
|
+
|
|
15
|
+
- **`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.
|
|
16
|
+
|
|
17
|
+
|
|
7
18
|
## [0.67.0] - 2026-10-27
|
|
8
19
|
|
|
9
20
|
- **`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).
|
package/docs/gates.md
CHANGED
|
@@ -16,12 +16,12 @@ so it needs no `--confirmed`.
|
|
|
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
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
|
-
| `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) |
|
|
19
|
+
| `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; **the worktree holds no uncommitted paths** (gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix that never ships; the refusal lists the paths, and the approved line prints `commits: N ahead of <default>, M uncommitted path(s)` like verify's); 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
|
-
| `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` |
|
|
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 (the refusal lists the paths, not just the count — gh#131); 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` |
|
|
22
22
|
| `reflect ["<note>"|list|tidy|move <n> --plugin|--playbook]` | — | `reflect "<note>"` queues a suggestion in `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` / `--plugin` files it in that section — the agent knows what its own note is about, so the wording guess is the fallback, and the echoed line prints the reason it landed where it did (`"gate" names dev-flow itself`, `playbook or project wording`, `nothing plugin-shaped in the note …`); a note is filed under **one** section, never both. `reflect list` numbers the open items with their section; `reflect move <n> --plugin|--playbook` re-files one of them. `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items; every surface that queues or reviews reflections (`reflect "<note>"`, bare `reflect`, `doctor`) nudges with the closed count when the checked-off pile grows. Bare `reflect` prints the full **session-reflection protocol** for the agent (from the `/flow reflect` bar it additionally wakes the model, so the protocol executes immediately): review the whole session log, re-check every open item against the current playbook and **newer dev-flow versions** (`npm view pi-dev-flow version` vs the running version — dev-flow ships from npm; recommend `pi install npm:pi-dev-flow` + `/reload`, the operator performs updates), dedupe new findings against the open ones, then report playbook vs plugin items to the operator and ask whether to fix now — plugin items: search upstream issues first (`gh issue list --repo <upstream> --state all --search …`; an author-addressed match is reported back, no match → `gh issue create` with a detailed description and a suggested fix), playbook items: `flow doctor` routes each to the docs flow that implements it |
|
|
23
23
|
| `roadmap [add "<feature>" \| pick <n> <slug> \| done <n> \| tidy]` | — | manages `.dev-flow/roadmap.md`, the gitignored backlog of future features (`- [ ]` checklist): bare prints the numbered open items, `add` appends one, `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it — **`finish` checks the stamped item off when that feature ships**; `done <n>` checks off by hand (items shipped outside a flow), `tidy` drops the checked lines. Never gates; the open count is surfaced in `status` and session context |
|
|
24
|
-
| `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
|
|
24
|
+
| `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — the state of an **aborted** feature is never a finding (its worktree cleanup is by design — gh#138) — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
|
|
25
25
|
| `status [slug]` / `abort [slug]` | — | — |
|
|
26
26
|
| `help` (`--help`, `-h`) | — | — (prints the gate help — answerable in any repo, at any stage, with no `.dev-flow/`) |
|
|
27
27
|
| `version [--check-upstream]` | — | — (prints dev-flow's **own** version and the directory it was loaded from — which copy this session runs, this checkout vs an installed `pi-dev-flow`; when the checkout has moved past the build this session loaded it says so and names both, because the gates execute the loaded code — `/reload` to run the newer one; `--check-upstream` adds the published npm version; answerable in any repo, at any stage, with no `.dev-flow/`) |
|
package/docs/playbook.md
CHANGED
|
@@ -145,6 +145,8 @@ needs to know which one the release contains. Three things read the key:
|
|
|
145
145
|
confirmation; a local `git merge --squash` only ever confirms, because merging main into a branch is
|
|
146
146
|
ordinary work. Spell the PR number **before** the flag: `gh pr merge --merge main` reads `main` as the
|
|
147
147
|
PR selector ("no pull requests found for main") and never merges anything.
|
|
148
|
+
- **whatever the style, merge only once CI is green** (`gh pr checks <n> --watch`): the local gate cannot run
|
|
149
|
+
CI-only jobs — a tool the host lacks turns a locally-green branch into a red default branch (gh#134).
|
|
148
150
|
- **`release-done` proves what actually landed** matched the policy (branch ancestry plus what the forge
|
|
149
151
|
reports), and `flow finish` says whether commits missing from the default branch are expected (squash,
|
|
150
152
|
rebase) or a violation (merge — where `yolo` does not answer for you). A shape dev-flow cannot see —
|
package/docs/stage-agent.md
CHANGED
|
@@ -22,8 +22,9 @@ the stage you are in. Everything else stays with the driving session:
|
|
|
22
22
|
the normal `verify` gate.
|
|
23
23
|
|
|
24
24
|
`plan` is the operator dialogue and `release`/`finish` carry the checkpoint
|
|
25
|
-
words — both stay in-session by design. One worker per session at a time
|
|
26
|
-
`
|
|
25
|
+
words — both stay in-session by design. One worker per session at a time
|
|
26
|
+
(`flow_stage { op: "status" }` reads the live one); sequential re-delegation is
|
|
27
|
+
legal and often right. `flow verify` cannot be delegated.
|
|
27
28
|
|
|
28
29
|
## Why an unbound worker is safe here
|
|
29
30
|
|
|
@@ -52,12 +53,46 @@ It closes with a `STAGE REPORT` block — `done` / `files` / `notes` /
|
|
|
52
53
|
`blockers` — and the parent digests exactly that (bounded). A worker that skips
|
|
53
54
|
the block is surfaced loudly (`reportMissing`), never silently trusted.
|
|
54
55
|
|
|
56
|
+
The brief also carries a standing order: **commit each completed unit of work
|
|
57
|
+
as you go** (one module, one file-group). If a run is ever cut, that costs one
|
|
58
|
+
unit — never a worktree.
|
|
59
|
+
|
|
60
|
+
## You can watch it work
|
|
61
|
+
|
|
62
|
+
A worker is a real pi session in pi's standard session directory, named
|
|
63
|
+
`⏳ stage worker · <stage> · <slug>` while it runs and `✓`/`✗ …` when it ends:
|
|
64
|
+
it shows up in the pi-web sidebar and the `/resume` picker with the transcript
|
|
65
|
+
rendering live as turns land (the ⏳ means live — resuming it forks it;
|
|
66
|
+
browsing is safe). `pi export <file>` turns any finished transcript into
|
|
67
|
+
readable HTML; the tool result names the file and the export command.
|
|
68
|
+
|
|
69
|
+
For hosts with no live partial rendering there are two more surfaces:
|
|
70
|
+
|
|
71
|
+
- the driving session's **footer** beats `⏳ stage worker mm:ss · <tool> · <slug>`
|
|
72
|
+
while a worker runs (cleared when it ends);
|
|
73
|
+
- every tool call appends a line to `.dev-flow/<slug>/stage-live.log` —
|
|
74
|
+
tail-able, and `flow_stage { op: "status" }` prints its last lines plus elapsed
|
|
75
|
+
time, budget, the worktree state and recent commits, on any host, no model call.
|
|
76
|
+
|
|
77
|
+
## The budget, and the soft landing
|
|
78
|
+
|
|
79
|
+
One run gets `budgetMin` minutes (default 45, clamped 5–120). At 75% of the
|
|
80
|
+
budget the worker is not killed — it is **steered**: “stop starting new units,
|
|
81
|
+
finish the edit you are in, commit everything done, close with the STAGE
|
|
82
|
+
REPORT”. A worker that obeys lands its work and reports honestly (the result
|
|
83
|
+
says so). The hard cut at the full budget is the backstop for a worker that
|
|
84
|
+
ignores the steer or wedges; a hard-cut run is marked mid-stage and is an error.
|
|
85
|
+
|
|
86
|
+
Either way, **a dirty worktree is never handed back**: the tool snapshots it
|
|
87
|
+
(tracked *and* untracked) with a throwaway index — no WIP commit on the branch,
|
|
88
|
+
no touching the real index — and names the `.dev-flow/<slug>/stage-sessions/*.diff`
|
|
89
|
+
file to read before deciding what to keep.
|
|
90
|
+
|
|
55
91
|
## Transcripts
|
|
56
92
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
interrupted and its report marked mid-stage.
|
|
93
|
+
Session JSONL lives where pi keeps sessions (standard dir, discoverable by the
|
|
94
|
+
picker and `pi export`); snapshots live under `.dev-flow/<slug>/stage-sessions/`
|
|
95
|
+
(gitignored, like all flow-owned state).
|
|
61
96
|
|
|
62
97
|
## Deliberate limits (v1)
|
|
63
98
|
|
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, createAgentSession, defineTool,
|
|
27
|
+
import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
28
28
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
29
29
|
import {
|
|
30
30
|
ALLOW_REWRITE,
|
|
@@ -45,6 +45,7 @@ import {
|
|
|
45
45
|
checklistPending,
|
|
46
46
|
checkoutTarget,
|
|
47
47
|
claimBlocks,
|
|
48
|
+
clampStageBudgetMin,
|
|
48
49
|
classifyMergeHistory,
|
|
49
50
|
cmpVersions,
|
|
50
51
|
cleanupAssess,
|
|
@@ -109,6 +110,10 @@ import {
|
|
|
109
110
|
shouldSelfCompact,
|
|
110
111
|
shouldTakeOverCompaction,
|
|
111
112
|
stageGuidance,
|
|
113
|
+
stageElapsedLabel,
|
|
114
|
+
stageInterruptSteer,
|
|
115
|
+
stageLiveLine,
|
|
116
|
+
summarizeToolArgs,
|
|
112
117
|
stateTamper,
|
|
113
118
|
statusFor,
|
|
114
119
|
statusJson,
|
|
@@ -399,17 +404,43 @@ function skillCore(): string | null {
|
|
|
399
404
|
/** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
|
|
400
405
|
export const compactionTakeover: { run: typeof compact } = { run: compact };
|
|
401
406
|
|
|
402
|
-
/** Seam
|
|
403
|
-
* `.
|
|
404
|
-
|
|
407
|
+
/** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
|
|
408
|
+
* `.run` with a stub, so the worker contract stays testable without spending a model and tests
|
|
409
|
+
* never touch the real session directory. The real spawn uses the DEFAULT session location (the
|
|
410
|
+
* picker and `pi export` find it for free) and names the session through an inline extension —
|
|
411
|
+
* `setSessionName` only exists on a session's own extension API — handing back a rename channel
|
|
412
|
+
* the driver uses for the ⏳ → ✓/✗ lifecycle. */
|
|
413
|
+
export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
|
|
414
|
+
export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string }) => Promise<StageWorkerHandle> } = {
|
|
415
|
+
run: async ({ work, model, name }) => {
|
|
416
|
+
let rename: (name: string) => void = () => {};
|
|
417
|
+
const loader = new DefaultResourceLoader({
|
|
418
|
+
cwd: work,
|
|
419
|
+
agentDir: getAgentDir(),
|
|
420
|
+
extensionFactories: [{
|
|
421
|
+
name: "dev-flow-stage-naming",
|
|
422
|
+
hidden: true,
|
|
423
|
+
factory: (childPi: ExtensionAPI) => {
|
|
424
|
+
childPi.on("session_start", () => { try { childPi.setSessionName(name); } catch { /* naming is visibility, not function */ } });
|
|
425
|
+
rename = (n: string) => { try { childPi.setSessionName(n); } catch { /* ditto */ } };
|
|
426
|
+
},
|
|
427
|
+
}],
|
|
428
|
+
});
|
|
429
|
+
await loader.reload();
|
|
430
|
+
const { session } = await createAgentSession({ cwd: work, model: model as never, tools: ["read", "bash", "edit", "write"], excludeTools: ["flow", "flow_stage"], resourceLoader: loader });
|
|
431
|
+
// coding tools only: what a worker cannot reach is a flow it cannot touch — the allowlist picks
|
|
432
|
+
// the defaults, excludeTools is the belt on the extension tools (allowlist semantics for those are ambiguous)
|
|
433
|
+
return { session, rename: (n) => rename(n) };
|
|
434
|
+
},
|
|
435
|
+
};
|
|
405
436
|
|
|
406
|
-
/**
|
|
407
|
-
|
|
408
|
-
const stageWorkers = new Set<string>();
|
|
437
|
+
/** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
|
|
438
|
+
export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
|
|
409
439
|
|
|
410
|
-
/**
|
|
411
|
-
*
|
|
412
|
-
|
|
440
|
+
/** What a live worker run knows about itself — the one-worker-per-session guard and the ledger the
|
|
441
|
+
* `op: "status"` verb reads. `lastLines` mirrors the live log (bounded). */
|
|
442
|
+
interface StageRun { startedAt: number; budgetMin: number; softFired: boolean; work: string; lastLines: string[] }
|
|
443
|
+
const stageRuns = new Map<string, StageRun>();
|
|
413
444
|
|
|
414
445
|
/** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
|
|
415
446
|
const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
|
|
@@ -566,7 +597,9 @@ async function gitConsistency(root: string, cfg: Config): Promise<string[]> {
|
|
|
566
597
|
for (const b of brRaw.out.split("\n").map((x) => x.replace(/^[*+]?\s+/, "").trim()).filter(Boolean)) {
|
|
567
598
|
if (!ownedBr.has(b)) out.push(`orphan branch ${b} — no unfinished feature owns it (git branch -D ${b})`);
|
|
568
599
|
}
|
|
569
|
-
|
|
600
|
+
// an aborted feature is a designed state, not drift: the abort echo tells the operator to remove
|
|
601
|
+
// the worktree by hand, and the stamp keeps that cleanup from being re-reported forever (gh#138)
|
|
602
|
+
for (const f of feats) if (f.worktree && !f.aborted && !existsSync(path.resolve(root, f.worktree))) out.push(`feature ${f.slug} (${f.stage}) has no worktree at ${f.worktree}`);
|
|
570
603
|
// the playbook belongs in git — an untracked project.md is invisible to teammates and lost on machine changes
|
|
571
604
|
if (existsSync(path.join(root, ".dev-flow", "project.md")) && !(await sh("git ls-files --error-unmatch -- .dev-flow/project.md", root)).ok)
|
|
572
605
|
out.push('.dev-flow/project.md is not tracked in git — track it: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force: a root .gitignore may exclude .dev-flow/ wholesale; the env prefix is for the installed hook — dev-flow allows a main commit whose only change is the playbook)');
|
|
@@ -1037,6 +1070,15 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1037
1070
|
if (yoloWord) return { text: yoloWord, isError: true };
|
|
1038
1071
|
// prep evidence is read from the worktree: the bump and changelog entry exist on the branch before the PR merges
|
|
1039
1072
|
const wtCwd = gateCwd(root, state!);
|
|
1073
|
+
// gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix
|
|
1074
|
+
// that never ships. verify shows the operator uncommitted paths; release proves them away. A git
|
|
1075
|
+
// that cannot answer is a measurement failure, never a refusal — same stance as the merge-base probes.
|
|
1076
|
+
const dirtyWt = await sh("git status --porcelain", wtCwd);
|
|
1077
|
+
if (dirtyWt.ok && dirtyWt.out.trim()) {
|
|
1078
|
+
const n = dirtyWt.out.split("\n").filter((l) => l.trim()).length;
|
|
1079
|
+
return { text: `release gate FAILED:\n- ${n} uncommitted path(s) in ${state!.worktree} — a merge ships the branch, not your working tree: commit or discard them, then re-run\n${tail(dirtyWt.out)}`, isError: true };
|
|
1080
|
+
}
|
|
1081
|
+
const branchProof = await branchState(wtCwd, cfg.defaultBranch);
|
|
1040
1082
|
const manifestVer = cfg.versioning.file && existsSync(path.join(wtCwd, cfg.versioning.file))
|
|
1041
1083
|
? parseVersion(cfg.versioning.file, readFileSync(path.join(wtCwd, cfg.versioning.file), "utf8"))
|
|
1042
1084
|
: null;
|
|
@@ -1135,7 +1177,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1135
1177
|
if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
|
|
1136
1178
|
clearPendingAsk(state!);
|
|
1137
1179
|
writeState(root, state!);
|
|
1138
|
-
return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${nextHint(state!, cfg)}` };
|
|
1180
|
+
return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
|
|
1139
1181
|
}
|
|
1140
1182
|
|
|
1141
1183
|
async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
|
|
@@ -1337,7 +1379,8 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1337
1379
|
const status = await sh(`git -C ${sq(wt)} status --porcelain`, root);
|
|
1338
1380
|
const unmerged = await sh(`git -C ${sq(wt)} log origin/${cfg.defaultBranch}..HEAD --oneline 2>/dev/null || git -C ${sq(wt)} log ${cfg.defaultBranch}..HEAD --oneline`, root);
|
|
1339
1381
|
const assess = cleanupAssess(status.out, unmerged.out.split("\n"));
|
|
1340
|
-
|
|
1382
|
+
// the refusal names the paths, not just the count — same proof verify and release print (gh#131)
|
|
1383
|
+
if (assess.errors.length) return { text: `finish blocked:\n- ${assess.errors.join("\n- ")}${status.out.trim() ? `:\n${tail(status.out)}` : ""}`, isError: true };
|
|
1341
1384
|
if (assess.unmerged.length) {
|
|
1342
1385
|
const policy = cfg.release.merge;
|
|
1343
1386
|
// "not on the default branch" is only a violation when the ancestry is measurable: with no origin,
|
|
@@ -1934,7 +1977,8 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
|
1934
1977
|
rmSync(featDir(root, target), { recursive: true, force: true });
|
|
1935
1978
|
return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
|
|
1936
1979
|
}
|
|
1937
|
-
|
|
1980
|
+
if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
|
|
1981
|
+
return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
|
|
1938
1982
|
}
|
|
1939
1983
|
|
|
1940
1984
|
|
|
@@ -2117,29 +2161,53 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2117
2161
|
name: "flow_stage",
|
|
2118
2162
|
label: "Stage worker",
|
|
2119
2163
|
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
|
|
2164
|
+
"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.",
|
|
2165
|
+
promptSnippet: 'flow_stage(stage: "implement"|"pre-release", note, budgetMin?) — do the stage\'s work in a fresh worker session; op: "status" reads the live run; gates and checkpoints stay with you',
|
|
2122
2166
|
parameters: Type.Object({
|
|
2123
|
-
|
|
2167
|
+
op: Type.Optional(Type.String({ description: '"run" (default) delegates the stage work; "status" reports the live worker run in this session' })),
|
|
2168
|
+
stage: Type.Optional(Type.String({ description: "Stage to delegate the work for — must match the bound feature's current stage" })),
|
|
2124
2169
|
note: Type.Optional(Type.String({ description: "The worker keeps nothing from this conversation: pass operator answers, decisions, warnings and the exact next action here." })),
|
|
2170
|
+
budgetMin: Type.Optional(Type.Number({ description: "Worker budget in minutes (5-120, default 45). At 75% the worker is steered to commit and report; past the budget it is interrupted and the tree snapshotted." })),
|
|
2125
2171
|
}),
|
|
2126
2172
|
execute: async (_id, params, signal, onUpdate, ctx) => {
|
|
2127
|
-
const stageArg = String(params.stage ?? "");
|
|
2128
2173
|
const err = (text: string) => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
|
|
2129
|
-
if (
|
|
2174
|
+
if (String(params.op ?? "run") === "status") {
|
|
2175
|
+
const run = stageRuns.get(sessionKey(ctx));
|
|
2176
|
+
if (!run) return { content: [{ type: "text", text: "no stage worker is running in this session" }], details: { running: false } };
|
|
2177
|
+
const elapsed = Date.now() - run.startedAt;
|
|
2178
|
+
const dirtyNow = await sh("git status --porcelain", run.work);
|
|
2179
|
+
const logNow = await sh("git log --oneline -5", run.work);
|
|
2180
|
+
const text = [
|
|
2181
|
+
`stage worker running: ${stageElapsedLabel(elapsed)} elapsed of ${run.budgetMin} min budget${run.softFired ? " — in grace: committing and reporting" : ""}`,
|
|
2182
|
+
...run.lastLines.slice(-10),
|
|
2183
|
+
`worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
|
|
2184
|
+
`recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
|
|
2185
|
+
].join("\n");
|
|
2186
|
+
return { content: [{ type: "text", text }], details: { running: true, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired } };
|
|
2187
|
+
}
|
|
2188
|
+
const stageArg = String(params.stage ?? "");
|
|
2189
|
+
if (!isDelegableStage(stageArg)) return err(`flow_stage delegates the work of: ${DELEGABLE_STAGES.join(" or ")} — "${stageArg}" is not delegable (plan is the operator dialogue; release/finish carry the checkpoint words; op "status" needs no stage)`);
|
|
2130
2190
|
if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
|
|
2131
2191
|
const st = boundFeature(ctx.cwd, sessionKey(ctx));
|
|
2132
2192
|
if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
|
|
2133
2193
|
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
2194
|
const key = sessionKey(ctx);
|
|
2135
|
-
if (
|
|
2136
|
-
|
|
2137
|
-
const
|
|
2195
|
+
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`);
|
|
2196
|
+
const budgetMin = clampStageBudgetMin(params.budgetMin);
|
|
2197
|
+
const budgetMs = budgetMin * 60_000;
|
|
2198
|
+
const softMs = stageTimingOverride.softMs ?? Math.round(budgetMs * 0.75);
|
|
2199
|
+
const hardMs = stageTimingOverride.hardMs ?? budgetMs;
|
|
2200
|
+
const run: StageRun = { startedAt: Date.now(), budgetMin, softFired: false, work: gateCwd(ctx.cwd, st), lastLines: [] };
|
|
2201
|
+
stageRuns.set(key, run);
|
|
2202
|
+
const work = run.work;
|
|
2203
|
+
const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
|
|
2138
2204
|
let child: AgentSession | undefined;
|
|
2139
2205
|
let crash: string | null = null;
|
|
2140
2206
|
let timedOut = false;
|
|
2141
2207
|
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
|
|
2142
2208
|
try {
|
|
2209
|
+
writeFileSync(logFile, `${stageLiveLine(0, "worker", `started (${st.stage}, budget ${budgetMin} min)`)}\n`);
|
|
2210
|
+
const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ stage worker ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName} · ${st.slug}`); };
|
|
2143
2211
|
const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
|
|
2144
2212
|
const git = await sh("git status --porcelain -b", work);
|
|
2145
2213
|
const refRel = stageReference(st.stage);
|
|
@@ -2155,49 +2223,83 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2155
2223
|
gitSummary: git.ok ? git.out.trim() : "(git status failed)",
|
|
2156
2224
|
note: typeof params.note === "string" ? params.note : undefined,
|
|
2157
2225
|
});
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2226
|
+
// the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
|
|
2227
|
+
// live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
|
|
2228
|
+
// browsing is read-only by construction); `pi export <file>` makes it readable HTML
|
|
2229
|
+
const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ stage worker · ${st.stage} · ${st.slug}` });
|
|
2230
|
+
child = worker.session;
|
|
2231
|
+
let lastBeat = 0;
|
|
2164
2232
|
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")
|
|
2233
|
+
const e = ev as { type?: string; toolName?: string; args?: unknown; message?: { role?: string; usage?: Record<string, number> & { cost?: Record<string, number> } } };
|
|
2234
|
+
if (e.type === "tool_execution_start") {
|
|
2235
|
+
const line = stageLiveLine(Date.now() - run.startedAt, e.toolName ?? "?", summarizeToolArgs(e.args));
|
|
2236
|
+
run.lastLines.push(line);
|
|
2237
|
+
if (run.lastLines.length > 50) run.lastLines.shift();
|
|
2238
|
+
try { appendFileSync(logFile, `${line}\n`); } catch { /* the log mirrors activity, the transcript is the record */ }
|
|
2239
|
+
onUpdate?.({ content: [{ type: "text", text: `stage worker ${stageElapsedLabel(Date.now() - run.startedAt)} · ${e.toolName ?? "?"}` }], details: undefined });
|
|
2240
|
+
const now = Date.now();
|
|
2241
|
+
if (now - lastBeat > 5000) { lastBeat = now; beat(e.toolName ?? "?"); }
|
|
2242
|
+
}
|
|
2167
2243
|
if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
|
|
2168
2244
|
const u = e.message.usage;
|
|
2169
2245
|
for (const f of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const) usage[f] += Number(u[f] ?? 0);
|
|
2170
2246
|
if (u.cost) for (const f of ["input", "output", "cacheRead", "cacheWrite", "total"] as const) usage.cost[f] += Number(u.cost[f] ?? 0);
|
|
2171
2247
|
}
|
|
2172
2248
|
});
|
|
2173
|
-
const
|
|
2174
|
-
|
|
2249
|
+
const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
|
|
2250
|
+
// grace before the cliff: at 75% the worker is told to commit and report — an honest handoff
|
|
2251
|
+
// beats an abort; the hard timer stays the backstop for a worker that ignores the steer
|
|
2252
|
+
const softTimer = setTimeout(() => {
|
|
2253
|
+
run.softFired = true;
|
|
2254
|
+
try { void Promise.resolve(child?.steer(stageInterruptSteer(budgetMin))).catch(() => {}); } catch { /* hard cut follows */ }
|
|
2255
|
+
}, softMs);
|
|
2256
|
+
const hardTimer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
|
|
2257
|
+
signal?.addEventListener("abort", abortChild);
|
|
2175
2258
|
try {
|
|
2176
2259
|
await child.prompt(brief);
|
|
2177
2260
|
} catch (e) {
|
|
2178
2261
|
crash = e instanceof Error ? e.message : String(e);
|
|
2179
2262
|
} finally {
|
|
2180
|
-
clearTimeout(
|
|
2263
|
+
clearTimeout(softTimer);
|
|
2264
|
+
clearTimeout(hardTimer);
|
|
2181
2265
|
unsub();
|
|
2182
2266
|
}
|
|
2183
|
-
const
|
|
2267
|
+
const clean = !crash && !timedOut;
|
|
2268
|
+
worker.rename(`${clean ? "✓" : "✗"} stage worker · ${st.stage} · ${st.slug}`);
|
|
2269
|
+
const transcript = child.sessionManager.getSessionFile() ?? "";
|
|
2184
2270
|
const report = parseStageReport(child.getLastAssistantText() ?? "");
|
|
2271
|
+
// never hand back an unrecoverable state: a dirty tree is snapshotted (tracked AND untracked,
|
|
2272
|
+
// via a throwaway index — no real-index or worktree mutation, no WIP commit on the branch)
|
|
2273
|
+
let snapshot: string | null = null;
|
|
2274
|
+
const dirty = await sh("git status --porcelain", work);
|
|
2275
|
+
if (dirty.ok && dirty.out.trim()) {
|
|
2276
|
+
const snapDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
|
|
2277
|
+
mkdirSync(snapDir, { recursive: true });
|
|
2278
|
+
const stamp = Date.now();
|
|
2279
|
+
const diffFile = path.join(snapDir, `${st.stage}-${stamp}.diff`);
|
|
2280
|
+
const idx = path.join(snapDir, `.snap-index-${stamp}`);
|
|
2281
|
+
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);
|
|
2282
|
+
if (snapRun.ok && existsSync(diffFile)) snapshot = diffFile;
|
|
2283
|
+
}
|
|
2185
2284
|
// the worker dirtied tier-1 records through the same hooks any edit dirties them — the
|
|
2186
2285
|
// driving session re-greens after the stage: the check runs on its binding, verdict rides along.
|
|
2187
2286
|
const check = await runFlow(["check"], ctx.cwd, uiFrom(ctx), sessFor(ctx));
|
|
2188
2287
|
const parts = [renderStageReport(report)];
|
|
2189
|
-
if (
|
|
2288
|
+
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"}`);
|
|
2289
|
+
if (timedOut) parts.push(`worker was hard-interrupted at the ${budgetMin}-minute cap — treat the report as mid-stage`);
|
|
2190
2290
|
if (crash) parts.push(`worker run ended with an error: ${crash}`);
|
|
2291
|
+
if (snapshot) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
|
|
2191
2292
|
parts.push(`tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}`);
|
|
2192
|
-
parts.push(`worker transcript: ${transcript}`);
|
|
2293
|
+
parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}`);
|
|
2193
2294
|
return {
|
|
2194
2295
|
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 },
|
|
2296
|
+
details: { slug: st.slug, stage: st.stage, done: report.done, files: report.files, notes: report.notes, blockers: report.blockers, reportMissing: report.missing, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot },
|
|
2196
2297
|
usage,
|
|
2197
2298
|
isError: !!crash || timedOut,
|
|
2198
2299
|
};
|
|
2199
2300
|
} finally {
|
|
2200
|
-
|
|
2301
|
+
stageRuns.delete(key);
|
|
2302
|
+
if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", undefined);
|
|
2201
2303
|
try { child?.dispose(); } catch { /* dispose stays idempotent; teardown noise must not bury the report */ }
|
|
2202
2304
|
}
|
|
2203
2305
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.68.1",
|
|
4
4
|
"description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -20,8 +20,15 @@ checkpoints and the claim stay with you. When it returns, digest its stage
|
|
|
20
20
|
report (done/files/notes/blockers — a handoff, never a verification), rerun
|
|
21
21
|
`flow check` (its edits invalidated tier-1 records), and close the remaining
|
|
22
22
|
loose ends yourself. A missing report block or a crashed worker means the
|
|
23
|
-
worktree is mid-stage: read the transcript path
|
|
24
|
-
|
|
23
|
+
worktree is mid-stage: read the transcript path and (if it names one) the
|
|
24
|
+
snapshot `.diff` the result gives. Delegate a real slice, not the tail: do not
|
|
25
|
+
delegate a stage you are about to finish anyway. One worker per session at a
|
|
26
|
+
time — but **sequential re-delegation is legal and often right**: a second
|
|
27
|
+
worker whose `note` says what the first one proved is how a big stage is
|
|
28
|
+
sliced. While one runs, the footer beats progress, the worker is visible as a
|
|
29
|
+
named session in the picker, and `flow_stage { op: "status" }` answers “how’s it
|
|
30
|
+
going?” without a model call. Size `budgetMin` to the slice (default 45): at 75%
|
|
31
|
+
the worker is steered to commit and report rather than cut off.
|
|
25
32
|
|
|
26
33
|
1. Implement per the approved plan with project conventions and the **stage
|
|
27
34
|
guidance injected at stage start** (tier-3 prose — your playbook's
|
|
@@ -8,7 +8,11 @@ Cleared for main-repo git (merge/tag/push on the default branch is allowed only
|
|
|
8
8
|
here) — this stage publishes; the preparation happened in pre-release. Run in
|
|
9
9
|
the worktree unless noted:
|
|
10
10
|
|
|
11
|
-
1. Commit everything, push the feature branch, open the PR,
|
|
11
|
+
1. Commit everything, push the feature branch, open the PR, and **merge only once
|
|
12
|
+
CI is green**: `gh pr checks <n> --watch` (or your forge's equivalent) first — a
|
|
13
|
+
locally-green branch can still fail checks that only CI runs (the host may lack the
|
|
14
|
+
tool entirely), and the merge is what turns the default branch red (gh#134). Then
|
|
15
|
+
wait for the merge
|
|
12
16
|
(`gh pr merge <n> --merge` or ask the user) — with the **playbook's merge style spelled out**
|
|
13
17
|
(`gh pr merge <n> --squash` under `merge = squash`), and **the PR number before the flag**: a bare
|
|
14
18
|
`gh pr merge --merge main` makes gh read `main` as the PR selector ("no pull requests found for
|
package/src/core.ts
CHANGED
|
@@ -47,6 +47,7 @@ export interface FlowState {
|
|
|
47
47
|
forgeReleaseSkipped?: string; // a gh/glab release create that failed: release-done says so, finish names it so the missing forge release cannot slip past (#63)
|
|
48
48
|
staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
|
|
49
49
|
pendingAsk?: string; // the checkpoint word a gate asked for and has not been given ("Approve?", "Verified?", …) — presentation only (💬 in the footer), it never gates
|
|
50
|
+
aborted?: string; // flow abort on a feature whose worktree exists: the state is a deliberate abandoned-feature record (gh#138) — the doctor's git-consistency sweep must never flag its hand-removed worktree as drift
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
/** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features. */
|
|
@@ -1810,8 +1811,8 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
1810
1811
|
return state.approvals.release
|
|
1811
1812
|
? "release recorded — commit and push the release chores in the main checkout (prefix the commit with DEV_FLOW_ALLOW_MAIN=1 — the installed pre-commit hook otherwise blocks main commits), ask the operator Finish? and run flow finish (removes worktree, branch and .dev-flow/" + state.slug + "/)"
|
|
1812
1813
|
: state.noVersion
|
|
1813
|
-
? `publish: commit and push the branch, open
|
|
1814
|
-
: `publish: commit and push the branch, open
|
|
1814
|
+
? `publish: commit and push the branch, open the PR, merge only once CI is green (gh pr checks <n> --watch — a locally-green branch can still fail CI-only jobs)${mergeHintFor(cfg)} — unversioned release: no manifest bump, no tag, your changelog entry rides under Unreleased; then run flow release-done (no further question)`
|
|
1815
|
+
: `publish: commit and push the branch, open the PR, merge only once CI is green (gh pr checks <n> --watch — a locally-green branch can still fail CI-only jobs)${mergeHintFor(cfg)}, create the annotated tag from the manifest version and push it, then run flow release-done (no further question)`;
|
|
1815
1816
|
default:
|
|
1816
1817
|
return "feature finished";
|
|
1817
1818
|
}
|
|
@@ -2001,7 +2002,7 @@ export function buildStageBrief(i: StageBriefInput): string {
|
|
|
2001
2002
|
Boundaries (the guard enforces these; do not work around them):
|
|
2002
2003
|
- 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
2004
|
- .dev-flow state files (state.json, claim.json, project.md) are read-only.
|
|
2004
|
-
- Commit to the current feature branch
|
|
2005
|
+
- 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
|
|
|
2006
2007
|
Start by reading the plan — ${i.planFile} — and whatever it points to.
|
|
2007
2008
|
|
|
@@ -2020,3 +2021,46 @@ ${i.note?.trim() || "(none — the plan and the status above are your whole brie
|
|
|
2020
2021
|
When you are done — finished OR blocked — stop doing work and close with the report.
|
|
2021
2022
|
${STAGE_REPORT_CONTRACT}`;
|
|
2022
2023
|
}
|
|
2024
|
+
|
|
2025
|
+
/** Stage-worker budget bounds, in minutes. The default is deliberately generous (a gate may wait
|
|
2026
|
+
* 15 min on one deploy; a stage is a whole stage); `budgetMin` is the per-call, operator-visible
|
|
2027
|
+
* override. A playbook knob would move the default project-side — deliberately a later flow. */
|
|
2028
|
+
export const STAGE_BUDGET_DEFAULT_MIN = 45;
|
|
2029
|
+
export const STAGE_BUDGET_MIN_MIN = 5;
|
|
2030
|
+
export const STAGE_BUDGET_MAX_MIN = 120;
|
|
2031
|
+
export function clampStageBudgetMin(raw?: unknown): number {
|
|
2032
|
+
const n = typeof raw === "number" && Number.isFinite(raw) ? Math.round(raw) : STAGE_BUDGET_DEFAULT_MIN;
|
|
2033
|
+
return Math.min(STAGE_BUDGET_MAX_MIN, Math.max(STAGE_BUDGET_MIN_MIN, n));
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
/** `mm:ss` for heartbeat, live-log and status lines. */
|
|
2037
|
+
export function stageElapsedLabel(ms: number): string {
|
|
2038
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
2039
|
+
return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
/** One-summarization of a tool call's args for the live line: bash shows the command, edit/write the
|
|
2043
|
+
* path, anything else compact JSON — always capped. */
|
|
2044
|
+
export function summarizeToolArgs(args: unknown): string {
|
|
2045
|
+
const a = args as Record<string, unknown> | undefined;
|
|
2046
|
+
let s = "";
|
|
2047
|
+
if (a && typeof a === "object") {
|
|
2048
|
+
if (typeof a.command === "string") s = a.command;
|
|
2049
|
+
else if (typeof a.path === "string") s = a.path;
|
|
2050
|
+
else { try { s = JSON.stringify(a); } catch { s = ""; } }
|
|
2051
|
+
}
|
|
2052
|
+
s = s.replace(/\s+/g, " ").trim();
|
|
2053
|
+
return s.length > 60 ? `${s.slice(0, 57)}…` : s;
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
/** One appended line of `.dev-flow/<slug>/stage-live.log` — the tail-able activity floor that works
|
|
2057
|
+
* on hosts where no tool partial ever renders. */
|
|
2058
|
+
export function stageLiveLine(elapsedMs: number, toolName: string, argsSummary: string): string {
|
|
2059
|
+
return `[+${stageElapsedLabel(elapsedMs)}] ${toolName}${argsSummary ? ` — ${argsSummary}` : ""}`;
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
/** The soft-landing order steered into a worker at 75% of its budget: commit what is done, report
|
|
2063
|
+
* the truth, stop starting new units. Beats an abort by one clean commit. */
|
|
2064
|
+
export function stageInterruptSteer(budgetMin: number): string {
|
|
2065
|
+
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.`;
|
|
2066
|
+
}
|