pi-dev-flow 0.82.1 → 0.83.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 +14 -0
- package/README.md +4 -1
- package/docs/gates.md +1 -1
- package/docs/playbook.md +2 -1
- package/extensions/dev-flow.ts +267 -198
- package/package.json +1 -1
- package/skills/dev-flow/SKILL.md +1 -1
- package/skills/dev-flow/references/finish.md +15 -6
- package/skills/dev-flow/references/implement.md +4 -1
- package/skills/dev-flow/references/reflect.md +3 -2
- package/skills/dev-flow/references/release.md +2 -1
- package/src/core.ts +14 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.83.1] - 2026-11-05
|
|
8
|
+
|
|
9
|
+
**A worker whose model is down is reported as down, not nudged as a stall.**
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- **A worker whose model is failing is reported as such, not nudged as a stall** (fixes #173). A review worker's turns all ended in `stopReason: "error"` ("Request timed out.", after pi's own retries). `flow_stage` spent both nudges on it, which only bought two more retry storms, and then printed `ended without REPORT after 2 nudge(s)` with empty last words. The driver read that as a stall, re-briefed the slice and lost the review. Now when the newest turn ended in a model error, the worker stops at once: no nudges, no salvage prompt. The result says `model failed: stopReason=error "<message>" (N consecutive error turn(s)) — not a stall` and tells the driver to take the work inline or retry later. The pi-web Agents row records the same error.
|
|
13
|
+
|
|
14
|
+
## [0.83.0] - 2026-11-05
|
|
15
|
+
|
|
16
|
+
**`flow finish` reflects before it cleans up, so a session's review can no longer be lost.**
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
- **`flow finish` runs the closing reflection itself, before it removes anything.** Before this, the reflection was a step the agent had to remember. `release-done` said "ask Finish? and run flow finish" without mentioning it, and the only reminder was a note inside the Finish? dialog. An agent that skipped it called `flow_stage reflect` after finish, which refused because the session was already unbound, and the session's review was lost. Now, while no reflection is recorded for the flow, the first `flow finish` runs the reflect worker while the worktree, `.dev-flow/<slug>/` and the binding still exist. It then stops for the operator's fold/drop, or for Finish? when nothing was found, and the re-run with `--confirmed` cleans up. If the worker fails, nothing is removed. `--no-reflect --confirmed` skips the reflection, but only on the operator's explicit word; yolo never skips it. `--note=` passes the operator's friction notes to the worker.
|
|
20
|
+
|
|
7
21
|
## [0.82.1] - 2026-11-05
|
|
8
22
|
|
|
9
23
|
**pi-web shows one dev-flow chip per session again.**
|
package/README.md
CHANGED
|
@@ -157,7 +157,10 @@ project**: `flow reflect --plugin "<note>"` prints the recipe for a GitHub issue
|
|
|
157
157
|
keyword guess the printed line explains (`flow reflect list` numbers the queue, `flow reflect move
|
|
158
158
|
<n> --code` re-files one). The open count surfaces in `flow status` and `flow doctor`.
|
|
159
159
|
|
|
160
|
-
**At finish, a separate reviewer reflects on the session.** `
|
|
160
|
+
**At finish, a separate reviewer reflects on the session.** `flow finish` runs it before it removes
|
|
161
|
+
anything (the worktree, `.dev-flow/<slug>/` and the session binding are still there), stops for your
|
|
162
|
+
answer, and cleans up on the re-run; only your explicit `--no-reflect` skips it. The worker (also
|
|
163
|
+
callable earlier as `flow_stage` op `reflect`) is a fresh
|
|
161
164
|
read-only pi session that reads the whole driving transcript *and every worker's*, re-checks the
|
|
162
165
|
open items, dedupes against them and the upstream issues, and returns a numbered list — each
|
|
163
166
|
finding classified docs / code / plugin with a **fold or drop** recommendation. You answer per item
|
package/docs/gates.md
CHANGED
|
@@ -18,7 +18,7 @@ so it needs no `--confirmed`.
|
|
|
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 — except a **release-only flow** (#161): on a versioned project an empty branch over unreleased commits on the default branch (since the newest local version tag, or all of them before the first release) passes, the line says `release-only flow: N unreleased commit(s)`, and the version bump is the pre-release commit; with nothing unreleased the refusal says there is nothing to release; 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|--no-marker-check]` | pre-release → release | checks re-greened after the prep edits; `release.preflight` (when set) passes in the worktree — the build the tag will trigger, proven before anything ships; **the branch adds no merge-conflict marker lines** vs its merge base (#164: a hand-resolved merge that kept a `<<<<<<<`/`>>>>>>>` line is refused with `file:line`; `--no-marker-check` on the operator's word when the lines are meant); **commits after Verified?** are named in the Release? question and the approved line (#162: the operator's word covers the HEAD verify stamped — a warning, never a refusal); **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`** (a `--docs` flow is exempt — #163: a playbook/docs change owes no user-facing entry; one it writes is welcome, not proven) (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 (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` |
|
|
21
|
+
| `finish [--yolo] [--no-reflect] [--note=<text>] [slug]` | release → done — **first run the closing reflection**: while no reflection is recorded for the flow, finish starts the reflect worker before it touches anything and stops for the operator's fold/drop (or Finish? when nothing was found); the re-run with `--confirmed` does the cleanup. `--no-reflect --confirmed` skips it on the operator's explicit word (yolo never does); `--note=` hands the worker the operator's friction notes. Cleanup (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> --playbook|--code|done <n> ["<what>"]]` | — | `reflect "<note>"` queues a suggestion in **this project's** `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` (alias `--docs`) files it under `## playbook` — the fix lives only in `project.md`, a docs flow implements it; `--code` files it under `## code` — the fix touches project code, a patch flow implements it. `--plugin` **never writes**: dev-flow feedback is filed upstream, so it prints the recipe — `gh issue list --repo <dev-flow repo> --state all --search …` first, then `gh issue create` with a body ending `— reflection from <slug> <date>` (in the dev-flow repo itself plugin is code → `## code`). With no flag the wording guesses (plugin-shaped → the recipe; otherwise `## playbook`) and the echo prints why. `reflect list` numbers the open items with their section; `reflect move <n> --playbook|--code` re-files one; `reflect done <n> ["<what>"]` checks a fixed one off (`— fixed: <date> <slug> — <what>`) so doctor stops re-reporting it; a legacy `## plugin` row is flagged by list and doctor (file it upstream, check it off `— filed: gh#NNN`). `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items. **Nudges are timed, not constant**: `⚑ fix the open reflections now?` prints when an item recurred this session, is ≥ 14 days old, ≥ 3 playbook items wait, or a code item waits while between flows — at finish, in an unbound session and in doctor, never mid-feature; `↻ N closed reflection(s)` prints at ≥ 5 closed, closed ≥ open (≥ 3), or a closed item ≥ 30 days old. Bare `reflect` prints the **session-reflection protocol** (from the `/flow reflect` bar it additionally wakes the model): bound to a flow, delegate the review to `flow_stage` op `reflect`; unbound, review inline; re-check every open item against the playbook and **newer dev-flow versions** (`npm view pi-dev-flow version`; the operator performs updates); show the operator a numbered list with a fold/drop recommendation per finding and stop; fold docs/code → `reflect --playbook|--code`, fold plugin → the upstream issue, drop → nothing recorded |
|
|
23
23
|
| `roadmap [add "<feature>" [--slug=<slug>] [--brief=<notes>\|--brief-file=<path>] \| 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 (`--slug=` stamps it like pick, `--brief=`/`--brief-file=` keeps notes under it as ` > ` lines, and a bound session records `— split from <slug>` — the spin-off route for a new feature surfaced mid-flow), `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it (start seeds `plan/plan.md` with the item and its brief) — **`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
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 |
|
package/docs/playbook.md
CHANGED
|
@@ -218,7 +218,8 @@ GitHub issue on the dev-flow repo. `flow reflect --playbook|--code "<note>"` app
|
|
|
218
218
|
wording and prints why), `flow reflect list` numbers the open ones, `flow reflect move <n>
|
|
219
219
|
--playbook|--code` re-files one, `flow reflect tidy` drops the closed (`- [x]`) ones, plain
|
|
220
220
|
`flow doctor` reviews the open ones and routes each fix to the flow that implements it. At finish
|
|
221
|
-
a fresh read-only **reflect worker**
|
|
221
|
+
— run by `flow finish` itself, before it removes anything — a fresh read-only **reflect worker**
|
|
222
|
+
(`flow_stage` op `reflect`) reviews the whole session — the
|
|
222
223
|
driver's and every worker's transcript — and returns classified findings with a fold/drop
|
|
223
224
|
recommendation each; the operator decides per item (fold = a queue row or an upstream issue, drop
|
|
224
225
|
= nothing recorded). Suggestions to fix open items or tidy closed ones are timed (finish, between
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -139,6 +139,7 @@ import {
|
|
|
139
139
|
buildWorkerBrief,
|
|
140
140
|
clampBudgetMin,
|
|
141
141
|
parseWorkerReport,
|
|
142
|
+
workerTurnError,
|
|
142
143
|
workerOpError,
|
|
143
144
|
WORKER_NUDGE,
|
|
144
145
|
WORKER_NUDGES,
|
|
@@ -384,7 +385,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
|
|
|
384
385
|
}
|
|
385
386
|
|
|
386
387
|
const GATE_HELP =
|
|
387
|
-
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
388
|
+
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
388
389
|
const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
389
390
|
const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
390
391
|
const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
|
@@ -996,8 +997,13 @@ function reflectTidy(root: string): RunResult {
|
|
|
996
997
|
return { text: `reflections: dropped ${closed} closed item(s) — ${open} open` };
|
|
997
998
|
}
|
|
998
999
|
|
|
1000
|
+
/** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
|
|
1001
|
+
export interface FlowHooks {
|
|
1002
|
+
reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean }>;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
999
1005
|
/** Single runner for both the /flow command and the flow tool. */
|
|
1000
|
-
async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Promise<RunResult> {
|
|
1006
|
+
async function runFlow(args: string[], root: string, ui: Ui, sess: Session, hooks: FlowHooks = {}): Promise<RunResult> {
|
|
1001
1007
|
const [sub = "status", ...rest] = args;
|
|
1002
1008
|
// help and version are questions about the plugin, not the repo: answerable with no .dev-flow/ at all
|
|
1003
1009
|
if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, loadedVersion()) : `usage: flow <sub> — ${GATE_HELP}` };
|
|
@@ -1013,7 +1019,7 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
|
|
|
1013
1019
|
return null;
|
|
1014
1020
|
};
|
|
1015
1021
|
const slugArg = rest.find((a) => !a.startsWith("--"));
|
|
1016
|
-
const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord };
|
|
1022
|
+
const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord, hooks };
|
|
1017
1023
|
|
|
1018
1024
|
switch (sub) {
|
|
1019
1025
|
case "init":
|
|
@@ -1539,19 +1545,38 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1539
1545
|
}
|
|
1540
1546
|
// a forge release that failed at release-done is still the operator's call — but they must see it before the state vanishes (#63)
|
|
1541
1547
|
const forgeSkipNote = state!.forgeReleaseSkipped ? ` WARNING: the forge release was not created (${state!.forgeReleaseSkipped}) — recreate it manually or re-run release-done before finishing.` : "";
|
|
1542
|
-
// the session context dies with the state: name a missing reflection — advisory, never a block (yolo too)
|
|
1543
|
-
const reflectSkipNote = state!.reflectedAt ? "" : ` Note: no reflection recorded for ${state!.slug} — the finish protocol runs flow_stage(op: "reflect") first and puts fold/drop to the operator.`;
|
|
1544
1548
|
// the one finish question — asked after the safety checks so it can never be a wasted question
|
|
1545
1549
|
// yolo works uniformly at every gate: at Finish? nothing later remains to pre-confirm, the flag just answers this one
|
|
1546
1550
|
const yoloWord = takeYoloWord(state!);
|
|
1547
1551
|
if (yoloWord) return { text: yoloWord, isError: true };
|
|
1552
|
+
// The closing reflection runs here, before anything is removed: the worker reads this session's
|
|
1553
|
+
// transcripts and .dev-flow/<slug>/tmp, and finish is about to drop that folder and the binding — a
|
|
1554
|
+
// reflection asked for after finish has nothing bound to run against. Only the operator's explicit
|
|
1555
|
+
// --no-reflect skips it; yolo never does (it answers checkpoints, it does not waive the review).
|
|
1556
|
+
const skipReflect = flag("no-reflect");
|
|
1557
|
+
if (skipReflect && !flag("confirmed")) return { text: "--no-reflect is the operator's word — ask them whether to skip the closing reflection, then re-run with --no-reflect --confirmed", isError: true };
|
|
1558
|
+
if (!state!.reflectedAt && !skipReflect) {
|
|
1559
|
+
const skipHint = "or — only on the operator's explicit word — flow finish --no-reflect --confirmed";
|
|
1560
|
+
if (!o.hooks.reflect) return { text: `finish: no reflection recorded for ${state!.slug} and no reflect worker available here — run flow_stage(op: "reflect") first, ${skipHint}`, isError: true };
|
|
1561
|
+
const r = await o.hooks.reflect(state!, flagValue(o.rest, "note") ?? "");
|
|
1562
|
+
const cur = readState(root, state!.slug) ?? state!; // the worker stamped reflectedAt on disk
|
|
1563
|
+
if (!r.recorded)
|
|
1564
|
+
return { text: `finish: the closing reflection did not report — nothing was removed.\n\n${r.text}\n\nNext: re-run flow finish to retry, or review inline (bare flow reflect prints the protocol) and then flow_stage(op: "reflect"), ${skipHint}.`, isError: true };
|
|
1565
|
+
if (!r.findings) {
|
|
1566
|
+
markPendingAsk(root, cur, "Finish?");
|
|
1567
|
+
return { text: needsOperator(`the closing reflection ran before cleanup and found nothing new to fold — nothing was removed yet.\n\n${r.text}\n\nAsk the operator Finish? and run flow finish --confirmed when they answer: the worktree, branch and .dev-flow/${state!.slug}/ go on that run.`, "Finish?"), isError: true };
|
|
1568
|
+
}
|
|
1569
|
+
markPendingAsk(root, cur, "Fold or drop?");
|
|
1570
|
+
return { text: needsOperator(`the closing reflection ran before cleanup — nothing was removed yet.\n\n${r.text}\n\nThe fold/drop answer is the Finish? answer: apply it, then run flow finish --confirmed without asking again — the worktree, branch and .dev-flow/${state!.slug}/ go on that run.`, "Fold or drop?"), isError: true };
|
|
1571
|
+
}
|
|
1572
|
+
const reflectSkipNote = skipReflect && !state!.reflectedAt ? ` Reflection skipped on the operator's word — nothing re-checked this session or the open reflections.` : "";
|
|
1548
1573
|
const askPending = !flag("confirmed") && !state!.yolo;
|
|
1549
1574
|
if (askPending) {
|
|
1550
1575
|
markPendingAsk(root, state!, "Finish?");
|
|
1551
1576
|
if (!ui.hasUI) {
|
|
1552
|
-
return { text: needsOperator(`finish needs the operator: ask them Finish? in chat, then re-run with --confirmed (or run /flow finish interactively)${forgeSkipNote}
|
|
1577
|
+
return { text: needsOperator(`finish needs the operator: ask them Finish? in chat, then re-run with --confirmed (or run /flow finish interactively)${forgeSkipNote}`, "Finish?"), isError: true };
|
|
1553
1578
|
}
|
|
1554
|
-
const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote}
|
|
1579
|
+
const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
|
|
1555
1580
|
if (!ok) {
|
|
1556
1581
|
delete state!.pendingAsk;
|
|
1557
1582
|
writeState(root, state!);
|
|
@@ -1601,7 +1626,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1601
1626
|
// finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
|
|
1602
1627
|
const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
|
|
1603
1628
|
const nudgeNote = [nudge.fix, nudge.tidy].filter(Boolean).map((n) => ` ${n} — offer it to the operator.`).join("");
|
|
1604
|
-
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
1629
|
+
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${reflectSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
1605
1630
|
}
|
|
1606
1631
|
|
|
1607
1632
|
/** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
|
|
@@ -2090,6 +2115,7 @@ interface GateCtx {
|
|
|
2090
2115
|
flag: (name: string) => boolean;
|
|
2091
2116
|
slugArg?: string;
|
|
2092
2117
|
takeYoloWord: (state: FlowState) => string | null;
|
|
2118
|
+
hooks: FlowHooks;
|
|
2093
2119
|
}
|
|
2094
2120
|
|
|
2095
2121
|
async function gateVersion(o: GateCtx): Promise<RunResult> {
|
|
@@ -2550,7 +2576,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2550
2576
|
handler: async (args, ctx) => {
|
|
2551
2577
|
const cmd = parse(args);
|
|
2552
2578
|
const root = await flowRoot(ctx.cwd);
|
|
2553
|
-
const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root));
|
|
2579
|
+
const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root), finishReflectHook("flow-finish", ctx, root));
|
|
2554
2580
|
// gate output belongs to the conversation, not a toast: display:true renders a [flow] box (TUI + web), no triggerTurn so no model turn fires.
|
|
2555
2581
|
// bare reflect is the exception: its whole output is instructions for the agent — displayed without a turn, they would never execute.
|
|
2556
2582
|
const wake = cmd.length === 1 && cmd[0] === "reflect";
|
|
@@ -2568,9 +2594,9 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2568
2594
|
parameters: Type.Object({
|
|
2569
2595
|
args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug"]' }),
|
|
2570
2596
|
}),
|
|
2571
|
-
execute: async (
|
|
2597
|
+
execute: async (id, params, signal, onUpdate, ctx) => {
|
|
2572
2598
|
const root = await flowRoot(ctx.cwd);
|
|
2573
|
-
const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root));
|
|
2599
|
+
const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
|
|
2574
2600
|
if (!res.isError) maybeCompactNow(ctx, root);
|
|
2575
2601
|
return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
|
|
2576
2602
|
},
|
|
@@ -2580,12 +2606,238 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2580
2606
|
/** Driver sessions with a worker running right now — one worker per session at a time. */
|
|
2581
2607
|
const runningWorkers = new Set<string>();
|
|
2582
2608
|
|
|
2609
|
+
type WorkerResult = { content: { type: "text"; text: string }[]; details: { op: WorkerOp; outcome: string; verdict: string | null; commits: number; findings?: number; recorded?: boolean } | undefined; isError?: boolean };
|
|
2610
|
+
|
|
2611
|
+
/** One fresh-session worker run for a bound flow — the body of flow_stage, shared with flow finish,
|
|
2612
|
+
* which runs the closing reflection itself before it removes anything (the worker reads the session
|
|
2613
|
+
* transcripts and .dev-flow/<slug>/tmp, which finish deletes, and the binding finish drops). */
|
|
2614
|
+
async function runStageWorker(a: {
|
|
2615
|
+
id: string;
|
|
2616
|
+
wop: WorkerOp;
|
|
2617
|
+
st: FlowState;
|
|
2618
|
+
root: string;
|
|
2619
|
+
key: string;
|
|
2620
|
+
note: string;
|
|
2621
|
+
label?: string;
|
|
2622
|
+
budgetMin?: number;
|
|
2623
|
+
signal?: AbortSignal;
|
|
2624
|
+
onUpdate?: (u: { content: { type: "text"; text: string }[]; details: unknown }) => void;
|
|
2625
|
+
ctx: ExtensionContext;
|
|
2626
|
+
}): Promise<WorkerResult> {
|
|
2627
|
+
const { id, wop, st, root, key, signal, onUpdate, ctx } = a;
|
|
2628
|
+
const params = { note: a.note, label: a.label, budgetMin: a.budgetMin };
|
|
2629
|
+
const err = (text: string): WorkerResult => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
|
|
2630
|
+
// a reflection reviews transcripts, not the branch: it runs in the main checkout, where the
|
|
2631
|
+
// worktree may already be gone at finish time
|
|
2632
|
+
const work = wop === "reflect" ? root : worktreeAbs(root, st);
|
|
2633
|
+
if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk — nothing for a worker to work in`);
|
|
2634
|
+
if (runningWorkers.has(key)) return err("a worker is already running for this session — wait for it to return");
|
|
2635
|
+
runningWorkers.add(key);
|
|
2636
|
+
const cfg = loadProject(dfDir(root)).cfg;
|
|
2637
|
+
const budgetMin = clampBudgetMin(params.budgetMin, wop);
|
|
2638
|
+
const glyph = wop === "implement" ? "🔨" : wop === "review" ? "🔍" : "🪞";
|
|
2639
|
+
const name = workerName(glyph, st.slug, wop, params.label);
|
|
2640
|
+
const started = Date.now();
|
|
2641
|
+
const git = async (cmd: string) => { const r = await sh(cmd, work); return r.ok ? r.out : ""; };
|
|
2642
|
+
const headBefore = (await git("git rev-parse HEAD")).trim();
|
|
2643
|
+
// the reflect worker runs in the main checkout, which may already carry the operator's edits
|
|
2644
|
+
const statusBefore = wop === "reflect" ? (await git("git status --short")).trim() : "";
|
|
2645
|
+
let lineage: { id?: string; file?: string; dir?: string } = {};
|
|
2646
|
+
try { lineage = { id: ctx.sessionManager.getSessionId(), file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
|
|
2647
|
+
const selfRepo = isSelfRepo(root);
|
|
2648
|
+
const brief =
|
|
2649
|
+
wop === "reflect"
|
|
2650
|
+
? await (async () => {
|
|
2651
|
+
const items = readReflections(root);
|
|
2652
|
+
const fold = await foldView(root, items);
|
|
2653
|
+
const upstream = await pluginUpstream(root);
|
|
2654
|
+
const children = lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [];
|
|
2655
|
+
return buildReflectBrief({
|
|
2656
|
+
slug: st.slug, root, today: now().slice(0, 10),
|
|
2657
|
+
driverFile: lineage.file ?? null,
|
|
2658
|
+
children,
|
|
2659
|
+
digests: lineage.file ? writeTranscriptDigests(root, st.slug, [lineage.file, ...children.map((c) => c.file)]) : [],
|
|
2660
|
+
upstreamIssues: (await reflectSeams.upstreamIssues(root, upstream)) ?? undefined,
|
|
2661
|
+
budgetMin,
|
|
2662
|
+
reflectionsFile: path.join(dfDir(root), "reflections.md"),
|
|
2663
|
+
items,
|
|
2664
|
+
projectMd: path.join(dfDir(root), "project.md"),
|
|
2665
|
+
version: pluginVersion(import.meta.dirname).version,
|
|
2666
|
+
upstream,
|
|
2667
|
+
selfRepo,
|
|
2668
|
+
projectIssues: fold.state === "ok" && !selfRepo ? { repo: fold.slug, issues: fold.result.upstreamOnly.map((i) => ({ number: i.number, title: i.title })) } : undefined,
|
|
2669
|
+
note: String(params.note ?? ""),
|
|
2670
|
+
});
|
|
2671
|
+
})()
|
|
2672
|
+
: buildWorkerBrief({
|
|
2673
|
+
op: wop, slug: st.slug, workDir: work,
|
|
2674
|
+
planFile: ((f) => (existsSync(f) ? f : null))(path.join(featDir(root, st.slug), "plan", "plan.md")),
|
|
2675
|
+
defaultBranch: cfg.defaultBranch,
|
|
2676
|
+
commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
|
|
2677
|
+
status: await git("git status --short"),
|
|
2678
|
+
checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
|
|
2679
|
+
note: String(params.note ?? ""),
|
|
2680
|
+
});
|
|
2681
|
+
// pi-web visibility needs both halves of the lineage: the id the Agents menu links the child
|
|
2682
|
+
// to, the file the parentSession header points at — without either the worker stays unlinked.
|
|
2683
|
+
const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
|
|
2684
|
+
let child: AgentSession | undefined;
|
|
2685
|
+
let timedOut = false;
|
|
2686
|
+
let steered = false;
|
|
2687
|
+
let salvaged = false;
|
|
2688
|
+
let crash: string | null = null;
|
|
2689
|
+
let nudges = 0;
|
|
2690
|
+
let report = parseWorkerReport("");
|
|
2691
|
+
let modelError: ReturnType<typeof workerTurnError> = null;
|
|
2692
|
+
const turnError = () => workerTurnError((child as { messages?: unknown[] } | undefined)?.messages ?? []);
|
|
2693
|
+
const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
|
|
2694
|
+
const hardMs = workerTiming.hardMs ?? budgetMin * 60_000;
|
|
2695
|
+
// grace before the cliff (gh#142): steered at 75% to wrap up, so a long run hands back a REPORT
|
|
2696
|
+
// instead of being cut mid-thought — the hard timer stays the backstop
|
|
2697
|
+
const softTimer = setTimeout(() => {
|
|
2698
|
+
steered = true;
|
|
2699
|
+
try { void Promise.resolve(child?.steer(workerSteer(wop, budgetMin))).catch(() => {}); } catch { /* the hard cut follows */ }
|
|
2700
|
+
}, workerTiming.softMs ?? Math.round(hardMs * WORKER_STEER_AT));
|
|
2701
|
+
const timer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
|
|
2702
|
+
signal?.addEventListener("abort", abortChild);
|
|
2703
|
+
let unsub: (() => void) | undefined;
|
|
2704
|
+
let releaseLive: (status: string) => void = () => {};
|
|
2705
|
+
try {
|
|
2706
|
+
child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir, subagent });
|
|
2707
|
+
if (subagent) {
|
|
2708
|
+
piwebStamp(child.sessionManager, PIWEB_SUBAGENT.status, { version: 1, status: "running" });
|
|
2709
|
+
releaseLive = piwebLiveClaim(child.sessionManager, subagent);
|
|
2710
|
+
}
|
|
2711
|
+
unsub = child.subscribe((ev: unknown) => {
|
|
2712
|
+
const e = ev as { type?: string; toolName?: string };
|
|
2713
|
+
if (e.type === "tool_execution_start") {
|
|
2714
|
+
const min = Math.floor((Date.now() - started) / 60_000);
|
|
2715
|
+
onUpdate?.({ content: [{ type: "text", text: `⏳ ${name} — ${min}/${budgetMin} min · ${e.toolName ?? "?"}` }], details: { running: true } });
|
|
2716
|
+
}
|
|
2717
|
+
});
|
|
2718
|
+
await child.prompt(brief);
|
|
2719
|
+
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2720
|
+
if (!report.found) modelError = turnError();
|
|
2721
|
+
// a turn that ends in prose ("now let me write D4…") ends the session: tell it to keep going —
|
|
2722
|
+
// but never a turn that ended in a model error: pi already retried it, a nudge buys one more storm (gh#173)
|
|
2723
|
+
while (!report.found && !modelError && !timedOut && !signal?.aborted && nudges < WORKER_NUDGES) {
|
|
2724
|
+
nudges++;
|
|
2725
|
+
await child.prompt(wop === "implement" ? WORKER_NUDGE : WORKER_NUDGE_READONLY);
|
|
2726
|
+
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2727
|
+
if (!report.found) modelError = turnError();
|
|
2728
|
+
}
|
|
2729
|
+
// cut at the budget without a REPORT: one short, tool-less turn to hand back what it found —
|
|
2730
|
+
// an aborted reflection otherwise loses every finding it had already made
|
|
2731
|
+
if (!report.found && !modelError && timedOut && !signal?.aborted) {
|
|
2732
|
+
salvaged = true;
|
|
2733
|
+
const grace = setTimeout(abortChild, workerTiming.graceMs ?? WORKER_SALVAGE_MS);
|
|
2734
|
+
try {
|
|
2735
|
+
await child.prompt(WORKER_SALVAGE);
|
|
2736
|
+
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2737
|
+
} catch {
|
|
2738
|
+
/* a failed salvage is still an interrupted run, not a crash */
|
|
2739
|
+
} finally {
|
|
2740
|
+
clearTimeout(grace);
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
} catch (e) {
|
|
2744
|
+
crash = e instanceof Error ? e.message : String(e);
|
|
2745
|
+
} finally {
|
|
2746
|
+
clearTimeout(softTimer);
|
|
2747
|
+
clearTimeout(timer);
|
|
2748
|
+
signal?.removeEventListener("abort", abortChild);
|
|
2749
|
+
unsub?.();
|
|
2750
|
+
runningWorkers.delete(key);
|
|
2751
|
+
}
|
|
2752
|
+
const transcript = (() => { try { return child?.sessionManager.getSessionFile() ?? ""; } catch { return ""; } })();
|
|
2753
|
+
const headAfter = (await git("git rev-parse HEAD")).trim();
|
|
2754
|
+
const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
|
|
2755
|
+
const dirty = (await git("git status --short")).trim();
|
|
2756
|
+
const modelLine = modelError ? `model failed: stopReason=${modelError.reason} ${JSON.stringify(modelError.message)} (${modelError.streak} consecutive error turn(s)) — not a stall, ${nudges ? `stopped after ${nudges} nudge(s)` : "nudges skipped"}` : "";
|
|
2757
|
+
const outcome = crash
|
|
2758
|
+
? `crashed: ${crash}`
|
|
2759
|
+
: modelError
|
|
2760
|
+
? modelLine
|
|
2761
|
+
: timedOut
|
|
2762
|
+
? `interrupted at the ${budgetMin}-min budget${steered ? " (steered to wrap up at " + Math.round(WORKER_STEER_AT * 100) + "%)" : ""}${report.found ? " — REPORT salvaged after the cut, treat it as partial" : salvaged ? " — the salvage prompt got no REPORT either" : ""}`
|
|
2763
|
+
: report.found
|
|
2764
|
+
? `reported${steered ? " (after the wrap-up steer)" : ""}`
|
|
2765
|
+
: `ended without REPORT after ${nudges} nudge(s)`;
|
|
2766
|
+
// the terminal entry is what settles the Agents menu row (a persisted `running` the host
|
|
2767
|
+
// cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a ✓.
|
|
2768
|
+
if (subagent) {
|
|
2769
|
+
const doneAt = now();
|
|
2770
|
+
const final = crash
|
|
2771
|
+
? { version: 1, status: "failed", completedAt: doneAt, error: crash }
|
|
2772
|
+
: modelError
|
|
2773
|
+
? { version: 1, status: "failed", completedAt: doneAt, error: modelLine }
|
|
2774
|
+
: signal?.aborted || (timedOut && !report.found)
|
|
2775
|
+
? { version: 1, status: "aborted", completedAt: doneAt }
|
|
2776
|
+
: report.found
|
|
2777
|
+
? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
|
|
2778
|
+
: { version: 1, status: "failed", completedAt: doneAt, error: `ended without REPORT after ${nudges} nudge(s)`, result: report.body };
|
|
2779
|
+
piwebStamp(child?.sessionManager, PIWEB_SUBAGENT.result, final);
|
|
2780
|
+
// leave the live map only once the result entry is down: the row is never neither
|
|
2781
|
+
releaseLive(final.status);
|
|
2782
|
+
}
|
|
2783
|
+
releaseLive("failed"); // idempotent guard: a throw between claim and result must not leave a live row
|
|
2784
|
+
try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
|
|
2785
|
+
try { child?.setSessionName(`${report.found && !crash && !signal?.aborted ? (timedOut ? "◐" : "✓") : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
|
|
2786
|
+
// a dead model is a different failure from a stall, with a different remedy: say which (gh#173)
|
|
2787
|
+
const deadModelNote = `no REPORT — the worker's model was failing (${modelError?.message ?? ""}), not stalled: no ${wop === "implement" ? "slice was finished" : wop === "review" ? "review happened" : "reflection happened"}. Take it inline, or retry the delegation later (check the provider) — re-briefing it now hits the same failure.`;
|
|
2788
|
+
const parts = [`${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`];
|
|
2789
|
+
let reflected: ReturnType<typeof parseReflectReport> | null = null;
|
|
2790
|
+
if (wop === "reflect") {
|
|
2791
|
+
reflected = report.found ? parseReflectReport(report.body) : null;
|
|
2792
|
+
const rows = reflected && (reflected.findings.length || reflected.open.length || /^\s*F0\b/m.test(report.body)) ? renderReflectFindings(reflected, selfRepo) : null;
|
|
2793
|
+
parts.push(rows ? rows.join("\n") : report.found ? `REPORT (rows did not parse — read them yourself):\n${report.body.slice(0, 6000)}` : modelError ? deadModelNote : `no REPORT — last words:\n${report.body}`);
|
|
2794
|
+
if (report.found) {
|
|
2795
|
+
// the record finish reads: a reflection ran for this flow, so finish goes on to its cleanup
|
|
2796
|
+
const cur = readState(root, st.slug);
|
|
2797
|
+
if (cur) { cur.reflectedAt = now(); writeState(root, cur); }
|
|
2798
|
+
}
|
|
2799
|
+
const recurred = reflected?.open.filter((x) => x.status === "recurred").length ?? 0;
|
|
2800
|
+
const nudges = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { recurred });
|
|
2801
|
+
parts.push(
|
|
2802
|
+
"Next: show the operator this numbered list with your recommendation per item and ask fold or drop for each (one answer like 'fold 1,3 drop 2' is fine) — then STOP until they answer. " +
|
|
2803
|
+
`Fold docs → flow reflect --playbook "<note>"; fold code → flow reflect --code "<note>"; fold plugin → ${selfRepo ? 'flow reflect --code "<note>" (this is the dev-flow repo)' : 'flow reflect --plugin "<note>" prints the upstream recipe (dedupe search, then gh issue create — the fold answer is the confirmation; never a reflections.md row)'}; drop → record nothing. Open items re-checked as fixed → propose checking them off.`,
|
|
2804
|
+
);
|
|
2805
|
+
if (nudges.fix) parts.push(`${nudges.fix} — offer it after the fold/drop answer.`);
|
|
2806
|
+
if (nudges.tidy) parts.push(`${nudges.tidy} — offer it after the fold/drop answer.`);
|
|
2807
|
+
if (newCommits.trim() || dirty !== statusBefore) parts.push("note: the reflect worker changed the tree — inspect the change; it was told to write nothing");
|
|
2808
|
+
parts.push(`transcript: ${transcript || "(unknown)"}`);
|
|
2809
|
+
return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: null, commits: 0, findings: reflected?.findings.length ?? 0, recorded: report.found } };
|
|
2810
|
+
}
|
|
2811
|
+
parts.push(
|
|
2812
|
+
report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : modelError ? deadModelNote : `no REPORT — last words:\n${report.body}`,
|
|
2813
|
+
`new commits:\n${newCommits.trim() || "(none)"}`,
|
|
2814
|
+
`uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
|
|
2815
|
+
);
|
|
2816
|
+
if (wop === "implement") {
|
|
2817
|
+
const check = await runFlow(["check"], root, uiFrom(ctx), sessFor(ctx, root));
|
|
2818
|
+
parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
|
|
2819
|
+
} else if (newCommits.trim() || dirty) {
|
|
2820
|
+
parts.push("note: the reviewer changed the tree — treat its verdict with suspicion and inspect the change");
|
|
2821
|
+
}
|
|
2822
|
+
parts.push(`transcript: ${transcript || "(unknown)"}`);
|
|
2823
|
+
parts.push(wop === "implement" ? "Next: read the report, decide what is left, and drive the gates yourself." : "Advisory review: fix what is real (inline is fine for small things), then carry on — no gate waits on this verdict.");
|
|
2824
|
+
return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
/** The hook flow finish calls for its closing reflection: the same reflect worker flow_stage runs. */
|
|
2828
|
+
const finishReflectHook = (id: string, ctx: ExtensionContext, root: string, signal?: AbortSignal, onUpdate?: (u: { content: { type: "text"; text: string }[]; details: unknown }) => void): FlowHooks => ({
|
|
2829
|
+
reflect: async (st, note) => {
|
|
2830
|
+
const r = await runStageWorker({ id, wop: "reflect", st, root, key: sessionKey(ctx), note, label: "finish reflection", signal, onUpdate, ctx });
|
|
2831
|
+
return { text: r.content.map((c) => c.text).join("\n"), recorded: !!r.details?.recorded, findings: r.details?.findings ?? 0, failed: !!r.isError };
|
|
2832
|
+
},
|
|
2833
|
+
});
|
|
2834
|
+
|
|
2583
2835
|
const stageWorkerTool = defineTool({
|
|
2584
2836
|
name: "flow_stage",
|
|
2585
2837
|
label: "Stage worker",
|
|
2586
2838
|
description:
|
|
2587
|
-
'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (advisory: no gate depends on it); op "reflect" (any stage
|
|
2588
|
-
promptSnippet: 'flow_stage(op: "implement"|"review"|"reflect", note, label?) — optional fresh-session worker for a big implement slice, an independent review, or
|
|
2839
|
+
'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (advisory: no gate depends on it); op "reflect" (any stage; flow finish runs it itself before cleanup) — a fresh read-only reviewer of this session\'s transcript and every worker transcript that returns classified reflection findings (docs / code / plugin) with a fold-or-drop recommendation each, for the operator to decide. The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Delegate an implement slice when it is in the plan, provable by flow check, needs no operator input mid-slice and is big enough (≈4+ files or heavy reading) to crowd this context; small work, small fixes, mid-debug work, operator-judged work and final integration stay inline (criteria: references/implement.md). In pi-web the worker appears in the session\'s Agents menu as a subagent (running while it works, then its final status); the opened transcript holds its report.',
|
|
2840
|
+
promptSnippet: 'flow_stage(op: "implement"|"review"|"reflect", note, label?) — optional fresh-session worker for a big implement slice, an independent review, or a reflection (flow finish runs the closing one itself); gates stay with you; in pi-web workers show up as subagents in the Agents menu',
|
|
2589
2841
|
parameters: Type.Object({
|
|
2590
2842
|
op: Type.String({ description: '"implement" (a worker edits + commits a slice), "review" (read-only reviewer, findings + verdict) or "reflect" (read-only reviewer of the session transcripts, reflection findings + fold/drop recommendations)' }),
|
|
2591
2843
|
note: Type.String({ description: "The slice: what to do and anything from this conversation the worker must know (operator answers, decisions). Facts (plan path, commits, checks) are added for you." }),
|
|
@@ -2602,190 +2854,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2602
2854
|
if (!st) return err("this session is not bound to a feature — flow start <slug> or flow use <slug> first");
|
|
2603
2855
|
const why = workerOpError(op, st.stage);
|
|
2604
2856
|
if (why) return err(why);
|
|
2605
|
-
|
|
2606
|
-
// a reflection reviews transcripts, not the branch: it runs in the main checkout, where the
|
|
2607
|
-
// worktree may already be gone at finish time
|
|
2608
|
-
const work = wop === "reflect" ? root : worktreeAbs(root, st);
|
|
2609
|
-
if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk — nothing for a worker to work in`);
|
|
2610
|
-
if (runningWorkers.has(key)) return err("a worker is already running for this session — wait for it to return");
|
|
2611
|
-
runningWorkers.add(key);
|
|
2612
|
-
const cfg = loadProject(dfDir(root)).cfg;
|
|
2613
|
-
const budgetMin = clampBudgetMin(params.budgetMin, wop);
|
|
2614
|
-
const glyph = wop === "implement" ? "🔨" : wop === "review" ? "🔍" : "🪞";
|
|
2615
|
-
const name = workerName(glyph, st.slug, wop, params.label);
|
|
2616
|
-
const started = Date.now();
|
|
2617
|
-
const git = async (cmd: string) => { const r = await sh(cmd, work); return r.ok ? r.out : ""; };
|
|
2618
|
-
const headBefore = (await git("git rev-parse HEAD")).trim();
|
|
2619
|
-
// the reflect worker runs in the main checkout, which may already carry the operator's edits
|
|
2620
|
-
const statusBefore = wop === "reflect" ? (await git("git status --short")).trim() : "";
|
|
2621
|
-
let lineage: { id?: string; file?: string; dir?: string } = {};
|
|
2622
|
-
try { lineage = { id: ctx.sessionManager.getSessionId(), file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
|
|
2623
|
-
const selfRepo = isSelfRepo(root);
|
|
2624
|
-
const brief =
|
|
2625
|
-
wop === "reflect"
|
|
2626
|
-
? await (async () => {
|
|
2627
|
-
const items = readReflections(root);
|
|
2628
|
-
const fold = await foldView(root, items);
|
|
2629
|
-
const upstream = await pluginUpstream(root);
|
|
2630
|
-
const children = lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [];
|
|
2631
|
-
return buildReflectBrief({
|
|
2632
|
-
slug: st.slug, root, today: now().slice(0, 10),
|
|
2633
|
-
driverFile: lineage.file ?? null,
|
|
2634
|
-
children,
|
|
2635
|
-
digests: lineage.file ? writeTranscriptDigests(root, st.slug, [lineage.file, ...children.map((c) => c.file)]) : [],
|
|
2636
|
-
upstreamIssues: (await reflectSeams.upstreamIssues(root, upstream)) ?? undefined,
|
|
2637
|
-
budgetMin,
|
|
2638
|
-
reflectionsFile: path.join(dfDir(root), "reflections.md"),
|
|
2639
|
-
items,
|
|
2640
|
-
projectMd: path.join(dfDir(root), "project.md"),
|
|
2641
|
-
version: pluginVersion(import.meta.dirname).version,
|
|
2642
|
-
upstream,
|
|
2643
|
-
selfRepo,
|
|
2644
|
-
projectIssues: fold.state === "ok" && !selfRepo ? { repo: fold.slug, issues: fold.result.upstreamOnly.map((i) => ({ number: i.number, title: i.title })) } : undefined,
|
|
2645
|
-
note: String(params.note ?? ""),
|
|
2646
|
-
});
|
|
2647
|
-
})()
|
|
2648
|
-
: buildWorkerBrief({
|
|
2649
|
-
op: wop, slug: st.slug, workDir: work,
|
|
2650
|
-
planFile: ((f) => (existsSync(f) ? f : null))(path.join(featDir(root, st.slug), "plan", "plan.md")),
|
|
2651
|
-
defaultBranch: cfg.defaultBranch,
|
|
2652
|
-
commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
|
|
2653
|
-
status: await git("git status --short"),
|
|
2654
|
-
checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
|
|
2655
|
-
note: String(params.note ?? ""),
|
|
2656
|
-
});
|
|
2657
|
-
// pi-web visibility needs both halves of the lineage: the id the Agents menu links the child
|
|
2658
|
-
// to, the file the parentSession header points at — without either the worker stays unlinked.
|
|
2659
|
-
const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
|
|
2660
|
-
let child: AgentSession | undefined;
|
|
2661
|
-
let timedOut = false;
|
|
2662
|
-
let steered = false;
|
|
2663
|
-
let salvaged = false;
|
|
2664
|
-
let crash: string | null = null;
|
|
2665
|
-
let nudges = 0;
|
|
2666
|
-
let report = parseWorkerReport("");
|
|
2667
|
-
const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
|
|
2668
|
-
const hardMs = workerTiming.hardMs ?? budgetMin * 60_000;
|
|
2669
|
-
// grace before the cliff (gh#142): steered at 75% to wrap up, so a long run hands back a REPORT
|
|
2670
|
-
// instead of being cut mid-thought — the hard timer stays the backstop
|
|
2671
|
-
const softTimer = setTimeout(() => {
|
|
2672
|
-
steered = true;
|
|
2673
|
-
try { void Promise.resolve(child?.steer(workerSteer(wop, budgetMin))).catch(() => {}); } catch { /* the hard cut follows */ }
|
|
2674
|
-
}, workerTiming.softMs ?? Math.round(hardMs * WORKER_STEER_AT));
|
|
2675
|
-
const timer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
|
|
2676
|
-
signal?.addEventListener("abort", abortChild);
|
|
2677
|
-
let unsub: (() => void) | undefined;
|
|
2678
|
-
let releaseLive: (status: string) => void = () => {};
|
|
2679
|
-
try {
|
|
2680
|
-
child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir, subagent });
|
|
2681
|
-
if (subagent) {
|
|
2682
|
-
piwebStamp(child.sessionManager, PIWEB_SUBAGENT.status, { version: 1, status: "running" });
|
|
2683
|
-
releaseLive = piwebLiveClaim(child.sessionManager, subagent);
|
|
2684
|
-
}
|
|
2685
|
-
unsub = child.subscribe((ev: unknown) => {
|
|
2686
|
-
const e = ev as { type?: string; toolName?: string };
|
|
2687
|
-
if (e.type === "tool_execution_start") {
|
|
2688
|
-
const min = Math.floor((Date.now() - started) / 60_000);
|
|
2689
|
-
onUpdate?.({ content: [{ type: "text", text: `⏳ ${name} — ${min}/${budgetMin} min · ${e.toolName ?? "?"}` }], details: { running: true } });
|
|
2690
|
-
}
|
|
2691
|
-
});
|
|
2692
|
-
await child.prompt(brief);
|
|
2693
|
-
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2694
|
-
// a turn that ends in prose ("now let me write D4…") ends the session: tell it to keep going
|
|
2695
|
-
while (!report.found && !timedOut && !signal?.aborted && nudges < WORKER_NUDGES) {
|
|
2696
|
-
nudges++;
|
|
2697
|
-
await child.prompt(wop === "implement" ? WORKER_NUDGE : WORKER_NUDGE_READONLY);
|
|
2698
|
-
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2699
|
-
}
|
|
2700
|
-
// cut at the budget without a REPORT: one short, tool-less turn to hand back what it found —
|
|
2701
|
-
// an aborted reflection otherwise loses every finding it had already made
|
|
2702
|
-
if (!report.found && timedOut && !signal?.aborted) {
|
|
2703
|
-
salvaged = true;
|
|
2704
|
-
const grace = setTimeout(abortChild, workerTiming.graceMs ?? WORKER_SALVAGE_MS);
|
|
2705
|
-
try {
|
|
2706
|
-
await child.prompt(WORKER_SALVAGE);
|
|
2707
|
-
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2708
|
-
} catch {
|
|
2709
|
-
/* a failed salvage is still an interrupted run, not a crash */
|
|
2710
|
-
} finally {
|
|
2711
|
-
clearTimeout(grace);
|
|
2712
|
-
}
|
|
2713
|
-
}
|
|
2714
|
-
} catch (e) {
|
|
2715
|
-
crash = e instanceof Error ? e.message : String(e);
|
|
2716
|
-
} finally {
|
|
2717
|
-
clearTimeout(softTimer);
|
|
2718
|
-
clearTimeout(timer);
|
|
2719
|
-
signal?.removeEventListener("abort", abortChild);
|
|
2720
|
-
unsub?.();
|
|
2721
|
-
runningWorkers.delete(key);
|
|
2722
|
-
}
|
|
2723
|
-
const transcript = (() => { try { return child?.sessionManager.getSessionFile() ?? ""; } catch { return ""; } })();
|
|
2724
|
-
const headAfter = (await git("git rev-parse HEAD")).trim();
|
|
2725
|
-
const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
|
|
2726
|
-
const dirty = (await git("git status --short")).trim();
|
|
2727
|
-
const outcome = crash
|
|
2728
|
-
? `crashed: ${crash}`
|
|
2729
|
-
: timedOut
|
|
2730
|
-
? `interrupted at the ${budgetMin}-min budget${steered ? " (steered to wrap up at " + Math.round(WORKER_STEER_AT * 100) + "%)" : ""}${report.found ? " — REPORT salvaged after the cut, treat it as partial" : salvaged ? " — the salvage prompt got no REPORT either" : ""}`
|
|
2731
|
-
: report.found
|
|
2732
|
-
? `reported${steered ? " (after the wrap-up steer)" : ""}`
|
|
2733
|
-
: `ended without REPORT after ${nudges} nudge(s)`;
|
|
2734
|
-
// the terminal entry is what settles the Agents menu row (a persisted `running` the host
|
|
2735
|
-
// cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a ✓.
|
|
2736
|
-
if (subagent) {
|
|
2737
|
-
const doneAt = now();
|
|
2738
|
-
const final = crash
|
|
2739
|
-
? { version: 1, status: "failed", completedAt: doneAt, error: crash }
|
|
2740
|
-
: signal?.aborted || (timedOut && !report.found)
|
|
2741
|
-
? { version: 1, status: "aborted", completedAt: doneAt }
|
|
2742
|
-
: report.found
|
|
2743
|
-
? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
|
|
2744
|
-
: { version: 1, status: "failed", completedAt: doneAt, error: `ended without REPORT after ${nudges} nudge(s)`, result: report.body };
|
|
2745
|
-
piwebStamp(child?.sessionManager, PIWEB_SUBAGENT.result, final);
|
|
2746
|
-
// leave the live map only once the result entry is down: the row is never neither
|
|
2747
|
-
releaseLive(final.status);
|
|
2748
|
-
}
|
|
2749
|
-
releaseLive("failed"); // idempotent guard: a throw between claim and result must not leave a live row
|
|
2750
|
-
try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
|
|
2751
|
-
try { child?.setSessionName(`${report.found && !crash && !signal?.aborted ? (timedOut ? "◐" : "✓") : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
|
|
2752
|
-
const parts = [`${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`];
|
|
2753
|
-
let reflected: ReturnType<typeof parseReflectReport> | null = null;
|
|
2754
|
-
if (wop === "reflect") {
|
|
2755
|
-
reflected = report.found ? parseReflectReport(report.body) : null;
|
|
2756
|
-
const rows = reflected && (reflected.findings.length || reflected.open.length || /^\s*F0\b/m.test(report.body)) ? renderReflectFindings(reflected, selfRepo) : null;
|
|
2757
|
-
parts.push(rows ? rows.join("\n") : report.found ? `REPORT (rows did not parse — read them yourself):\n${report.body.slice(0, 6000)}` : `no REPORT — last words:\n${report.body}`);
|
|
2758
|
-
if (report.found) {
|
|
2759
|
-
// the record finish reads: a reflection ran for this flow (advisory — finish never blocks on it)
|
|
2760
|
-
const cur = readState(root, st.slug);
|
|
2761
|
-
if (cur) { cur.reflectedAt = now(); writeState(root, cur); }
|
|
2762
|
-
}
|
|
2763
|
-
const recurred = reflected?.open.filter((x) => x.status === "recurred").length ?? 0;
|
|
2764
|
-
const nudges = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { recurred });
|
|
2765
|
-
parts.push(
|
|
2766
|
-
"Next: show the operator this numbered list with your recommendation per item and ask fold or drop for each (one answer like 'fold 1,3 drop 2' is fine) — then STOP until they answer. " +
|
|
2767
|
-
`Fold docs → flow reflect --playbook "<note>"; fold code → flow reflect --code "<note>"; fold plugin → ${selfRepo ? 'flow reflect --code "<note>" (this is the dev-flow repo)' : 'flow reflect --plugin "<note>" prints the upstream recipe (dedupe search, then gh issue create — the fold answer is the confirmation; never a reflections.md row)'}; drop → record nothing. Open items re-checked as fixed → propose checking them off.`,
|
|
2768
|
-
);
|
|
2769
|
-
if (nudges.fix) parts.push(`${nudges.fix} — offer it after the fold/drop answer.`);
|
|
2770
|
-
if (nudges.tidy) parts.push(`${nudges.tidy} — offer it after the fold/drop answer.`);
|
|
2771
|
-
if (newCommits.trim() || dirty !== statusBefore) parts.push("note: the reflect worker changed the tree — inspect the change; it was told to write nothing");
|
|
2772
|
-
parts.push(`transcript: ${transcript || "(unknown)"}`);
|
|
2773
|
-
return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: null, commits: 0, findings: reflected?.findings.length ?? 0 } };
|
|
2774
|
-
}
|
|
2775
|
-
parts.push(
|
|
2776
|
-
report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : `no REPORT — last words:\n${report.body}`,
|
|
2777
|
-
`new commits:\n${newCommits.trim() || "(none)"}`,
|
|
2778
|
-
`uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
|
|
2779
|
-
);
|
|
2780
|
-
if (wop === "implement") {
|
|
2781
|
-
const check = await runFlow(["check"], root, uiFrom(ctx), sessFor(ctx, root));
|
|
2782
|
-
parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
|
|
2783
|
-
} else if (newCommits.trim() || dirty) {
|
|
2784
|
-
parts.push("note: the reviewer changed the tree — treat its verdict with suspicion and inspect the change");
|
|
2785
|
-
}
|
|
2786
|
-
parts.push(`transcript: ${transcript || "(unknown)"}`);
|
|
2787
|
-
parts.push(wop === "implement" ? "Next: read the report, decide what is left, and drive the gates yourself." : "Advisory review: fix what is real (inline is fine for small things), then carry on — no gate waits on this verdict.");
|
|
2788
|
-
return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
|
|
2857
|
+
return runStageWorker({ id, wop: op as WorkerOp, st, root, key, note: String(params.note ?? ""), label: params.label, budgetMin: params.budgetMin, signal, onUpdate, ctx });
|
|
2789
2858
|
},
|
|
2790
2859
|
});
|
|
2791
2860
|
pi.registerTool(stageWorkerTool);
|
|
@@ -3066,7 +3135,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
3066
3135
|
// stage (finish runs the reflection), between flows, and in status/doctor
|
|
3067
3136
|
if (state.stage === "release") {
|
|
3068
3137
|
const refl = readReflections(root);
|
|
3069
|
-
if (refl.length) guidance.push(`↻ ${refl.length} reflection(s) open —
|
|
3138
|
+
if (refl.length) guidance.push(`↻ ${refl.length} reflection(s) open — flow finish runs the closing reflection over them before cleanup; fix them only on the operator's word.`);
|
|
3070
3139
|
}
|
|
3071
3140
|
const rmap = roadmapOpenCount(readRoadmap(root));
|
|
3072
3141
|
if (rmap) guidance.push(`◇ ${rmap} roadmap item(s) open — flow roadmap lists them (pick only on the operator's word).`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.83.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": [
|
package/skills/dev-flow/SKILL.md
CHANGED
|
@@ -91,5 +91,5 @@ session's stage injection names the file to read now, and this is the map.
|
|
|
91
91
|
| `references/implement.md` | implement stage — worktree, commits, checks, tier-2 list, Verified? |
|
|
92
92
|
| `references/pre-release.md` | pre-release — `/flow-review`, docs, changelog + bump, Release? |
|
|
93
93
|
| `references/release.md` | release — PR and merge style, tag, forge release, release-done; hands over to finish |
|
|
94
|
-
| `references/finish.md` | the close-out after `release-done` — the reflect worker
|
|
94
|
+
| `references/finish.md` | the close-out after `release-done` — `flow finish` runs the reflect worker first, fold/drop (= Finish?), then the re-run cleans up |
|
|
95
95
|
| `references/reflect.md` | reflections (this project's queue; plugin feedback → upstream issues), when to fix or tidy, and the roadmap backlog |
|
|
@@ -4,10 +4,16 @@
|
|
|
4
4
|
|
|
5
5
|
## Stage: finish
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
**`flow finish` reflects before it removes anything** — it deletes
|
|
8
|
+
`.dev-flow/<slug>/` and unbinds the session, and a reflection asked for after
|
|
9
|
+
that has nothing to run against. So the first `flow finish` (with or without
|
|
10
|
+
`--confirmed`) runs the end-of-session reflection itself and stops; cleanup
|
|
11
|
+
happens on the re-run:
|
|
9
12
|
|
|
10
|
-
1. `
|
|
13
|
+
1. `flow finish [--note="<friction the operator mentioned>"]` — while no
|
|
14
|
+
reflection is recorded for the flow, it starts the reflect worker (the same
|
|
15
|
+
one `flow_stage({ op: "reflect", note })` runs — call that earlier if you
|
|
16
|
+
want, and finish skips straight to cleanup). A fresh **read-only** reviewer reads
|
|
11
17
|
this session's transcript **and every `flow_stage` worker transcript**,
|
|
12
18
|
re-checks the open items in `.dev-flow/reflections.md`, dedupes against them
|
|
13
19
|
and the upstream issues, and returns numbered findings, each classified
|
|
@@ -17,7 +23,9 @@ the session context goes with it. Run the end-of-session reflection now:
|
|
|
17
23
|
`note` = anything the operator said about friction this session. The tool
|
|
18
24
|
prebuilds a line-tagged digest of every transcript and prefetches the
|
|
19
25
|
upstream issues, so the worker reads instead of dumping and searching. If the
|
|
20
|
-
worker fails, run
|
|
26
|
+
worker fails, finish removes nothing: re-run it, or review inline (bare `flow
|
|
27
|
+
reflect` prints the protocol). Only the operator's explicit word skips the
|
|
28
|
+
reflection — `flow finish --no-reflect --confirmed`; **yolo never does**.
|
|
21
29
|
2. Show the operator the list with your recommendation per item and ask
|
|
22
30
|
**fold or drop** for each (`fold 1,3 drop 2` is a fine answer) — then stop.
|
|
23
31
|
3. Apply the answer: fold docs → `flow reflect --playbook "<note>"`; fold code →
|
|
@@ -32,8 +40,9 @@ the session context goes with it. Run the end-of-session reflection now:
|
|
|
32
40
|
|
|
33
41
|
The fold/drop answer replaces **Finish?** — act on it, then run
|
|
34
42
|
`flow finish --confirmed` without asking again. Nothing found → ask the
|
|
35
|
-
operator **Finish?** → `flow finish --confirmed`.
|
|
36
|
-
|
|
43
|
+
operator **Finish?** → `flow finish --confirmed`. Never tell the operator the
|
|
44
|
+
open items were "classified" or "reviewed" unless the worker's list is what
|
|
45
|
+
you are showing.
|
|
37
46
|
Checkpoint report: stage line **🏁 finish · `<slug>`** — release recorded ·
|
|
38
47
|
main state · unmerged count · reflections open · release-checklist open,
|
|
39
48
|
then `Done:`/`Next steps:` per the Stage reports rule.
|
|
@@ -101,7 +101,10 @@ resending the same note.
|
|
|
101
101
|
adds the facts itself: the absolute plan path, the branch's commits, the
|
|
102
102
|
uncommitted paths and the project checks. Your `note` is just the slice, plus
|
|
103
103
|
any operator answers the worker cannot see. A worker whose turn ends in prose
|
|
104
|
-
is nudged to continue, up to twice.
|
|
104
|
+
is nudged to continue, up to twice. A turn that ended in a **model error**
|
|
105
|
+
(`model failed: stopReason=error …`) is not nudged: pi already retried it, so
|
|
106
|
+
the model is down, not slow. Take the slice or review inline, or retry the
|
|
107
|
+
delegation once the provider answers again. On return the tool reruns `flow check` and
|
|
105
108
|
lists the new commits and anything uncommitted.
|
|
106
109
|
- `flow_stage({ op: "review", note })` — a fresh **read-only** reviewer (at
|
|
107
110
|
implement or pre-release): findings plus `verdict: PASS|FAIL`. It is advisory:
|
|
@@ -33,8 +33,9 @@ flagged by `flow doctor` / `reflect list`: file it upstream and check it off
|
|
|
33
33
|
prints an investigation brief without queueing.
|
|
34
34
|
|
|
35
35
|
- Reflect real friction only, one line each, never the same issue twice.
|
|
36
|
-
- **The end-of-session reflection runs at finish** (see Stage: finish):
|
|
37
|
-
`flow_stage({ op: "reflect" })` worker
|
|
36
|
+
- **The end-of-session reflection runs at finish** (see Stage: finish): `flow
|
|
37
|
+
finish` itself starts the `flow_stage({ op: "reflect" })` worker before it
|
|
38
|
+
removes anything (only `--no-reflect --confirmed` skips it); the worker reviews the whole session — driver and
|
|
38
39
|
every worker transcript — and the operator decides **fold or drop** per
|
|
39
40
|
finding. Bare `flow reflect` prints that protocol (bound: delegate to the
|
|
40
41
|
worker; unbound: review inline); the command writes nothing.
|
|
@@ -64,4 +64,5 @@ the worktree unless noted:
|
|
|
64
64
|
|
|
65
65
|
|
|
66
66
|
Once `flow release-done` has recorded the release, the playbook continues in
|
|
67
|
-
[finish.md](finish.md) —
|
|
67
|
+
[finish.md](finish.md) — `flow finish` runs the closing reflection first and stops for
|
|
68
|
+
fold/drop (that answer is **Finish?**); its re-run with `--confirmed` cleans up.
|
package/src/core.ts
CHANGED
|
@@ -49,7 +49,7 @@ export interface FlowState {
|
|
|
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
50
|
releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
|
|
51
51
|
verifiedHead?: string; // HEAD the operator's Verified? was given over — release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
|
|
52
|
-
reflectedAt?: string; // a
|
|
52
|
+
reflectedAt?: string; // a reflect worker reported for this flow — finish runs one first while this is unset (only --no-reflect --confirmed skips it)
|
|
53
53
|
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
|
|
54
54
|
}
|
|
55
55
|
|
|
@@ -2115,7 +2115,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
2115
2115
|
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`;
|
|
2116
2116
|
case "release":
|
|
2117
2117
|
return state.approvals.release
|
|
2118
|
-
? "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),
|
|
2118
|
+
? "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), then run flow finish: it runs the closing reflection first and stops for the operator's fold/drop (that answer is Finish?) — the re-run with --confirmed removes worktree, branch and .dev-flow/" + state.slug + "/"
|
|
2119
2119
|
: state.noVersion
|
|
2120
2120
|
? `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)`
|
|
2121
2121
|
: `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)`;
|
|
@@ -2286,6 +2286,18 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
|
|
|
2286
2286
|
return [...head, ...contract].join("\n");
|
|
2287
2287
|
}
|
|
2288
2288
|
|
|
2289
|
+
/** A worker turn that ended in a model error (gh#173): the newest assistant message has stopReason
|
|
2290
|
+
* "error". pi has already auto-retried inside the prompt by then, so this is a dead model, not a stall —
|
|
2291
|
+
* nudging it only buys another retry storm. `streak` counts the consecutive trailing error turns. */
|
|
2292
|
+
export function workerTurnError(messages: readonly unknown[]): { reason: string; message: string; streak: number } | null {
|
|
2293
|
+
const turns = messages.filter((m): m is { role: string; stopReason?: string; errorMessage?: string } => !!m && typeof m === "object" && (m as { role?: unknown }).role === "assistant");
|
|
2294
|
+
const last = turns.at(-1);
|
|
2295
|
+
if (!last || last.stopReason !== "error") return null;
|
|
2296
|
+
let streak = 0;
|
|
2297
|
+
for (let i = turns.length - 1; i >= 0 && turns[i].stopReason === "error"; i--) streak++;
|
|
2298
|
+
return { reason: last.stopReason, message: String(last.errorMessage ?? "").trim() || "(no error message)", streak };
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2289
2301
|
/** The REPORT section of a worker's final message: everything after the last `REPORT` heading line. */
|
|
2290
2302
|
export function parseWorkerReport(text: string): { found: boolean; body: string; verdict: "PASS" | "FAIL" | null } {
|
|
2291
2303
|
const lines = (text ?? "").split("\n");
|