pi-dev-flow 0.62.2 → 0.64.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,27 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.64.0] - 2026-10-24
8
+
9
+ ### Fixed
10
+
11
+ - **Reflections land where they are filed, and `flow doctor` reads the file.** The `## playbook` / `## plugin` section was a keyword guess, and it was re-guessed on every surface instead of being read back: `reflectionRoutes` classified the whole item line, ` — <slug> <date>` tail included, so one slug full of trigger words (`fix-versioning-guard` = "versioning" + "guard") made **every** open item read as `playbook+plugin` and routed every fix — a drifted project command included — to "file an issue against pi-dev-flow upstream". Meanwhile the heading the note actually sits under, which `appendReflection` has treated as authoritative since #69, was flattened away by the reader, so doctor's table argued with the file it had just read. Open items now come back from one section-aware reader that carries its heading, routing labels from that heading, and the classifier only ever sees the note body — an item's verdict can no longer change because of what its slug spells. A note that describes dev-flow without saying one of the old magic words also stopped being misfiled quietly: dev-flow's own commands and files (`flow doctor`, `.dev-flow`, `state.json`, gate/guard, worktree) are high-precision plugin signals, so "doctor prints the same finding twice" is a plugin item now, while "the deploy gate in CI is flaky" and "our repo's commit hook rejects rebases" stay the project's own business.
12
+
13
+ ### Added
14
+
15
+ - **`flow reflect --playbook|--plugin "<note>"` — you file it, the tool does not guess.** The session-reflection protocol tells the agent to decide playbook-or-plugin for every finding, and then the tool re-guessed from the sentence. An explicit flag now wins, and a note queued without one prints the guess and its reason — `reflected (plugin — "gate" names dev-flow itself)`, `reflected (playbook — nothing plugin-shaped in the note — if it is a dev-flow bug: flow reflect move <n> --plugin)` — so a wrong filing is visible at the moment it is filed instead of months later in a queue nobody re-reads. `--both` stays for a genuine two-ticket note (it then gets one route per section).
16
+ - **`flow reflect list` and `flow reflect move <n> --plugin|--playbook`.** The queue numbered (same convention as `flow roadmap`), and one command to re-file an item under the other heading — correcting a misfile used to mean hand-editing markdown and hoping the next rewrite kept it where you put it. An item outside both sections (a legacy flat line, or under a `## Plugin notes` heading nobody recognises) is reported by `flow doctor` instead of silently inheriting the previous bucket on the next write.
17
+
18
+ ### Changed
19
+
20
+ - **A both-shaped note has one home.** When both keyword sets matched, the note was written under *both* headings — the operator checked the same issue off twice, and only the plugin half was ever routed (`reflectionRoutes` returned one route and picked the plugin branch first). A guess now picks a primary section (plugin on a strong dev-flow signal, otherwise the playbook, where the operator notices and moves it), and the printed line names the reason.
21
+
22
+ ## [0.63.0] - 2026-10-24
23
+
24
+ ### Added
25
+
26
+ - **`/flow-simplify` — the review skill that actually cuts.** `/flow-review` and `/flow-audit` only report; the new third sibling edits: dead code, no-op placeholder subsystems, misplaced dev scaffolding, genuine duplication (reuse the existing helper before inventing one) and speculative abstractions, removed in a risk-ascending order with the safe levers first. The rails are the feature: a green baseline before any cut (red → stop), behavior-preserving only — a test touched to pass is a reverted cut, Chesterton's fence for anything you cannot explain, semantic dead-code tooling with grep demoted to confirmation, one cut → checks → commit so every regression names its cut, and a structural-vs-cheap self-audit that forces the skill to admit when it shrank the number instead of the system (reformatting, comment-trimming-as-strategy and counted-path moves are named as gaming). Deleting a feature is always escalated, never done. Default target: what you name, else the bound flow's branch diff — whole-repo stays `/flow-audit`'s job. Adapts maxim-saplin/goal-sloc (MIT), addyosmani/agent-skills code-simplification (MIT) and Anthropic's code-simplifier plugin (Apache-2.0).
27
+
7
28
  ## [0.62.2] - 2026-10-24
8
29
 
9
30
  ### Added
package/README.md CHANGED
@@ -147,7 +147,10 @@ claiming a gate result it never produced. → [Gate reference](docs/gates.md)
147
147
  When something costs the agent a step — a playbook command that stopped existing, a guard that
148
148
  refused the wrong thing, a gate that forced a detour, a rough edge in dev-flow itself — it does not
149
149
  just work around it. It parks a one-line note in `.dev-flow/reflections.md`, under **playbook**
150
- (something about your project) or **plugin** (something about dev-flow); the open count surfaces in
150
+ (something about your project) or **plugin** (something about dev-flow) — the agent says which with
151
+ `flow reflect --playbook|--plugin "<note>"`, and a note queued without a flag lands on a keyword
152
+ guess the printed line explains (`flow reflect list` numbers the queue, `flow reflect move <n>
153
+ --plugin` re-files one). The open count surfaces in
151
154
  `flow status` and in the agent's stage context (`↻ 2 reflection(s) open`).
152
155
 
153
156
  They never gate anything, and the fix is never the agent's call alone. You ask it to go through them
@@ -167,12 +170,17 @@ finding needs a concrete triggering case (refuted findings are dropped), grouped
167
170
  Should fix / Nice to have, ending in a verdict and an honest `Not checked:` line. It is the
168
171
  pre-release review step (`release.review` in `project.md` stays yours to set). **`/flow-audit`**
169
172
  audits the whole repo in the same style: map first, judge against the load the project actually
170
- expects, at most 20 ranked findings, changes nothing. And while a flow writes code, the
173
+ expects, at most 20 ranked findings, changes nothing. The operative sibling **`/flow-simplify`**
174
+ makes the cuts audit and review only name: dead code, no-op subsystems, duplication,
175
+ speculative layers — removed in a risk-ascending order, one verified commit per cut, green
176
+ tests as contract, and a structural-vs-cheap self-audit so the diff shrank because the system
177
+ got smaller, not because comments got deleted. And while a flow writes code, the
171
178
  implement stage injects a compact senior-discipline guidance — smallest complete change, no
172
179
  speculative abstraction, finish what your change breaks, a failing-first test for risky logic —
173
180
  your playbook's `prose.implement` replaces it wholesale whenever you write your own. (The review
174
181
  rules adapt ponytail, obra/superpowers and pi-development-system — all MIT, credited in the
175
- skill files.)
182
+ skill files; `/flow-simplify` adapts goal-sloc (MIT), addyosmani/agent-skills (MIT) and
183
+ Anthropic's code-simplifier plugin (Apache-2.0).)
176
184
 
177
185
  ## The playbook the agent always has
178
186
 
package/docs/gates.md CHANGED
@@ -19,9 +19,9 @@ so it needs no `--confirmed`.
19
19
  | `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; with `versioning.file`: the manifest version parses and is **not tagged yet** (the bump must be ahead of the last release); with `release.changelog` the gate **proves the entry mechanically** (#97): a **heading names the version** (prose that mentions it, or a `1.2.0-beta` section when releasing `1.2.0`, is not an entry), **this branch touched the file** (an inherited changelog is not release prep), **every entry that was pending before the release survives inside the new section** — compared on normalized lines, so re-indenting a fold is free while rewording or deleting one is refused by naming the line — and **nothing is left under `Unreleased`**. The pending baseline is the newest tag's changelog (what actually shipped), else the branch's merge base; when neither resolves, the two git-dependent proofs are skipped **with a printed advisory** rather than refusing a legal release for a topology reason, and the content proofs (the heading, its body) always run; tier-2 `## pre-release` checklist confirmed; the manifest version it validates is **stamped as the release's version of record** (`release-done` publishes that, whatever the checkouts say later); **one question** (Release?) — or `--confirmed`; `--no-version` (your call at Release?) ships this flow as **merge + changelog** — the bump/tag requirements and the tag checks at `release-done` are skipped for it, but the branch must still add its **own line under `Unreleased`** (editing an older section releases nothing) and it rides there until the next versioned release folds it (default: versioned); `--no-fold-check` is the operator-granted escape from the line-level fold proofs — one flow, stamped in the gate output, the heading and touched proofs stay; **stale session build** (loaded build behind the checkout): the gate prints both builds, lists what shipped between them (those proofs will not run this release) and folds *update (/reload, then re-run) or proceed with the old release?* into the Release? question — the operator's word, recorded in the release output, **never a block**: publishing under an older gate is a legitimate choice (hotfix, offline reload) |
20
20
  | `release-done` | records the release (the stage stays `release`) | **no question — the Release? answer covered the publication**; verify approval; the version published is the one `release` **stamped** from the manifest it validated (a main checkout still behind cannot republish the previous version), and it must not be older than the newest matching tag **on origin** (tag lists come from `git ls-remote`, so an unfetched clone does not decide what exists; when an origin exists but cannot be asked (offline, no ssh agent) **both release gates refuse** rather than answering with local tags); with `versioning.file`: that tag exists, is reachable from the default branch **and is on origin** (a local-only tag is not a release); with `release.artifact`: the published-artifact check runs (`{version}`/`{tag}` placeholders — the line it prints names the version it verified; skip once with `--no-artifact-check`, operator-instructed only) · creates the forge release from the tag, its body **the `release.changelog` entry for that version** — the changelog is the source of truth, and the tag's annotation stands in only when the changelog has no entry for the version, else nothing (and it says why — a body that is really a shell error is dropped, never shipped) — `gh` for GitHub, `glab` for GitLab) and then **proves the release exists**: it asks the forge (`gh release view <tag>` / `glab release view <tag>`) and refuses when nothing is there, because #51, #60 and #63 were three ways of ending `release recorded as complete` with nothing published — and when the changelog was the body it **reads the stored body back** and refuses a mismatch, so the release page and the changelog cannot drift (#97; normalized before comparing, skipped with a printed note on another forge). Skipping is deliberate and loud — `--no-release-create`, `release.releases = false` or `forge = self` each print that no forge release was created, and the view check is skipped for them; **with a `merge` policy** it also proves the merge that shipped matches it — branch ancestry plus what the forge says (`gh pr view` / `glab api`), so a squash under `merge = merge` (or a merge commit under `merge = squash`) refuses the release record, while a shape it cannot see prints an advisory instead (#97's split: an invisible topology never blocks a legal release); when the release went out on a stale build the operator acknowledged at the release gate, it prints that acknowledgement in place of the after-the-fact version-skew warning, and that warning prints the session vs disk version pair plus the duplicate-copy note when a second copy is registered (#117) |
21
21
  | `finish [--yolo] [slug]` | release → done (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes; when the clean checkout trails `origin/<default>` the gate **fast-forwards local main** as it closes out (never a merge — anything that cannot fast-forward prints the operator's exact `git pull --ff-only` command); **one question** (Finish? — mentions unmerged-looking commits with the playbook's `merge` policy in mind, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; under `merge = merge`, commits that never reached the default branch are a **policy violation**: `yolo` does not answer it, only your explicit answer does; to abandon an unreleased feature use `abort` |
22
- | `reflect ["<note>"|tidy]` | — | `reflect "<note>"` queues a suggestion in `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items; every surface that queues or reviews reflections (`reflect "<note>"`, bare `reflect`, `doctor`) nudges with the closed count when the checked-off pile grows. Bare `reflect` prints the full **session-reflection protocol** for the agent (from the `/flow reflect` bar it additionally wakes the model, so the protocol executes immediately): review the whole session log, re-check every open item against the current playbook and **newer dev-flow versions** (`npm view pi-dev-flow version` vs the running version — dev-flow ships from npm; recommend `pi install npm:pi-dev-flow` + `/reload`, the operator performs updates), dedupe new findings against the open ones, then report playbook vs plugin items to the operator and ask whether to fix now — plugin items: search upstream issues first (`gh issue list --repo <upstream> --state all --search …`; an author-addressed match is reported back, no match → `gh issue create` with a detailed description and a suggested fix), playbook items: `flow doctor` routes each to the docs flow that implements it |
22
+ | `reflect ["<note>"|list|tidy|move <n> --plugin|--playbook]` | — | `reflect "<note>"` queues a suggestion in `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` / `--plugin` files it in that section — the agent knows what its own note is about, so the wording guess is the fallback, and the echoed line prints the reason it landed where it did (`"gate" names dev-flow itself`, `playbook or project wording`, `nothing plugin-shaped in the note …`); a note is filed under **one** section, never both. `reflect list` numbers the open items with their section; `reflect move <n> --plugin|--playbook` re-files one of them. `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items; every surface that queues or reviews reflections (`reflect "<note>"`, bare `reflect`, `doctor`) nudges with the closed count when the checked-off pile grows. Bare `reflect` prints the full **session-reflection protocol** for the agent (from the `/flow reflect` bar it additionally wakes the model, so the protocol executes immediately): review the whole session log, re-check every open item against the current playbook and **newer dev-flow versions** (`npm view pi-dev-flow version` vs the running version — dev-flow ships from npm; recommend `pi install npm:pi-dev-flow` + `/reload`, the operator performs updates), dedupe new findings against the open ones, then report playbook vs plugin items to the operator and ask whether to fix now — plugin items: search upstream issues first (`gh issue list --repo <upstream> --state all --search …`; an author-addressed match is reported back, no match → `gh issue create` with a detailed description and a suggested fix), playbook items: `flow doctor` routes each to the docs flow that implements it |
23
23
  | `roadmap [add "<feature>" \| pick <n> <slug> \| done <n> \| tidy]` | — | manages `.dev-flow/roadmap.md`, the gitignored backlog of future features (`- [ ]` checklist): bare prints the numbered open items, `add` appends one, `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it — **`finish` checks the stamped item off when that feature ships**; `done <n>` checks off by hand (items shipped outside a flow), `tidy` drops the checked lines. Never gates; the open count is surfaced in `status` and session context |
24
- | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo). 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 |
24
+ | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
25
25
  | `status [slug]` / `abort [slug]` | — | — |
26
26
  | `help` (`--help`, `-h`) | — | — (prints the gate help — answerable in any repo, at any stage, with no `.dev-flow/`) |
27
27
  | `version [--check-upstream]` | — | — (prints dev-flow's **own** version and the directory it was loaded from — which copy this session runs, this checkout vs an installed `pi-dev-flow`; when the checkout has moved past the build this session loaded it says so and names both, because the gates execute the loaded code — `/reload` to run the newer one; `--check-upstream` adds the published npm version; answerable in any repo, at any stage, with no `.dev-flow/`) |
@@ -14,7 +14,7 @@ While a feature is active, the extension intercepts every tool call:
14
14
  - **A forced push asks the operator**: `git push` carrying `--force`, `--force-with-lease…` or `-f` is confirmed before it runs — a rewritten branch is history CI and other sessions already have. The one spelling that answers for it is the prefix the refusal prints (`DEV_FLOW_ALLOW_REWRITE=1 git push -f …`), the same "the operator said so" contract as `DEV_FLOW_ALLOW_MAIN`. Local history rewrites (`git filter-branch --force`) are not pushes and stay free, so a project never needs a blunt flag-only deny of its own.
15
15
  - **Shell calls can't hang forever**: pi kills a shell command only when the model passed a `timeout` — it omits one in ~75% of calls, so a `gh` waiting on a prompt or a dead `curl` froze sessions for hours. In an initiated repo (`.dev-flow/project.md` exists) the call is therefore by default **refused** until the model states one (`bashTimeout = require`): the refusal names the exact value the class table would have armed, so the retry is a one-token fix and the call line in the transcript shows the timeout that is actually running. The injected class default (30s quick inspection · 120s local git and unknown · 180s network · 300s containers/services · 900s builds/tests/installs · 1,200s watchers like `gh run watch`) stays armed underneath either way, and absurd explicit values clamp to 1,800s. A project that would rather not nag sets `bashTimeout = inject` in `## global` — then the default is armed silently and the call passes. Uninitiated folders hear nothing at all: without the playbook dev-flow enforces no rules.
16
16
  - **Compact-aware**: dev-flow paces compaction the way pi counts it: the self-compaction trigger uses the *effective* `reserveTokens` (settings and per-model overrides, not the built-in default) and is checked at every turn end, not only when a run settles. When pi force-compacts on its threshold anyway — the chat-only states (open tier-2 dialog, plan discussion not yet in `plan/`) refuse to self-compact by design — dev-flow takes the compaction over and redoes it with flow-aware summary instructions (overflow recovery keeps pi's compact-and-retry and is left alone). Auto-compaction turned off in settings is honored; a note about any compaction dev-flow could not shape still lands in `reflections.md`.
17
- - The active stage is injected into the model's context every turn; the bundled `dev-flow` skill is the agent's playbook, including the recommended sequences: pre-release — review (`/flow-review`) → fixes → docs → changelog/version bump; release — PR → merge → tag → `release-done`. The package also bundles the review skills themselves — `/flow-review` (a change, read against its `plan/plan.md`) and `/flow-audit` (the whole repo) — and injects a built-in senior-discipline guidance at implement stage unless the playbook sets its own `prose.implement`.
17
+ - The active stage is injected into the model's context every turn; the bundled `dev-flow` skill is the agent's playbook, including the recommended sequences: pre-release — review (`/flow-review`) → fixes → docs → changelog/version bump; release — PR → merge → tag → `release-done`. The package also bundles the review skills themselves — `/flow-review` (a change, read against its `plan/plan.md`), `/flow-audit` (the whole repo) and `/flow-simplify` (the operative cut: deletes dead and duplicated code, one verified commit at a time) — and injects a built-in senior-discipline guidance at implement stage unless the playbook sets its own `prose.implement`.
18
18
  - **Status bar**: an initiated repo (`.dev-flow/project.md` exists) always carries the dev-flow footer; while the session **is bound** to a feature it shows `<stage glyph> <slug>` plus mode markers — stages 📝 plan, 🔨 implement, 🔍 pre-release, 🚀 release; markers ⚡ patch, 📚 docs, 🎱 yolo, and `⚠️` while a check of the bound feature fails (emoji render in their own color, so the footer carries no theme coloring). An **unbound** session never sees a slug — it shows `⧖ N flow(s) open` (unfinished-feature count only, no warning marker) or `⧖ no flows` when nothing is in flight; a session binds only via `flow start`/`flow use`, never by opening. The footer repaints at session start, at the start of every agent run (the earliest a late-attaching web client is listening) and after every gate; an uninitiated folder gets no footer at all. `flow status` is the spelled-out surface: `stage=implement`, the per-feature mode tags (`[ui]`, `[yolo]`, `[no-version]`) and the `flow=<ver>` stamp of the build that started the feature.
19
19
 
20
20
  ## Limitations (deliberate, v1)
package/docs/playbook.md CHANGED
@@ -162,7 +162,9 @@ anything (findings are also printed whenever `flow init` runs without a UI, e.g.
162
162
  rewrites from fresh detection. Improvement
163
163
  ideas the agent notices along the way queue up in `.dev-flow/reflections.md` under `## playbook`
164
164
  (what to change in *your* playbook) and `## plugin` (what to change in dev-flow itself) —
165
- `flow reflect "<note>"` appends them, `flow reflect tidy` drops the closed (`- [x]`) ones,
165
+ `flow reflect "<note>"` appends them (`--playbook` / `--plugin` says which section, no flag guesses
166
+ from the wording and prints why), `flow reflect list` numbers the open ones, `flow reflect move <n>
167
+ --plugin|--playbook` re-files one, `flow reflect tidy` drops the closed (`- [x]`) ones,
166
168
  plain `flow doctor` reviews the open ones and routes
167
169
  each fix to the flow that implements it (docs flow for playbook items — those edits only pass a
168
170
  docs/patch flow's worktree), bare `flow reflect` hands the agent the full end-of-session
@@ -72,12 +72,17 @@ import {
72
72
  playbookOnlyChange,
73
73
  pluginVersion,
74
74
  preReleaseGate,
75
+ guessReflectSections,
76
+ reflectItems,
77
+ reflectMove,
75
78
  reflectProtocol,
76
- reflectSections,
79
+ reflectUnfiledCount,
77
80
  reflectionLine,
78
81
  reflectionRoutes,
79
82
  reflectionsTidy,
80
83
  reflectionsTidyHint,
84
+ type ReflectItem,
85
+ type ReflectSection,
81
86
  stageReference,
82
87
  sessionRunsOlderBuild,
83
88
 
@@ -319,7 +324,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
319
324
  }
320
325
 
321
326
  const GATE_HELP =
322
- "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|tidy] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui] [--force] [--patch|--docs --confirmed] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — start preflights the playbook before creating anything: it prints playbook gaps and warns when the session runs an older dev-flow build than the disk ships (in the dev-flow repo, an older build than this checkout's own manifest), and it refuses until a merge policy is set (ask the operator squash / merge / rebase / any in chat, then re-run with --merge=<style> --confirmed — the answer is written into project.md and enforced from then on: gh/glab merges that contradict it are blocked, and release-done proves what actually landed); version prints the build the disk says to run (this checkout's own manifest in the dev-flow repo, the installed package's elsewhere) and names any other dev-flow copies registered in the same process (--check-upstream also asks the registry for the published one) — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there); reflect tidy drops the closed (`- [x]`) items from reflections.md — every surface that queues or reviews reflections nudges when the checked-off pile grows; bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned); when the session runs an older dev-flow build than the checkout, release names both builds, lists what the running code can no longer prove, and asks the operator update (/reload) or proceed with the old release — an operator decision recorded in state and repeated by release-done, never a block";
327
+ "help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|list|tidy|move <n> --plugin|--playbook] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui] [--force] [--patch|--docs --confirmed] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — start preflights the playbook before creating anything: it prints playbook gaps and warns when the session runs an older dev-flow build than the disk ships (in the dev-flow repo, an older build than this checkout's own manifest), and it refuses until a merge policy is set (ask the operator squash / merge / rebase / any in chat, then re-run with --merge=<style> --confirmed — the answer is written into project.md and enforced from then on: gh/glab merges that contradict it are blocked, and release-done proves what actually landed); version prints the build the disk says to run (this checkout's own manifest in the dev-flow repo, the installed package's elsewhere) and names any other dev-flow copies registered in the same process (--check-upstream also asks the registry for the published one) — reflect <note> queues a suggestion in reflections.md (gate flags like --confirmed are ignored there; --plugin / --playbook / --both state the section instead of leaving it to the wording, and the echo prints why the note landed where it did); reflect list numbers the open items with their section; reflect move <n> --plugin|--playbook re-files one of them; reflect tidy drops the closed (`- [x]`) items from reflections.md — every surface that queues or reviews reflections nudges when the checked-off pile grows; bare reflect prints the full session-reflection protocol (review the session log, re-check open items against shipped fixes and newer dev-flow versions, dedupe and report new findings, put the fix decision to the operator); roadmap manages .dev-flow/roadmap.md, the gitignored backlog of future features (bare lists open items; add appends one; pick <n> <slug> stamps open item <n> with the slug a later flow start uses — flow finish checks it off when that feature ships; done <n> checks off by hand; tidy drops done items); bare doctor reviews structure, git consistency and open reflections (routes each fix to a flow; it never writes); doctor <note> prints an investigation brief for a fresh observation; state gates take [slug] and --confirmed (the operator already answered in chat); --patch/--docs likewise need --confirmed (the operator granted the mode); --yolo on any state gate (approve/verify/release/finish) = the operator said \"yolo\" at that checkpoint: it answers that question and pre-confirms every later one (needs --confirmed; checks and guardrails stay); release --no-fold-check = operator-granted escape from the changelog fold proofs (the entries pending before the release are not line-checked; the entry heading and the 'this branch touched the changelog' proofs stay); release --no-version = this flow ships merge + changelog only — no bump, tag or forge release; the entry rides under Unreleased until the next versioned release folds it (default: versioned); when the session runs an older dev-flow build than the checkout, release names both builds, lists what the running code can no longer prove, and asks the operator update (/reload) or proceed with the old release — an operator decision recorded in state and repeated by release-done, never a block";
323
328
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
324
329
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
325
330
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -399,10 +404,10 @@ function unfinishedStates(root: string): FlowState[] {
399
404
  .filter((s): s is FlowState => !!s && s.stage !== "done");
400
405
  }
401
406
 
402
- /** Open items of the agent's suggestion queue (.dev-flow/reflections.md). */
403
- const readReflections = (root: string): string[] => {
407
+ /** Open items of the agent's suggestion queue (.dev-flow/reflections.md), each with its section. */
408
+ const readReflections = (root: string): ReflectItem[] => {
404
409
  const f = path.join(dfDir(root), "reflections.md");
405
- return existsSync(f) ? openReflections(readFileSync(f, "utf8")) : [];
410
+ return existsSync(f) ? reflectItems(readFileSync(f, "utf8")) : [];
406
411
  };
407
412
 
408
413
  /** Raw reflections.md content — the closed-item count needs the checked lines the open-only reader drops. */
@@ -684,19 +689,51 @@ function setupQuestions(det: { partial: { defaultBranch: string; versioning?: {
684
689
 
685
690
  const GIT_TRACK_NOTE = 'the playbook belongs in git: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force-add: a root .gitignore may exclude .dev-flow/ entirely — tracked once, the ignore stops mattering; the env prefix is for the pre-commit hook, dev-flow itself lets a main commit whose only change is the playbook)';
686
691
 
687
- /** `flow reflect <note>` — advisory queue, operator decides. The note lands in the
688
- * playbook and/or plugin section of reflections.md, chosen from its wording. */
689
- function reflectNote(root: string, sess: Session, note: string[]): RunResult {
692
+ /** `flow reflect <note>` — advisory queue, operator decides. `--plugin` / `--playbook` states where
693
+ * it lands (the agent knows what its own note is about); with no flag the wording guesses ONE primary
694
+ * section and the echo prints the reason — a silent guess is how a dev-flow bug got buried in
695
+ * `## playbook` and never routed anywhere. */
696
+ function reflectNote(root: string, sess: Session, note: string[], forced: ReflectSection[] | null): RunResult {
690
697
  const file = path.join(dfDir(root), "reflections.md");
691
698
  const text = existsSync(file) ? readFileSync(file, "utf8") : "";
692
- const sections = reflectSections(note.join(" "));
699
+ const guess = guessReflectSections(note.join(" "));
700
+ const sections = forced ?? guess.sections;
693
701
  const line = reflectionLine(note.join(" "), sess.slug, now().slice(0, 10));
694
702
  const next = appendReflection(text, sections, line);
695
703
  if (next === text) return { text: `already reflected (duplicate): ${line}` };
696
704
  writeFileSync(file, next);
697
705
  // queueing is exactly when the operator hears about the checked-off pile — nudge instead of letting it grow
698
706
  const closed = closedReflectionCount(next);
699
- return { text: `reflected (${sections.join(" + ")}): ${line}` + (closed ? `\n${reflectionsTidyHint(closed)}` : "") };
707
+ const why = forced ? "as told" : guess.why;
708
+ return { text: `reflected (${sections.join(" + ")} — ${why}): ${line}` + (closed ? `\n${reflectionsTidyHint(closed)}` : "") };
709
+ }
710
+
711
+ /** `flow reflect list` — the queue numbered, so `move <n>` can address an item (same numbering as `flow roadmap`). */
712
+ function reflectList(root: string): RunResult {
713
+ const items = readReflections(root);
714
+ if (!items.length) return { text: "reflections: nothing open" };
715
+ return {
716
+ text: [`reflections — ${items.length} open:`, ...items.map((it, i) => ` ${i + 1}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`)].join("\n"),
717
+ };
718
+ }
719
+
720
+ /** `flow reflect move <n> --plugin|--playbook` — re-file an item under the other heading, so fixing a
721
+ * misfile is one command instead of hand-editing markdown. */
722
+ function reflectMoveNote(root: string, args: string[], forced: ReflectSection[] | null): RunResult {
723
+ if (!forced || forced.length !== 1) return { text: "usage: flow reflect move <n> --plugin | --playbook", isError: true };
724
+ const section = forced[0];
725
+ const n = Number(args[0]);
726
+ const text = readReflectionsText(root);
727
+ const items = reflectItems(text);
728
+ if (!Number.isInteger(n) || n < 1 || n > items.length) return { text: `move: open item 1–${items.length} required — flow reflect list numbers them`, isError: true };
729
+ if (items[n - 1].section === section) return { text: `reflect: item ${n} is already under ## ${section}` };
730
+ // the same note open under both headings (an old --both filing): the move merges it, it does not copy it
731
+ const twin = items.some((it, i) => i !== n - 1 && it.section === section && it.body === items[n - 1].body);
732
+ const next = reflectMove(text, n, section);
733
+ if (next === null) return { text: `move: open item 1–${items.length} required — flow reflect list numbers them`, isError: true };
734
+ writeFileSync(path.join(dfDir(root), "reflections.md"), next);
735
+ const note = items[n - 1].line.replace(/^- \[ \] /, "");
736
+ return { text: twin ? `reflect: item ${n} was already recorded under ## ${section} — the duplicate is gone (${note})` : `reflect: item ${n} re-filed under ## ${section} — ${note}` };
700
737
  }
701
738
 
702
739
  /** `flow reflect tidy` — drop the closed (`- [x]`) items; the `— fixed:` note already recorded the outcome. */
@@ -813,7 +850,7 @@ async function runFlow(args: string[], root: string, ui: Ui, sess: Session): Pro
813
850
  const ev = await mergeHistoryEvidence(root, loaded.cfg.defaultBranch);
814
851
  if (ev?.recent) findings.push(`${ev.note} — write it into the playbook: merge = ${ev.recent} under ## release (or let the next flow start ask and write it)`);
815
852
  }
816
- for (const l of readReflections(root)) findings.push(`open reflection: ${l.slice(6)}`);
853
+ for (const it of readReflections(root)) findings.push(`open reflection [${it.section}]: ${it.line.slice(6)}`);
817
854
  if (!findings.length) notes.push("doctor: project.md OK — no drift, no inconsistencies");
818
855
  else {
819
856
  // a refresh is regenerated from detection + config: lines it cannot reproduce are
@@ -960,11 +997,21 @@ ${mdDigest(draftRefresh)}`))
960
997
 
961
998
  case "reflect": {
962
999
  // gate flags belong to the state verbs — pasted into the note they read as part of the operator's
963
- // own sentence in reflections.md (#43)
1000
+ // own sentence in reflections.md (#43). --plugin/--playbook/--both are reflect's own: they state
1001
+ // the filing instead of leaving it to a keyword guess.
964
1002
  const words = rest.filter((a) => !a.startsWith("--"));
965
- // the single word `tidy` is a verb (roadmap-style); a note merely starting with it stays a note
1003
+ const forced: ReflectSection[] | null = flag("both")
1004
+ ? (["playbook", "plugin"] as ReflectSection[])
1005
+ : flag("plugin")
1006
+ ? (["plugin"] as ReflectSection[])
1007
+ : flag("playbook")
1008
+ ? (["playbook"] as ReflectSection[])
1009
+ : null;
1010
+ // single words are verbs (roadmap-style); a note merely starting with one stays a note
966
1011
  if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
967
- if (words.length) return reflectNote(root, sess, words);
1012
+ if (words.length === 1 && words[0] === "list") return reflectList(root);
1013
+ if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
1014
+ if (words.length) return reflectNote(root, sess, words, forced);
968
1015
  // upstream for the update probe: the manifest's repository field; the dev-flow checkout itself falls back to its origin
969
1016
  const self = pluginVersion(import.meta.dirname);
970
1017
  const upstream = self.repo || (isSelfRepo(root) ? githubSlug((await sh("git remote get-url origin", root)).out) : "");
@@ -1023,8 +1070,12 @@ ${mdDigest(draftRefresh)}`))
1023
1070
  const refl = readReflections(root);
1024
1071
  if (refl.length) {
1025
1072
  findings.push(`reflection review — ${refl.length} open item(s); doctor never implements: investigate each, present the fix, the operator confirms, then the routed flow implements it:`);
1073
+ // labelled from the heading each item sits under — the file is the record, re-guessing from the
1074
+ // note text made doctor's table disagree with where the note was actually filed
1026
1075
  for (const r of reflectionRoutes(refl, isSelfRepo(root))) findings.push(` [${r.sections.join("+")}] ${r.text}\n → ${r.route}`);
1027
1076
  }
1077
+ const unfiled = reflectUnfiledCount(readReflectionsText(root));
1078
+ if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## plugin — flow reflect list shows them, flow reflect move <n> --plugin|--playbook files them`);
1028
1079
  const closedRefl = closedReflectionCount(readReflectionsText(root));
1029
1080
  if (closedRefl) findings.push(reflectionsTidyHint(closedRefl));
1030
1081
  if (!rest.length) return { text: findings.length ? `doctor: ${findings.length} finding(s)\n${findings.map((f) => ` ${f}`).join("\n")}` : "doctor: no findings — playbook, flow state and git layout are consistent" };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.62.2",
3
+ "version": "0.64.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": [
@@ -6,12 +6,18 @@
6
6
 
7
7
  Anything the playbook or plugin should improve (drifted commands, gate friction,
8
8
  a plugin bug) gets parked, not complained about:
9
- `flow reflect "<one-line note>"`; gate flags are ignored —
9
+ `flow reflect --playbook|--plugin "<one-line note>"`; gate flags are ignored —
10
10
  `flow reflect "<note>" --confirmed` queues the note alone. For a note to chase
11
11
  **now**: `flow doctor "<observation>"` prints an investigation brief without
12
- queueing. Notes land under `## playbook` or `## plugin` — the wording decides,
13
- a note about both goes to both. The open count shows in status and stage
14
- context; the operator decides:
12
+ queueing. **You file the note, the tool does not guess**: `--playbook` puts it
13
+ under `## playbook`, `--plugin` under `## plugin` (you already know which one it
14
+ is — the session log does). With no flag the wording guesses ONE section and the
15
+ printed line says why (`"gate" names dev-flow itself`, `playbook or project
16
+ wording`, or `nothing plugin-shaped in the note …`); if the guess is wrong,
17
+ `flow reflect list` numbers the queue and `flow reflect move <n> --plugin` (or
18
+ `--playbook`) re-files the item — never hand-retype it. Nothing is ever written
19
+ to both sections: one note, one home, one route. The open count shows in status
20
+ and stage context; the operator decides:
15
21
 
16
22
  - Reflect real friction only, one line each, never the same issue twice.
17
23
  - **`flow reflect tidy` drops the closed (`- [x]`) items** — the `— fixed:` note has
@@ -30,7 +36,10 @@ context; the operator decides:
30
36
  now. The command writes nothing; you execute the protocol.
31
37
  - Plain `flow doctor` reviews the open items and **routes** each to the flow
32
38
  that implements it — playbook item → docs flow; plugin item → upstream issue
33
- (or a patch/normal flow in the dev-flow repo). To fold items in on the
39
+ (or a patch/normal flow in the dev-flow repo). It labels each item with the
40
+ `## heading` it is filed under (the file is the record; the wording of the
41
+ note decided nothing since the note was queued) and flags items sitting
42
+ outside both sections. To fold items in on the
34
43
  operator's word: investigate, propose the fix, get confirmation, open the
35
44
  routed flow (playbook items: `flow start fold-<topic> --docs --confirmed`)
36
45
  and apply it there — project.md is editable only in that worktree. Check
@@ -0,0 +1,137 @@
1
+ ---
2
+ name: flow-simplify
3
+ description: >
4
+ Operative cut-down of code: delete dead code, collapse near-copies, reuse
5
+ shared helpers, remove unused options and speculative abstractions — while
6
+ behavior and the green test suite are contract. Unlike the read-only
7
+ flow-review and flow-audit, this one edits, commit by verified commit. Use
8
+ for "simplify this", "slim this down", "compact this code", "remove dead
9
+ code", "dedupe this". Default target: what the operator names, or the bound
10
+ flow's branch diff.
11
+ argument-hint: "[file... | dir...]"
12
+ ---
13
+
14
+ # flow-simplify
15
+
16
+ Cut real weight: less system, same behavior. Review and audit report; this
17
+ skill edits — under a discipline that keeps every cut reviewable and cheaply
18
+ revertible. Order of importance: **behavior preserved, honest cuts, least
19
+ code.** Editing means working where editing is allowed — a dev-flow worktree
20
+ or a branch, never a bare default branch. Deleting or changing a feature is
21
+ one cut too far: that is the operator's call.
22
+
23
+ ## 0. The game's rules
24
+
25
+ - Behavior-preserving only: same inputs, outputs, error behavior, side
26
+ effects, edges. Tests define that behavior.
27
+ - Green baseline first: run the project's checks (playbook test/build/lint
28
+ commands, or README's). Red baseline → stop; never simplify on top of red.
29
+ - Never touch a test to make it pass after a cut. A cut that breaks a green
30
+ test changed behavior — or found a bug. Revert and report; the bug is a
31
+ separate flow.
32
+ - Small steps: one cut, one check, one commit (§6).
33
+
34
+ ## 1. Pick the target
35
+
36
+ - What the operator names: files, a folder, a subsystem.
37
+ - Nothing named and the session is bound to a dev-flow feature: the code
38
+ this flow's branch touched — `git diff $(git merge-base origin/<default> HEAD)`
39
+ plus uncommitted work (run `flow status` for the worktree and default).
40
+ - Neither: ask. Never silently widen to the whole repo — that is
41
+ `/flow-audit`'s job: audit finds it, you cut it.
42
+
43
+ ## 2. Baseline and tools
44
+
45
+ - Count lines per area (app code, tests) before you start, measured through
46
+ the project's formatter so a reformat cannot fake a win.
47
+ - Dead-code claims come from semantic tooling — language server, knip,
48
+ vulture, `cargo machete`, whatever the repo has. Grep confirms a tool's
49
+ hit; grep alone lies: it misses re-exports, dynamic and string dispatch,
50
+ tear-offs, and config references.
51
+ - Name the floor you will not touch: generated files, vendored code,
52
+ platform scaffolding. A line that was never yours is not bloat.
53
+
54
+ ## 3. Chesterton's fence
55
+
56
+ Understand why the code exists before you touch it: who calls it, what it
57
+ calls, which tests pin it, what `git blame` says about its origin. If you
58
+ cannot say why it exists and what exact maintenance cost removing it lifts,
59
+ leave it and list it under `Untouched:`. Commented-out blocks and
60
+ unreachable branches are the exception — they never get a fence.
61
+
62
+ ## 4. The cut order
63
+
64
+ Safe to risky; risk rises as you go down, so stopping at any line is a fine
65
+ answer. Verify each cut (§6) before the next.
66
+
67
+ 1. **Dead code:** files, exports, functions, branches with zero references —
68
+ §2-verified, tests, fixtures, config and dynamic references included.
69
+ 2. **No-op places:** fully plumbed subsystems that do nothing, toggles
70
+ hardcoded off, config nobody sets, options with no effect. Dead weight
71
+ in feature clothing.
72
+ 3. **Misplaced scaffolding:** dev/debug/test harnesses in shipping code →
73
+ move them to their real home.
74
+ 4. **Duplication:** same logic in two places → one remains. Search for an
75
+ existing helper before extracting a new one — reuse beats inventing.
76
+ Near-identical files become one; two helpers doing one job keep the
77
+ better path, by name.
78
+ 5. **Speculative structure:** an interface with one implementation, a
79
+ factory or strategy for one case, a wrapper that only forwards. Delete
80
+ the layer; call the thing.
81
+ 6. **Comment hygiene:** comments restating the code die; comments saying
82
+ *why* stay. This rides along on files you are already editing — a
83
+ standalone comment-trim is not simplification, it is silencing.
84
+ 7. **Only when asked and the tests are a faithful spec:** clean-room rewrite
85
+ of a worst file against its tests, discarding accumulated cruft. Riskiest
86
+ lever here; without trusting tests you rewrite bugs into features.
87
+
88
+ ## 5. Honest cuts
89
+
90
+ The number is the temptation; the system is the point. Never: reformat, pack
91
+ lines or strip blanks to shrink; delete docs or features to win; move code
92
+ out of the counted path; adjust the measuring tool. When done, split your
93
+ cuts: **structural** (dead, no-op, duplication, layers) vs **cheap**
94
+ (comments, whitespace, cosmetic moves). Cheap in the majority means the
95
+ metric was gamed — say so plainly and report that the structural well is
96
+ dry; that report is itself a good result.
97
+
98
+ ## 6. The loop
99
+
100
+ One cut → project checks → commit, or revert and reconsider. Never batch cuts
101
+ into one commit — a regression must name its cut. A single cut touching 500+
102
+ lines gets scripted (codemod, AST transform, sed), not hand-edited. Pure
103
+ reformatting, when you must have any, rides a separate commit from real cuts.
104
+
105
+ ## 7. Do not over-simplify
106
+
107
+ - Never inline away a helper whose name was the concept.
108
+ - Never merge two functions into one with two jobs.
109
+ - Never remove error handling "for cleanliness"; never delete an abstraction
110
+ that exists for testability — ask before that one.
111
+ - Never trade if/else for a nested ternary to save lines; explicit and a
112
+ touch longer beats clever and short.
113
+ - Never rename to your taste — project conventions win; churn dressed as
114
+ cleanup is just churn.
115
+
116
+ ## 8. When to stop
117
+
118
+ The remaining cuts are architecture reshuffles you cannot finish and verify
119
+ here, product scope, or riskier than their value: stop and report. No
120
+ refactor→regret→revert loops, no half-migrated layer left behind — half a
121
+ migration is worse than none. A legitimate ending is *"already lean"*:
122
+ small cut, suite green, nothing worth removing.
123
+
124
+ ## 9. Report
125
+
126
+ Plain English, short sentences. Start with **`Cut:`** — counts per §4
127
+ category, files and lines before → after, the structural:cheap split (§5),
128
+ checks green. Then **`Reused:`** — the existing helpers duplicated logic
129
+ folded into (paths). Then **`Untouched:`** — fences left standing and why,
130
+ parts not covered and anything you could not verify. Close with
131
+ **`Decisions needed:`** only when a remaining cut is scope or product — with
132
+ the numbers, so the operator can choose.
133
+
134
+ ---
135
+ _Adapted for dev-flow from: maxim-saplin/goal-sloc (MIT), addyosmani/
136
+ agent-skills code-simplification (MIT),
137
+ anthropics/claude-plugins-official code-simplifier (Apache-2.0)._
package/src/core.ts CHANGED
@@ -1306,15 +1306,14 @@ export const closedReflectionCount = (text: string) => text.split("\n").filter(i
1306
1306
  * (a line filter — no re-bucketing like appendReflection's rewrite), and a `## section` heading
1307
1307
  * left with no open items under it goes with its items. */
1308
1308
  export function reflectionsTidy(text: string): string {
1309
- const headerRe = new RegExp(`^## (${REFLECT_SECTIONS.join("|")})\\s*$`, "i");
1309
+ const bucket = (l: string) => (REFLECT_HEADING.test(l) ? REFLECT_HEADING.exec(l)![1].toLowerCase() : "unfiled");
1310
1310
  const lines = text.split("\n");
1311
1311
  // pass 1: open items per heading decides which sections survive; items above every heading are legacy flat lines with no heading to drop
1312
1312
  let section: string | null = null;
1313
1313
  const openUnder = new Map<string, number>();
1314
1314
  for (const raw of lines) {
1315
1315
  const l = raw.trim();
1316
- const h = headerRe.exec(l);
1317
- if (h) section = h[1].toLowerCase();
1316
+ if (ANY_HEADING.test(l)) section = bucket(l);
1318
1317
  else if (section && isOpenItem(l)) openUnder.set(section, (openUnder.get(section) ?? 0) + 1);
1319
1318
  }
1320
1319
  // pass 2: closed items never survive; an emptied heading never survives
@@ -1322,9 +1321,8 @@ export function reflectionsTidy(text: string): string {
1322
1321
  section = null;
1323
1322
  for (const raw of lines) {
1324
1323
  const l = raw.trim();
1325
- const h = headerRe.exec(l);
1326
- if (h) {
1327
- section = h[1].toLowerCase();
1324
+ if (ANY_HEADING.test(l)) {
1325
+ section = bucket(l);
1328
1326
  if ((openUnder.get(section) ?? 0) > 0) out.push(raw);
1329
1327
  continue;
1330
1328
  }
@@ -1355,15 +1353,91 @@ export const REFLECT_HEADER =
1355
1353
  export const REFLECT_SECTIONS = ["playbook", "plugin"] as const;
1356
1354
  export type ReflectSection = (typeof REFLECT_SECTIONS)[number];
1357
1355
 
1358
- // keyword sets decide the section: plugin = dev-flow's own behaviour, playbook = this project's
1359
- const PLUGIN_HINT = /\b(plugin|extension|dev-flow|gate|guard|tool|session|compact\w*|hook|status bar)\b/i;
1360
- const PLAYBOOK_HINT = /\b(project\.md|playbook|checklist|versioning|defaultBranch|prose|setup|health|release rules)\b/i;
1356
+ /** One matcher for the section headings: the writer, the tidy and the reader share it, so a heading
1357
+ * one of them accepts cannot be invisible to another. */
1358
+ const REFLECT_HEADING = new RegExp(`^##\\s*(${REFLECT_SECTIONS.join("|")})\\s*$`, "i");
1359
+ /** Any `## …` line claims the items under it — one that names no section leaves them unfiled, so the
1360
+ * reader (and doctor) can say so instead of inheriting whichever heading came before. */
1361
+ const ANY_HEADING = /^##/;
1362
+
1363
+ /** An open reflections.md item together with the section that owns it. The heading is the record of
1364
+ * where a note was filed; the keyword guess is made once, when the note is queued. */
1365
+ export interface ReflectItem {
1366
+ /** the `## section` the line sits under; "unfiled" = above every heading or under an unknown one */
1367
+ section: ReflectSection | "unfiled";
1368
+ /** the verbatim `- [ ] …` line, trimmed */
1369
+ line: string;
1370
+ /** the note without checkbox and without the ` — attribution` tail */
1371
+ body: string;
1372
+ }
1373
+
1374
+ /** Open items of reflections.md, each carrying the heading that owns it. Items above every known
1375
+ * heading (a legacy flat file) or under an unknown `## …` heading come back "unfiled" instead of
1376
+ * silently inheriting whichever bucket came before them. */
1377
+ export function reflectItems(text: string): ReflectItem[] {
1378
+ const out: ReflectItem[] = [];
1379
+ let section: ReflectSection | "unfiled" = "unfiled";
1380
+ for (const raw of text.split("\n")) {
1381
+ const l = raw.trim();
1382
+ if (ANY_HEADING.test(l)) {
1383
+ const h = REFLECT_HEADING.exec(l);
1384
+ section = h ? (h[1].toLowerCase() as ReflectSection) : "unfiled";
1385
+ continue;
1386
+ }
1387
+ if (!isOpenItem(l)) continue;
1388
+ out.push({ section, line: l, body: reflectionBody(l) });
1389
+ }
1390
+ return out;
1391
+ }
1361
1392
 
1362
- /** Which reflections.md section(s) a note belongs to. Both keyword sets → both sections;
1363
- * neither → playbook, where the operator will notice and move it. */
1393
+ /** Open items the file does not place in a known section — doctor names the count so a note that
1394
+ * would once have quietly migrated to `## playbook` on the next write gets moved on purpose. */
1395
+ export const reflectUnfiledCount = (text: string) => reflectItems(text).filter((i) => i.section === "unfiled").length;
1396
+
1397
+ // The classifier decides where a note being queued LANDS — nothing re-derives it afterwards.
1398
+ // Signals are ranked. A note that names dev-flow's own surface is a plugin issue, and its commands
1399
+ // and files are a closed set, so that read is high-precision. Vague words (tool, hook, session) are
1400
+ // weak on purpose: every project has git hooks and CI gates of its own, and matching those as
1401
+ // "plugin" is how project feedback ended up in the plugin queue.
1402
+ const PLUGIN_STRONG_SRC =
1403
+ "\\bflow (?:help|init|reflect|roadmap|doctor|status|start|use|test|check|health|approve|verify|release(?:-done)?|finish|abort|version)\\b|\\/flow\\b|\\.dev-flow\\b|state\\.json|flow-guard|flow-check|\\bdoctor\\b|\\bgates?\\b|\\bguards?\\b|checkpoint|worktree";
1404
+ const PLUGIN_STRONG_ALL = new RegExp(PLUGIN_STRONG_SRC, "gi");
1405
+ /** …but "CI gate", "deploy gate", "review gate" is the project's own gate, not a flow gate. */
1406
+ const PROJECT_QUALIFIED = /\b(?:ci|cd|deploy|staging|stage|prod(?:uction)?|build|lint|review|preview|merge|security)\s+(?:gates?|checks?|hooks?|tools?|tooling)\b/i;
1407
+ const PLAYBOOK_STRONG = /project\.md|playbook|checklist|defaultBranch|merge policy|versionFile|versionTag|release rules|(?:npm|pnpm|yarn|bun|make|cargo)\s+\S+|\b(?:our|this) (?:repo|project)\b|health (?:command|endpoint)/i;
1408
+ const PLUGIN_WEAK = /\b(plugin|extension|dev-flow|tool|session|compact\w*|hook|status bar)\b/i;
1409
+ const PLAYBOOK_WEAK = /\b(playbook|checklist|versioning|prose|setup|docs?|readme)\b/i;
1410
+
1411
+ export interface ReflectGuess {
1412
+ sections: ReflectSection[];
1413
+ /** why the note landed there — printed, so a wrong guess is visible at the moment it is filed */
1414
+ why: string;
1415
+ }
1416
+
1417
+ /** Where a fresh note lands: ONE primary home. Writing a both-shaped note to both sections made the
1418
+ * operator check the same issue off twice while only the plugin half ever got a route. A strong
1419
+ * plugin signal wins; otherwise the playbook, where the operator reads it and can move it. */
1420
+ export function guessReflectSections(note: string): ReflectGuess {
1421
+ // never classify the ` — <slug> <date>` tail: slugs are made of "guard", "release", "versioning"
1422
+ const body = reflectionBody(note);
1423
+ // every signal counts, not just the first one found: "the CI gate is wrong, flow doctor reports it
1424
+ // twice" is a plugin note even though its earliest match is a demoted one
1425
+ const qualified = PROJECT_QUALIFIED.test(body);
1426
+ const hits = [...body.matchAll(PLUGIN_STRONG_ALL)]
1427
+ .map((m) => m[0].trim())
1428
+ .filter((h) => !(qualified && /gates?|guards?/i.test(h)));
1429
+ if (hits.length) return { sections: ["plugin"], why: `"${hits[0]}" names dev-flow itself` };
1430
+ const plug = PLUGIN_WEAK.test(body);
1431
+ const playStrong = PLAYBOOK_STRONG.test(body);
1432
+ const play = playStrong || PLAYBOOK_WEAK.test(body);
1433
+ if (plug && !play) return { sections: ["plugin"], why: "plugin wording" };
1434
+ if (play) return { sections: ["playbook"], why: playStrong ? "playbook or project wording" : "playbook wording" };
1435
+ return { sections: ["playbook"], why: "nothing plugin-shaped in the note — if it is a dev-flow bug: flow reflect move <n> --plugin" };
1436
+ }
1437
+
1438
+ /** The section(s) a note belongs to, decided from its wording (primary home only — see guessReflectSections). */
1364
1439
  export function reflectSections(note: string): ReflectSection[] {
1365
- const plugin = PLUGIN_HINT.test(note);
1366
- return plugin && PLAYBOOK_HINT.test(note) ? ["playbook", "plugin"] : plugin ? ["plugin"] : ["playbook"];
1440
+ return guessReflectSections(note).sections;
1367
1441
  }
1368
1442
 
1369
1443
  /** Where a fix must be implemented: every fix runs through a flow whose gates confirm it —
@@ -1376,10 +1450,12 @@ export interface ReflectionRoute {
1376
1450
  route: string;
1377
1451
  }
1378
1452
 
1379
- export function reflectionRoutes(items: string[], selfRepo: boolean): ReflectionRoute[] {
1380
- return items.map((l) => {
1381
- const text = l.replace(/^-\s*\[[ xX]\]\s*/, "").trim();
1382
- const sections = reflectSections(text);
1453
+ export function reflectionRoutes(items: ReflectItem[], selfRepo: boolean): ReflectionRoute[] {
1454
+ return items.map((it) => {
1455
+ const text = it.line.replace(/^-\s*\[[ xX]\]\s*/, "").trim();
1456
+ // the heading the item lives under IS the filing; a both-flagged note sits under both headings
1457
+ // and therefore yields one item per section, each with its own route.
1458
+ const sections: ReflectSection[] = it.section === "unfiled" ? ["playbook"] : [it.section];
1383
1459
  if (sections.includes("plugin"))
1384
1460
  return selfRepo
1385
1461
  ? { text, sections, mode: "code" as const, route: "patch flow for a small fix (flow start fix-<topic> --patch --confirmed), normal flow when bigger" }
@@ -1388,13 +1464,34 @@ export function reflectionRoutes(items: string[], selfRepo: boolean): Reflection
1388
1464
  });
1389
1465
  }
1390
1466
 
1467
+ /** Move open item n (1-based over open items — the numbering `flow reflect list` prints) under
1468
+ * `## section`. null = out of range; an item already in that section comes back unchanged, so the
1469
+ * caller can say so instead of pretending to relocate it. */
1470
+ export function reflectMove(text: string, n: number, section: ReflectSection): string | null {
1471
+ const lines = text.split("\n");
1472
+ let seen = 0;
1473
+ let hit = -1;
1474
+ for (let i = 0; i < lines.length; i++) {
1475
+ if (!isOpenItem(lines[i])) continue;
1476
+ if (++seen === n) {
1477
+ hit = i;
1478
+ break;
1479
+ }
1480
+ }
1481
+ if (hit < 0) return null;
1482
+ const [line] = lines.splice(hit, 1);
1483
+ return appendReflection(lines.join("\n"), [section], line.trim());
1484
+ }
1485
+
1391
1486
  /** What `flow doctor <note>` prints: the note is an investigation order, not an answer —
1392
1487
  * the plugin has no LLM; the agent investigates, the gates confirm, the flow implements. */
1393
1488
  export function investigationBrief(note: string, selfRepo: boolean): string[] {
1394
- const [route] = reflectionRoutes([`- [ ] ${note}`], selfRepo);
1489
+ const guess = guessReflectSections(note);
1490
+ const [route] = reflectionRoutes([{ section: guess.sections[0], line: `- [ ] ${note.trim()}`, body: note.trim() }], selfRepo);
1395
1491
  return [
1396
1492
  `investigate: "${route.text}"`,
1397
1493
  "read first: .dev-flow/project.md, flow doctor findings, and whatever files the note names.",
1494
+ `if it is real it belongs in ## ${route.sections[0]} (${guess.why})`,
1398
1495
  `fix routing: ${route.route}`,
1399
1496
  "the note is not implemented by doctor — propose the fix to the operator first; only after they confirm, open the routed flow; its gates carry the confirmation.",
1400
1497
  ];
@@ -1403,17 +1500,17 @@ export function investigationBrief(note: string, selfRepo: boolean): string[] {
1403
1500
  /** Bare `flow reflect`: the full session-reflection protocol for the agent (the plugin has no LLM —
1404
1501
  * the agent reviews the session log, re-checks open items against shipped fixes, dedupes new
1405
1502
  * findings and puts the fix decision to the operator). Writes nothing, runs no network calls. */
1406
- export function reflectProtocol(items: string[], selfRepo: boolean, facts: { version: string | null; upstream: string; closed?: number }): string[] {
1503
+ export function reflectProtocol(items: ReflectItem[], selfRepo: boolean, facts: { version: string | null; upstream: string; closed?: number }): string[] {
1407
1504
  const ver = facts.version ? `dev-flow ${facts.version}` : "dev-flow version unknown";
1408
1505
  const up = facts.upstream || "<upstream — ask the operator for the dev-flow repo>";
1409
1506
  const url = facts.upstream ? `https://github.com/${facts.upstream}` : "<upstream-url>";
1410
1507
  const lines = [
1411
1508
  `flow reflect — session reflection (${ver}, upstream: ${up})`,
1412
1509
  "this output is your work instruction: execute these steps now — do not echo the protocol and do not ask to begin.",
1413
- "queue: .dev-flow/reflections.md — gitignored and yours to edit; check items off as `- [x] … — fixed: <what or where>`.",
1414
- "1. review the current session log in full — every message, tool call and result: friction, wrong turns, repeated failures, guards or gates that misfired, playbook drift, optimization candidates. Decide for each: playbook issue or plugin issue.",
1510
+ "queue: .dev-flow/reflections.md — gitignored and yours to edit; check items off as `- [x] … — fixed: <what or where>`; a note filed under the wrong heading is moved with flow reflect move <n> --plugin|--playbook (flow reflect list numbers them).",
1511
+ "1. review the current session log in full — every message, tool call and result: friction, wrong turns, repeated failures, guards or gates that misfired, playbook drift, optimization candidates. Decide each one BEFORE queueing — you know what the note is about, so say it: flow reflect --plugin \"<note>\" for a dev-flow bug, --playbook for this project's playbook; a note queued without a flag is filed on a keyword guess and the printed line tells you which.",
1415
1512
  `2. re-check every open item below: already handled by the current playbook (.dev-flow/project.md) or obsolete → check it off with a fixed: note. Possibly fixed in a newer dev-flow: npm view pi-dev-flow version — a newer published version covering the item → recommend the operator update the plugin (pi install npm:pi-dev-flow, then /reload; a git-installed copy updates against its own tags: git ls-remote --tags --sort=-v:refname ${url} | head -1), never update it yourself.`,
1416
- '3. new findings: dedupe against the open items first — never reflect the same issue twice; queue each real one with flow reflect "<one-line note>", then report to the operator structurally: playbook items vs plugin items, each with its route from the list below.',
1513
+ '3. new findings: dedupe against the open items first — never reflect the same issue twice; queue each real one with flow reflect --plugin|--playbook "<one-line note>", then report to the operator structurally: playbook items vs plugin items, each with its route from the list below.',
1417
1514
  "4. ask the operator whether to fix the open issues now. If yes:",
1418
1515
  ` a. plugin items: search upstream first — gh issue list --repo ${up} --state all --search "<keywords>" — an author-addressed match → report the verdict back to the operator (fixed in v… / closed won't-fix + reason), do not re-file; no match → gh issue create --repo ${up} with a detailed description, session evidence and a suggested fix.`,
1419
1516
  " b. playbook items: run flow doctor — it reviews each open item and routes it to the docs flow that implements the fix.",
@@ -1438,7 +1535,7 @@ export function reflectProtocol(items: string[], selfRepo: boolean, facts: { ver
1438
1535
  */
1439
1536
  export function appendReflection(text: string, sections: ReflectSection[], line: string): string {
1440
1537
  const lines = text.split("\n");
1441
- const sectionHeader = new RegExp(`^## (${REFLECT_SECTIONS.join("|")})\\s*$`, "i");
1538
+ const sectionHeader = REFLECT_HEADING;
1442
1539
  // shortcut: only the preamble above the first header or item survives verbatim; hand-written prose below the items is dropped.
1443
1540
  // a header is part of the body, not of the preamble: it owns the items under it, and one with no items left simply disappears from the rewrite.
1444
1541
  const firstBody = lines.findIndex((l) => l.trim().startsWith("- [") || sectionHeader.test(l.trim()));
@@ -1450,11 +1547,12 @@ export function appendReflection(text: string, sections: ReflectSection[], line:
1450
1547
  let section: ReflectSection | null = null;
1451
1548
  for (const raw of firstBody < 0 ? [] : lines.slice(firstBody)) {
1452
1549
  const l = raw.trim();
1453
- const header = sectionHeader.exec(l);
1454
- if (header) {
1550
+ if (ANY_HEADING.test(l)) {
1551
+ const header = sectionHeader.exec(l);
1455
1552
  // a heading is authoritative for the items under it: deriving the bucket from the inline
1456
1553
  // marker instead moved every marker-less `## plugin` line into `## playbook` on the next write.
1457
- section = header[1].toLowerCase() as ReflectSection;
1554
+ // an unknown `## …` heading places nothing (it used to inherit the previous section by accident).
1555
+ section = header ? (header[1].toLowerCase() as ReflectSection) : null;
1458
1556
  continue;
1459
1557
  }
1460
1558
  if (!l.startsWith("- [")) continue;