pi-dev-flow 0.82.0 β†’ 0.83.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md 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.0] - 2026-11-05
8
+
9
+ **`flow finish` reflects before it cleans up, so a session's review can no longer be lost.**
10
+
11
+ ### Fixed
12
+ - **`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.
13
+
14
+ ## [0.82.1] - 2026-11-05
15
+
16
+ **pi-web shows one dev-flow chip per session again.**
17
+
18
+ ### Fixed
19
+ - **A stage change no longer leaves the previous stage's chip behind in pi-web.** The chip's label is its widget key, and the "previous key" to clear on repaint was one slot for the whole server process; when another session (a chat, a worker) repainted in between, the next repaint cleared that session's key instead, so e.g. `πŸ”¨telegram-settings` stayed beside `πŸš€telegram-settings`. The previous key is now kept per session (and survives `/reload`); a session's slot is dropped at shutdown.
20
+
7
21
  ## [0.82.0] - 2026-11-05
8
22
 
9
23
  **A feature split off mid-flow is parked in the roadmap with its notes, and a hand-made feature dir can be adopted instead of deleted.**
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.** `flow_stage` op `reflect` starts a fresh
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** (`flow_stage` op `reflect`) reviews the whole session β€” the
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
@@ -384,7 +384,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
384
384
  }
385
385
 
386
386
  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)";
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] [--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
388
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
389
389
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
390
390
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -996,8 +996,13 @@ function reflectTidy(root: string): RunResult {
996
996
  return { text: `reflections: dropped ${closed} closed item(s) β€” ${open} open` };
997
997
  }
998
998
 
999
+ /** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
1000
+ export interface FlowHooks {
1001
+ reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean }>;
1002
+ }
1003
+
999
1004
  /** 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> {
1005
+ async function runFlow(args: string[], root: string, ui: Ui, sess: Session, hooks: FlowHooks = {}): Promise<RunResult> {
1001
1006
  const [sub = "status", ...rest] = args;
1002
1007
  // help and version are questions about the plugin, not the repo: answerable with no .dev-flow/ at all
1003
1008
  if (sub === "help" || sub === "--help" || sub === "-h") return { text: rest.includes("--json") ? gateHelpJson(GATE_HELP, loadedVersion()) : `usage: flow <sub> β€” ${GATE_HELP}` };
@@ -1013,7 +1018,7 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
1013
1018
  return null;
1014
1019
  };
1015
1020
  const slugArg = rest.find((a) => !a.startsWith("--"));
1016
- const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord };
1021
+ const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord, hooks };
1017
1022
 
1018
1023
  switch (sub) {
1019
1024
  case "init":
@@ -1539,19 +1544,38 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1539
1544
  }
1540
1545
  // 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
1546
  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
1547
  // the one finish question β€” asked after the safety checks so it can never be a wasted question
1545
1548
  // yolo works uniformly at every gate: at Finish? nothing later remains to pre-confirm, the flag just answers this one
1546
1549
  const yoloWord = takeYoloWord(state!);
1547
1550
  if (yoloWord) return { text: yoloWord, isError: true };
1551
+ // The closing reflection runs here, before anything is removed: the worker reads this session's
1552
+ // transcripts and .dev-flow/<slug>/tmp, and finish is about to drop that folder and the binding β€” a
1553
+ // reflection asked for after finish has nothing bound to run against. Only the operator's explicit
1554
+ // --no-reflect skips it; yolo never does (it answers checkpoints, it does not waive the review).
1555
+ const skipReflect = flag("no-reflect");
1556
+ 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 };
1557
+ if (!state!.reflectedAt && !skipReflect) {
1558
+ const skipHint = "or β€” only on the operator's explicit word β€” flow finish --no-reflect --confirmed";
1559
+ 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 };
1560
+ const r = await o.hooks.reflect(state!, flagValue(o.rest, "note") ?? "");
1561
+ const cur = readState(root, state!.slug) ?? state!; // the worker stamped reflectedAt on disk
1562
+ if (!r.recorded)
1563
+ 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 };
1564
+ if (!r.findings) {
1565
+ markPendingAsk(root, cur, "Finish?");
1566
+ 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 };
1567
+ }
1568
+ markPendingAsk(root, cur, "Fold or drop?");
1569
+ 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 };
1570
+ }
1571
+ const reflectSkipNote = skipReflect && !state!.reflectedAt ? ` Reflection skipped on the operator's word β€” nothing re-checked this session or the open reflections.` : "";
1548
1572
  const askPending = !flag("confirmed") && !state!.yolo;
1549
1573
  if (askPending) {
1550
1574
  markPendingAsk(root, state!, "Finish?");
1551
1575
  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}${reflectSkipNote}`, "Finish?"), isError: true };
1576
+ 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
1577
  }
1554
- const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote}${reflectSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1578
+ const ok = await ui.confirm("Finish feature", `Finish ${state!.slug}?${unmergedNote}${forgeSkipNote} Removes worktree, branch ${state!.branch || "-"} and .dev-flow/${state!.slug}/.`);
1555
1579
  if (!ok) {
1556
1580
  delete state!.pendingAsk;
1557
1581
  writeState(root, state!);
@@ -1601,7 +1625,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
1601
1625
  // finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
1602
1626
  const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
1603
1627
  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.` };
1628
+ 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
1629
  }
1606
1630
 
1607
1631
  /** The main-branch guard as a hook body β€” installed into .git/hooks, or printed for a hook manager to carry. */
@@ -2090,6 +2114,7 @@ interface GateCtx {
2090
2114
  flag: (name: string) => boolean;
2091
2115
  slugArg?: string;
2092
2116
  takeYoloWord: (state: FlowState) => string | null;
2117
+ hooks: FlowHooks;
2093
2118
  }
2094
2119
 
2095
2120
  async function gateVersion(o: GateCtx): Promise<RunResult> {
@@ -2413,9 +2438,12 @@ function tail(out: string, n = 15): string {
2413
2438
 
2414
2439
  // ------------------------------------------------------------------ extension
2415
2440
 
2416
- /** The pi-web chip's current key: the chip's label IS the widget key, so it changes with the footer text
2417
- * and the previous one must be cleared on every repaint. */
2418
- let webChipKey: string | undefined;
2441
+ /** The pi-web chip's current key, per session: the chip's label IS the widget key, so it changes with the
2442
+ * footer text and the previous one must be cleared on every repaint. Per session, not per process β€” one
2443
+ * pi-web server repaints many sessions (drivers, chats, workers), and a single shared slot let session B's
2444
+ * repaint overwrite A's key, so A's next repaint cleared a key A never had and left its old chip beside
2445
+ * the new one. On globalThis so a /reload or a duplicate copy still knows the chip already painted. */
2446
+ const WEB_CHIP_KEYS: Map<string, string> = ((globalThis as { __piDevFlowChipKeys?: Map<string, string> }).__piDevFlowChipKeys ??= new Map());
2419
2447
 
2420
2448
  /** Compact footer: bound flow = stage glyph, slug, mode markers, ⚠️ on its failing checks; unbound = the
2421
2449
  * unfinished-flow count, or `πŸ’¬ no flows` β€” an initiated repo always carries the footer. An uninitiated
@@ -2425,10 +2453,15 @@ let webChipKey: string | undefined;
2425
2453
  function refreshStatus(ctx: ExtensionContext, root: string): void {
2426
2454
  if (!ctx.hasUI) return;
2427
2455
  const web = ctx.mode !== "tui";
2456
+ const sk = sessionKey(ctx);
2428
2457
  const setChip = (key: string | undefined, lines?: string[]) => {
2429
- if (webChipKey !== undefined && webChipKey !== key) ctx.ui.setWidget(webChipKey, undefined);
2430
- webChipKey = key;
2431
- if (key !== undefined) ctx.ui.setWidget(key, lines);
2458
+ const prev = WEB_CHIP_KEYS.get(sk);
2459
+ if (prev !== undefined && prev !== key) ctx.ui.setWidget(prev, undefined);
2460
+ if (key === undefined) WEB_CHIP_KEYS.delete(sk);
2461
+ else {
2462
+ WEB_CHIP_KEYS.set(sk, key);
2463
+ ctx.ui.setWidget(key, lines);
2464
+ }
2432
2465
  };
2433
2466
  if (!initiated(root)) {
2434
2467
  ctx.ui.setStatus("dev-flow", undefined);
@@ -2542,7 +2575,7 @@ export default function devFlow(pi: ExtensionAPI) {
2542
2575
  handler: async (args, ctx) => {
2543
2576
  const cmd = parse(args);
2544
2577
  const root = await flowRoot(ctx.cwd);
2545
- const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root));
2578
+ const res = await runFlow(cmd, root, uiFrom(ctx), sessFor(ctx, root), finishReflectHook("flow-finish", ctx, root));
2546
2579
  // gate output belongs to the conversation, not a toast: display:true renders a [flow] box (TUI + web), no triggerTurn so no model turn fires.
2547
2580
  // bare reflect is the exception: its whole output is instructions for the agent β€” displayed without a turn, they would never execute.
2548
2581
  const wake = cmd.length === 1 && cmd[0] === "reflect";
@@ -2560,9 +2593,9 @@ export default function devFlow(pi: ExtensionAPI) {
2560
2593
  parameters: Type.Object({
2561
2594
  args: Type.Array(Type.String(), { description: 'Gate invocation, e.g. ["status"] or ["start", "my-slug"]' }),
2562
2595
  }),
2563
- execute: async (_id, params, _signal, _onUpdate, ctx) => {
2596
+ execute: async (id, params, signal, onUpdate, ctx) => {
2564
2597
  const root = await flowRoot(ctx.cwd);
2565
- const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root));
2598
+ const res = await runFlow(params.args, root, uiFrom(ctx), sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
2566
2599
  if (!res.isError) maybeCompactNow(ctx, root);
2567
2600
  return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
2568
2601
  },
@@ -2572,12 +2605,226 @@ export default function devFlow(pi: ExtensionAPI) {
2572
2605
  /** Driver sessions with a worker running right now β€” one worker per session at a time. */
2573
2606
  const runningWorkers = new Set<string>();
2574
2607
 
2608
+ type WorkerResult = { content: { type: "text"; text: string }[]; details: { op: WorkerOp; outcome: string; verdict: string | null; commits: number; findings?: number; recorded?: boolean } | undefined; isError?: boolean };
2609
+
2610
+ /** One fresh-session worker run for a bound flow β€” the body of flow_stage, shared with flow finish,
2611
+ * which runs the closing reflection itself before it removes anything (the worker reads the session
2612
+ * transcripts and .dev-flow/<slug>/tmp, which finish deletes, and the binding finish drops). */
2613
+ async function runStageWorker(a: {
2614
+ id: string;
2615
+ wop: WorkerOp;
2616
+ st: FlowState;
2617
+ root: string;
2618
+ key: string;
2619
+ note: string;
2620
+ label?: string;
2621
+ budgetMin?: number;
2622
+ signal?: AbortSignal;
2623
+ onUpdate?: (u: { content: { type: "text"; text: string }[]; details: unknown }) => void;
2624
+ ctx: ExtensionContext;
2625
+ }): Promise<WorkerResult> {
2626
+ const { id, wop, st, root, key, signal, onUpdate, ctx } = a;
2627
+ const params = { note: a.note, label: a.label, budgetMin: a.budgetMin };
2628
+ const err = (text: string): WorkerResult => ({ content: [{ type: "text" as const, text }], details: undefined, isError: true });
2629
+ // a reflection reviews transcripts, not the branch: it runs in the main checkout, where the
2630
+ // worktree may already be gone at finish time
2631
+ const work = wop === "reflect" ? root : worktreeAbs(root, st);
2632
+ if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk β€” nothing for a worker to work in`);
2633
+ if (runningWorkers.has(key)) return err("a worker is already running for this session β€” wait for it to return");
2634
+ runningWorkers.add(key);
2635
+ const cfg = loadProject(dfDir(root)).cfg;
2636
+ const budgetMin = clampBudgetMin(params.budgetMin, wop);
2637
+ const glyph = wop === "implement" ? "πŸ”¨" : wop === "review" ? "πŸ”" : "πŸͺž";
2638
+ const name = workerName(glyph, st.slug, wop, params.label);
2639
+ const started = Date.now();
2640
+ const git = async (cmd: string) => { const r = await sh(cmd, work); return r.ok ? r.out : ""; };
2641
+ const headBefore = (await git("git rev-parse HEAD")).trim();
2642
+ // the reflect worker runs in the main checkout, which may already carry the operator's edits
2643
+ const statusBefore = wop === "reflect" ? (await git("git status --short")).trim() : "";
2644
+ let lineage: { id?: string; file?: string; dir?: string } = {};
2645
+ try { lineage = { id: ctx.sessionManager.getSessionId(), file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
2646
+ const selfRepo = isSelfRepo(root);
2647
+ const brief =
2648
+ wop === "reflect"
2649
+ ? await (async () => {
2650
+ const items = readReflections(root);
2651
+ const fold = await foldView(root, items);
2652
+ const upstream = await pluginUpstream(root);
2653
+ const children = lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [];
2654
+ return buildReflectBrief({
2655
+ slug: st.slug, root, today: now().slice(0, 10),
2656
+ driverFile: lineage.file ?? null,
2657
+ children,
2658
+ digests: lineage.file ? writeTranscriptDigests(root, st.slug, [lineage.file, ...children.map((c) => c.file)]) : [],
2659
+ upstreamIssues: (await reflectSeams.upstreamIssues(root, upstream)) ?? undefined,
2660
+ budgetMin,
2661
+ reflectionsFile: path.join(dfDir(root), "reflections.md"),
2662
+ items,
2663
+ projectMd: path.join(dfDir(root), "project.md"),
2664
+ version: pluginVersion(import.meta.dirname).version,
2665
+ upstream,
2666
+ selfRepo,
2667
+ projectIssues: fold.state === "ok" && !selfRepo ? { repo: fold.slug, issues: fold.result.upstreamOnly.map((i) => ({ number: i.number, title: i.title })) } : undefined,
2668
+ note: String(params.note ?? ""),
2669
+ });
2670
+ })()
2671
+ : buildWorkerBrief({
2672
+ op: wop, slug: st.slug, workDir: work,
2673
+ planFile: ((f) => (existsSync(f) ? f : null))(path.join(featDir(root, st.slug), "plan", "plan.md")),
2674
+ defaultBranch: cfg.defaultBranch,
2675
+ commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
2676
+ status: await git("git status --short"),
2677
+ checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
2678
+ note: String(params.note ?? ""),
2679
+ });
2680
+ // pi-web visibility needs both halves of the lineage: the id the Agents menu links the child
2681
+ // to, the file the parentSession header points at β€” without either the worker stays unlinked.
2682
+ const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
2683
+ let child: AgentSession | undefined;
2684
+ let timedOut = false;
2685
+ let steered = false;
2686
+ let salvaged = false;
2687
+ let crash: string | null = null;
2688
+ let nudges = 0;
2689
+ let report = parseWorkerReport("");
2690
+ const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2691
+ const hardMs = workerTiming.hardMs ?? budgetMin * 60_000;
2692
+ // grace before the cliff (gh#142): steered at 75% to wrap up, so a long run hands back a REPORT
2693
+ // instead of being cut mid-thought β€” the hard timer stays the backstop
2694
+ const softTimer = setTimeout(() => {
2695
+ steered = true;
2696
+ try { void Promise.resolve(child?.steer(workerSteer(wop, budgetMin))).catch(() => {}); } catch { /* the hard cut follows */ }
2697
+ }, workerTiming.softMs ?? Math.round(hardMs * WORKER_STEER_AT));
2698
+ const timer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2699
+ signal?.addEventListener("abort", abortChild);
2700
+ let unsub: (() => void) | undefined;
2701
+ let releaseLive: (status: string) => void = () => {};
2702
+ try {
2703
+ child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir, subagent });
2704
+ if (subagent) {
2705
+ piwebStamp(child.sessionManager, PIWEB_SUBAGENT.status, { version: 1, status: "running" });
2706
+ releaseLive = piwebLiveClaim(child.sessionManager, subagent);
2707
+ }
2708
+ unsub = child.subscribe((ev: unknown) => {
2709
+ const e = ev as { type?: string; toolName?: string };
2710
+ if (e.type === "tool_execution_start") {
2711
+ const min = Math.floor((Date.now() - started) / 60_000);
2712
+ onUpdate?.({ content: [{ type: "text", text: `⏳ ${name} β€” ${min}/${budgetMin} min Β· ${e.toolName ?? "?"}` }], details: { running: true } });
2713
+ }
2714
+ });
2715
+ await child.prompt(brief);
2716
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2717
+ // a turn that ends in prose ("now let me write D4…") ends the session: tell it to keep going
2718
+ while (!report.found && !timedOut && !signal?.aborted && nudges < WORKER_NUDGES) {
2719
+ nudges++;
2720
+ await child.prompt(wop === "implement" ? WORKER_NUDGE : WORKER_NUDGE_READONLY);
2721
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2722
+ }
2723
+ // cut at the budget without a REPORT: one short, tool-less turn to hand back what it found β€”
2724
+ // an aborted reflection otherwise loses every finding it had already made
2725
+ if (!report.found && timedOut && !signal?.aborted) {
2726
+ salvaged = true;
2727
+ const grace = setTimeout(abortChild, workerTiming.graceMs ?? WORKER_SALVAGE_MS);
2728
+ try {
2729
+ await child.prompt(WORKER_SALVAGE);
2730
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2731
+ } catch {
2732
+ /* a failed salvage is still an interrupted run, not a crash */
2733
+ } finally {
2734
+ clearTimeout(grace);
2735
+ }
2736
+ }
2737
+ } catch (e) {
2738
+ crash = e instanceof Error ? e.message : String(e);
2739
+ } finally {
2740
+ clearTimeout(softTimer);
2741
+ clearTimeout(timer);
2742
+ signal?.removeEventListener("abort", abortChild);
2743
+ unsub?.();
2744
+ runningWorkers.delete(key);
2745
+ }
2746
+ const transcript = (() => { try { return child?.sessionManager.getSessionFile() ?? ""; } catch { return ""; } })();
2747
+ const headAfter = (await git("git rev-parse HEAD")).trim();
2748
+ const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
2749
+ const dirty = (await git("git status --short")).trim();
2750
+ const outcome = crash
2751
+ ? `crashed: ${crash}`
2752
+ : timedOut
2753
+ ? `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" : ""}`
2754
+ : report.found
2755
+ ? `reported${steered ? " (after the wrap-up steer)" : ""}`
2756
+ : `ended without REPORT after ${nudges} nudge(s)`;
2757
+ // the terminal entry is what settles the Agents menu row (a persisted `running` the host
2758
+ // cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a βœ“.
2759
+ if (subagent) {
2760
+ const doneAt = now();
2761
+ const final = crash
2762
+ ? { version: 1, status: "failed", completedAt: doneAt, error: crash }
2763
+ : signal?.aborted || (timedOut && !report.found)
2764
+ ? { version: 1, status: "aborted", completedAt: doneAt }
2765
+ : report.found
2766
+ ? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
2767
+ : { version: 1, status: "failed", completedAt: doneAt, error: `ended without REPORT after ${nudges} nudge(s)`, result: report.body };
2768
+ piwebStamp(child?.sessionManager, PIWEB_SUBAGENT.result, final);
2769
+ // leave the live map only once the result entry is down: the row is never neither
2770
+ releaseLive(final.status);
2771
+ }
2772
+ releaseLive("failed"); // idempotent guard: a throw between claim and result must not leave a live row
2773
+ try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
2774
+ try { child?.setSessionName(`${report.found && !crash && !signal?.aborted ? (timedOut ? "◐" : "βœ“") : "βœ—"} ${name}${report.verdict ? ` Β· ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2775
+ const parts = [`${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`];
2776
+ let reflected: ReturnType<typeof parseReflectReport> | null = null;
2777
+ if (wop === "reflect") {
2778
+ reflected = report.found ? parseReflectReport(report.body) : null;
2779
+ const rows = reflected && (reflected.findings.length || reflected.open.length || /^\s*F0\b/m.test(report.body)) ? renderReflectFindings(reflected, selfRepo) : null;
2780
+ 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}`);
2781
+ if (report.found) {
2782
+ // the record finish reads: a reflection ran for this flow, so finish goes on to its cleanup
2783
+ const cur = readState(root, st.slug);
2784
+ if (cur) { cur.reflectedAt = now(); writeState(root, cur); }
2785
+ }
2786
+ const recurred = reflected?.open.filter((x) => x.status === "recurred").length ?? 0;
2787
+ const nudges = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { recurred });
2788
+ parts.push(
2789
+ "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. " +
2790
+ `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.`,
2791
+ );
2792
+ if (nudges.fix) parts.push(`${nudges.fix} β€” offer it after the fold/drop answer.`);
2793
+ if (nudges.tidy) parts.push(`${nudges.tidy} β€” offer it after the fold/drop answer.`);
2794
+ if (newCommits.trim() || dirty !== statusBefore) parts.push("note: the reflect worker changed the tree β€” inspect the change; it was told to write nothing");
2795
+ parts.push(`transcript: ${transcript || "(unknown)"}`);
2796
+ 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 } };
2797
+ }
2798
+ parts.push(
2799
+ report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : `no REPORT β€” last words:\n${report.body}`,
2800
+ `new commits:\n${newCommits.trim() || "(none)"}`,
2801
+ `uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
2802
+ );
2803
+ if (wop === "implement") {
2804
+ const check = await runFlow(["check"], root, uiFrom(ctx), sessFor(ctx, root));
2805
+ parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
2806
+ } else if (newCommits.trim() || dirty) {
2807
+ parts.push("note: the reviewer changed the tree β€” treat its verdict with suspicion and inspect the change");
2808
+ }
2809
+ parts.push(`transcript: ${transcript || "(unknown)"}`);
2810
+ 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.");
2811
+ return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
2812
+ }
2813
+
2814
+ /** The hook flow finish calls for its closing reflection: the same reflect worker flow_stage runs. */
2815
+ const finishReflectHook = (id: string, ctx: ExtensionContext, root: string, signal?: AbortSignal, onUpdate?: (u: { content: { type: "text"; text: string }[]; details: unknown }) => void): FlowHooks => ({
2816
+ reflect: async (st, note) => {
2817
+ const r = await runStageWorker({ id, wop: "reflect", st, root, key: sessionKey(ctx), note, label: "finish reflection", signal, onUpdate, ctx });
2818
+ return { text: r.content.map((c) => c.text).join("\n"), recorded: !!r.details?.recorded, findings: r.details?.findings ?? 0, failed: !!r.isError };
2819
+ },
2820
+ });
2821
+
2575
2822
  const stageWorkerTool = defineTool({
2576
2823
  name: "flow_stage",
2577
2824
  label: "Stage worker",
2578
2825
  description:
2579
- '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, standard at finish) β€” 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.',
2580
- promptSnippet: 'flow_stage(op: "implement"|"review"|"reflect", note, label?) β€” optional fresh-session worker for a big implement slice, an independent review, or the end-of-session reflection (finish); gates stay with you; in pi-web workers show up as subagents in the Agents menu',
2826
+ '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.',
2827
+ 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',
2581
2828
  parameters: Type.Object({
2582
2829
  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)' }),
2583
2830
  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." }),
@@ -2594,190 +2841,7 @@ export default function devFlow(pi: ExtensionAPI) {
2594
2841
  if (!st) return err("this session is not bound to a feature β€” flow start <slug> or flow use <slug> first");
2595
2842
  const why = workerOpError(op, st.stage);
2596
2843
  if (why) return err(why);
2597
- const wop = op as WorkerOp;
2598
- // a reflection reviews transcripts, not the branch: it runs in the main checkout, where the
2599
- // worktree may already be gone at finish time
2600
- const work = wop === "reflect" ? root : worktreeAbs(root, st);
2601
- if (!work || !existsSync(work)) return err(`feature ${st.slug} has no worktree on disk β€” nothing for a worker to work in`);
2602
- if (runningWorkers.has(key)) return err("a worker is already running for this session β€” wait for it to return");
2603
- runningWorkers.add(key);
2604
- const cfg = loadProject(dfDir(root)).cfg;
2605
- const budgetMin = clampBudgetMin(params.budgetMin, wop);
2606
- const glyph = wop === "implement" ? "πŸ”¨" : wop === "review" ? "πŸ”" : "πŸͺž";
2607
- const name = workerName(glyph, st.slug, wop, params.label);
2608
- const started = Date.now();
2609
- const git = async (cmd: string) => { const r = await sh(cmd, work); return r.ok ? r.out : ""; };
2610
- const headBefore = (await git("git rev-parse HEAD")).trim();
2611
- // the reflect worker runs in the main checkout, which may already carry the operator's edits
2612
- const statusBefore = wop === "reflect" ? (await git("git status --short")).trim() : "";
2613
- let lineage: { id?: string; file?: string; dir?: string } = {};
2614
- try { lineage = { id: ctx.sessionManager.getSessionId(), file: ctx.sessionManager.getSessionFile() ?? undefined, dir: ctx.sessionManager.getSessionDir() ?? undefined }; } catch { /* unbacked driver: the worker is unlinked */ }
2615
- const selfRepo = isSelfRepo(root);
2616
- const brief =
2617
- wop === "reflect"
2618
- ? await (async () => {
2619
- const items = readReflections(root);
2620
- const fold = await foldView(root, items);
2621
- const upstream = await pluginUpstream(root);
2622
- const children = lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [];
2623
- return buildReflectBrief({
2624
- slug: st.slug, root, today: now().slice(0, 10),
2625
- driverFile: lineage.file ?? null,
2626
- children,
2627
- digests: lineage.file ? writeTranscriptDigests(root, st.slug, [lineage.file, ...children.map((c) => c.file)]) : [],
2628
- upstreamIssues: (await reflectSeams.upstreamIssues(root, upstream)) ?? undefined,
2629
- budgetMin,
2630
- reflectionsFile: path.join(dfDir(root), "reflections.md"),
2631
- items,
2632
- projectMd: path.join(dfDir(root), "project.md"),
2633
- version: pluginVersion(import.meta.dirname).version,
2634
- upstream,
2635
- selfRepo,
2636
- projectIssues: fold.state === "ok" && !selfRepo ? { repo: fold.slug, issues: fold.result.upstreamOnly.map((i) => ({ number: i.number, title: i.title })) } : undefined,
2637
- note: String(params.note ?? ""),
2638
- });
2639
- })()
2640
- : buildWorkerBrief({
2641
- op: wop, slug: st.slug, workDir: work,
2642
- planFile: ((f) => (existsSync(f) ? f : null))(path.join(featDir(root, st.slug), "plan", "plan.md")),
2643
- defaultBranch: cfg.defaultBranch,
2644
- commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
2645
- status: await git("git status --short"),
2646
- checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
2647
- note: String(params.note ?? ""),
2648
- });
2649
- // pi-web visibility needs both halves of the lineage: the id the Agents menu links the child
2650
- // to, the file the parentSession header points at β€” without either the worker stays unlinked.
2651
- const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
2652
- let child: AgentSession | undefined;
2653
- let timedOut = false;
2654
- let steered = false;
2655
- let salvaged = false;
2656
- let crash: string | null = null;
2657
- let nudges = 0;
2658
- let report = parseWorkerReport("");
2659
- const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2660
- const hardMs = workerTiming.hardMs ?? budgetMin * 60_000;
2661
- // grace before the cliff (gh#142): steered at 75% to wrap up, so a long run hands back a REPORT
2662
- // instead of being cut mid-thought β€” the hard timer stays the backstop
2663
- const softTimer = setTimeout(() => {
2664
- steered = true;
2665
- try { void Promise.resolve(child?.steer(workerSteer(wop, budgetMin))).catch(() => {}); } catch { /* the hard cut follows */ }
2666
- }, workerTiming.softMs ?? Math.round(hardMs * WORKER_STEER_AT));
2667
- const timer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2668
- signal?.addEventListener("abort", abortChild);
2669
- let unsub: (() => void) | undefined;
2670
- let releaseLive: (status: string) => void = () => {};
2671
- try {
2672
- child = await stageWorkerSpawn.run({ work, model: ctx.model, name: `⏳ ${name}`, tools: WORKER_TOOLS[wop], parent: lineage.file, dir: lineage.dir, subagent });
2673
- if (subagent) {
2674
- piwebStamp(child.sessionManager, PIWEB_SUBAGENT.status, { version: 1, status: "running" });
2675
- releaseLive = piwebLiveClaim(child.sessionManager, subagent);
2676
- }
2677
- unsub = child.subscribe((ev: unknown) => {
2678
- const e = ev as { type?: string; toolName?: string };
2679
- if (e.type === "tool_execution_start") {
2680
- const min = Math.floor((Date.now() - started) / 60_000);
2681
- onUpdate?.({ content: [{ type: "text", text: `⏳ ${name} β€” ${min}/${budgetMin} min Β· ${e.toolName ?? "?"}` }], details: { running: true } });
2682
- }
2683
- });
2684
- await child.prompt(brief);
2685
- report = parseWorkerReport(child.getLastAssistantText() ?? "");
2686
- // a turn that ends in prose ("now let me write D4…") ends the session: tell it to keep going
2687
- while (!report.found && !timedOut && !signal?.aborted && nudges < WORKER_NUDGES) {
2688
- nudges++;
2689
- await child.prompt(wop === "implement" ? WORKER_NUDGE : WORKER_NUDGE_READONLY);
2690
- report = parseWorkerReport(child.getLastAssistantText() ?? "");
2691
- }
2692
- // cut at the budget without a REPORT: one short, tool-less turn to hand back what it found β€”
2693
- // an aborted reflection otherwise loses every finding it had already made
2694
- if (!report.found && timedOut && !signal?.aborted) {
2695
- salvaged = true;
2696
- const grace = setTimeout(abortChild, workerTiming.graceMs ?? WORKER_SALVAGE_MS);
2697
- try {
2698
- await child.prompt(WORKER_SALVAGE);
2699
- report = parseWorkerReport(child.getLastAssistantText() ?? "");
2700
- } catch {
2701
- /* a failed salvage is still an interrupted run, not a crash */
2702
- } finally {
2703
- clearTimeout(grace);
2704
- }
2705
- }
2706
- } catch (e) {
2707
- crash = e instanceof Error ? e.message : String(e);
2708
- } finally {
2709
- clearTimeout(softTimer);
2710
- clearTimeout(timer);
2711
- signal?.removeEventListener("abort", abortChild);
2712
- unsub?.();
2713
- runningWorkers.delete(key);
2714
- }
2715
- const transcript = (() => { try { return child?.sessionManager.getSessionFile() ?? ""; } catch { return ""; } })();
2716
- const headAfter = (await git("git rev-parse HEAD")).trim();
2717
- const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
2718
- const dirty = (await git("git status --short")).trim();
2719
- const outcome = crash
2720
- ? `crashed: ${crash}`
2721
- : timedOut
2722
- ? `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" : ""}`
2723
- : report.found
2724
- ? `reported${steered ? " (after the wrap-up steer)" : ""}`
2725
- : `ended without REPORT after ${nudges} nudge(s)`;
2726
- // the terminal entry is what settles the Agents menu row (a persisted `running` the host
2727
- // cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a βœ“.
2728
- if (subagent) {
2729
- const doneAt = now();
2730
- const final = crash
2731
- ? { version: 1, status: "failed", completedAt: doneAt, error: crash }
2732
- : signal?.aborted || (timedOut && !report.found)
2733
- ? { version: 1, status: "aborted", completedAt: doneAt }
2734
- : report.found
2735
- ? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
2736
- : { version: 1, status: "failed", completedAt: doneAt, error: `ended without REPORT after ${nudges} nudge(s)`, result: report.body };
2737
- piwebStamp(child?.sessionManager, PIWEB_SUBAGENT.result, final);
2738
- // leave the live map only once the result entry is down: the row is never neither
2739
- releaseLive(final.status);
2740
- }
2741
- releaseLive("failed"); // idempotent guard: a throw between claim and result must not leave a live row
2742
- try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
2743
- try { child?.setSessionName(`${report.found && !crash && !signal?.aborted ? (timedOut ? "◐" : "βœ“") : "βœ—"} ${name}${report.verdict ? ` Β· ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2744
- const parts = [`${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`];
2745
- let reflected: ReturnType<typeof parseReflectReport> | null = null;
2746
- if (wop === "reflect") {
2747
- reflected = report.found ? parseReflectReport(report.body) : null;
2748
- const rows = reflected && (reflected.findings.length || reflected.open.length || /^\s*F0\b/m.test(report.body)) ? renderReflectFindings(reflected, selfRepo) : null;
2749
- 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}`);
2750
- if (report.found) {
2751
- // the record finish reads: a reflection ran for this flow (advisory β€” finish never blocks on it)
2752
- const cur = readState(root, st.slug);
2753
- if (cur) { cur.reflectedAt = now(); writeState(root, cur); }
2754
- }
2755
- const recurred = reflected?.open.filter((x) => x.status === "recurred").length ?? 0;
2756
- const nudges = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { recurred });
2757
- parts.push(
2758
- "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. " +
2759
- `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.`,
2760
- );
2761
- if (nudges.fix) parts.push(`${nudges.fix} β€” offer it after the fold/drop answer.`);
2762
- if (nudges.tidy) parts.push(`${nudges.tidy} β€” offer it after the fold/drop answer.`);
2763
- if (newCommits.trim() || dirty !== statusBefore) parts.push("note: the reflect worker changed the tree β€” inspect the change; it was told to write nothing");
2764
- parts.push(`transcript: ${transcript || "(unknown)"}`);
2765
- return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: null, commits: 0, findings: reflected?.findings.length ?? 0 } };
2766
- }
2767
- parts.push(
2768
- report.found ? `REPORT:\n${report.body.slice(0, 6000)}` : `no REPORT β€” last words:\n${report.body}`,
2769
- `new commits:\n${newCommits.trim() || "(none)"}`,
2770
- `uncommitted: ${dirty ? `\n${dirty}` : "clean"}`,
2771
- );
2772
- if (wop === "implement") {
2773
- const check = await runFlow(["check"], root, uiFrom(ctx), sessFor(ctx, root));
2774
- parts.push(`flow check after the worker: ${check.text.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
2775
- } else if (newCommits.trim() || dirty) {
2776
- parts.push("note: the reviewer changed the tree β€” treat its verdict with suspicion and inspect the change");
2777
- }
2778
- parts.push(`transcript: ${transcript || "(unknown)"}`);
2779
- 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.");
2780
- return { content: [{ type: "text", text: parts.join("\n\n") }], details: { op: wop, outcome, verdict: report.verdict, commits: newCommits.trim().split("\n").filter(Boolean).length } };
2844
+ return runStageWorker({ id, wop: op as WorkerOp, st, root, key, note: String(params.note ?? ""), label: params.label, budgetMin: params.budgetMin, signal, onUpdate, ctx });
2781
2845
  },
2782
2846
  });
2783
2847
  pi.registerTool(stageWorkerTool);
@@ -2796,6 +2860,7 @@ export default function devFlow(pi: ExtensionAPI) {
2796
2860
  // The session, not the process, owns the binding and the claim: pi-web keeps serving other sessions
2797
2861
  // after one ends, and a stale claim there is a permanent lock (its pid is the server's, always alive).
2798
2862
  pi.on("session_shutdown", async (_event, ctx) => {
2863
+ WEB_CHIP_KEYS.delete(sessionKey(ctx)); // the session's UI is gone; a long-lived server must not keep its slot
2799
2864
  if (!guardsAreMine()) return;
2800
2865
  const root = await flowRoot(ctx.cwd);
2801
2866
  if (!existsSync(dfDir(root))) return;
@@ -3057,7 +3122,7 @@ export default function devFlow(pi: ExtensionAPI) {
3057
3122
  // stage (finish runs the reflection), between flows, and in status/doctor
3058
3123
  if (state.stage === "release") {
3059
3124
  const refl = readReflections(root);
3060
- if (refl.length) guidance.push(`↻ ${refl.length} reflection(s) open β€” the finish reflection (flow_stage op "reflect") re-checks them; fix them only on the operator's word.`);
3125
+ 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.`);
3061
3126
  }
3062
3127
  const rmap = roadmapOpenCount(readRoadmap(root));
3063
3128
  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.82.0",
3
+ "version": "0.83.0",
4
4
  "description": "Enforced feature workflow for Pi: plan β†’ implement β†’ pre-release β†’ release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -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 and fold/drop first, Finish?, worktree and branch cleanup |
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
- **Reflect before you finish** β€” `flow finish` deletes `.dev-flow/<slug>/` and
8
- the session context goes with it. Run the end-of-session reflection now:
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. `flow_stage({ op: "reflect", note })` β€” a fresh **read-only** reviewer reads
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 the review inline (bare `flow reflect` prints the protocol).
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`. A finish question with no
36
- reflection recorded for the flow names it (advisory, never a block).
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.
@@ -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): a
37
- `flow_stage({ op: "reflect" })` worker reviews the whole session β€” driver and
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) β€” reflect first, then **Finish?**, then cleanup.
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 flow_stage reflect worker reported for this flow β€” finish names a missing one (advisory, never a block)
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), ask the operator Finish? and run flow finish (removes worktree, branch and .dev-flow/" + state.slug + "/)"
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)`;