pi-dev-flow 0.79.0 → 0.80.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,23 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.80.0] - 2026-11-03
8
+
9
+ **A reflection that runs out of time still hands back its findings; release-only flows pass verify.**
10
+
11
+ ### Fixed
12
+ - **A reflection cut at its budget no longer loses its findings.** `flow_stage` workers are steered at 75% of their budget to wrap up and write the REPORT (the gh#142 grace, lost in the 0.73 slim-down, is back for every op). A worker still cut at the budget gets one tool-less prompt for its REPORT, and the result comes back marked partial instead of "aborted".
13
+ - **The reflect worker reads instead of digging.** Before it starts, the tool writes a line-tagged digest of the driver and every worker transcript into `.dev-flow/<slug>/tmp/reflect/`: operator messages, flow calls and answers, tool errors, NEEDS-OPERATOR, repeated commands. A 2.5 MB driver transcript digests to about 25 KB. The upstream issue list (all states) is prefetched into the brief, the brief states the budget, and the worker is told it reviews the session, not the product.
14
+ - **Release refuses leftover merge-conflict markers** (#164). A `<<<<<<<` / `|||||||` / `>>>>>>>` line the branch adds is named with `file:line`; `--no-marker-check` is the operator's escape.
15
+ - **A review worker on a `--docs` / `--patch` flow is no longer sent after a missing plan.md** (#167). The brief says the flow has no plan file and to judge the work against the task.
16
+ - **`--docs --no-version` no longer owes a changelog line** (#163), and the pre-release hint for a docs flow says unversioned is the usual path instead of "bump version" (#166).
17
+
18
+ ### Added
19
+ - `flow reflect done <n> ["<what>"]` checks a fixed item off, so doctor stops re-reporting it (#165).
20
+ - `- [ ] (versioned) item` in the playbook: a checklist item that only applies when the flow ships a version. It stands down on `--no-version`, so release-done stops listing tag/image proofs an unversioned flow can never satisfy (#166).
21
+ - **Release-only flows** (#161): on a versioned project, `flow verify` accepts an empty branch when the default branch has unreleased commits since the newest version tag. The version bump is the pre-release commit, as the playbook says, and the release gate does not count it as a post-verify change. With nothing unreleased, verify says there is nothing to release.
22
+ - `flow release` names commits made after the operator's Verified? (verify now stamps the HEAD it was given over). It warns and never refuses (#162).
23
+
7
24
  ## [0.79.0] - 2026-11-03
8
25
 
9
26
  **Scratch files live in the feature folder and go away at finish.**
package/docs/gates.md CHANGED
@@ -15,11 +15,11 @@ so it needs no `--confirmed`.
15
15
  | `test` | records a check | — (runs the `test` command/check, records pass/fail) |
16
16
  | `check` | records all tier-1 checks | — (runs every `flow-check`/test/health from project.md `## implement`); a `--docs` feature runs none of them and says `docs mode: project commands skipped` — a docs flow builds nothing, so a fresh checkout must not read as a failed deploy (#96) |
17
17
  | `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
18
- | `verify [--yolo]` | implement → pre-release | all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`); with **no `dev` command but a `health` probe configured the gate live-re-probes the app before asking** (`health: live re-probe PASS` — a killed server refuses with `live probe FAILED`, because process death dirties no worktree fingerprint and a green record alone cannot prove liveness: start the app and rerun), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
19
- | `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; `release.preflight` (when set) passes in the worktree — the build the tag will trigger, proven before anything ships; **the worktree holds no uncommitted paths** (gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix that never ships; the refusal lists the paths, and the approved line prints `commits: N ahead of <default>, M uncommitted path(s)` like verify's); with `versioning.file`: the manifest version parses and is **not tagged yet** (the bump must be ahead of the last release); with `release.changelog` the gate **proves the entry mechanically** (#97): a **heading names the version** (prose that mentions it, or a `1.2.0-beta` section when releasing `1.2.0`, is not an entry), **this branch touched the file** (an inherited changelog is not release prep), **every entry that was pending before the release survives inside the new section** — compared on normalized lines, so re-indenting a fold is free while rewording or deleting one is refused by naming the line — and **nothing is left under `Unreleased`**. The proofs guard the **baseline's** pending lines — they do not freeze the wording of the entry this flow writes, so a branch that landed as several iteration commits is free to state its result as one entry (see the changelog-writer rule in the pre-release reference). The pending baseline is the newest tag's changelog (what actually shipped), else the branch's merge base; when neither resolves, the two git-dependent proofs are skipped **with a printed advisory** rather than refusing a legal release for a topology reason, and the content proofs (the heading, its body) always run; tier-2 `## pre-release` checklist confirmed; the manifest version it validates is **stamped as the release's version of record** (`release-done` publishes that, whatever the checkouts say later); **one question** (Release?) — or `--confirmed`; `--no-version` (your call at Release?) ships this flow as **merge + changelog** — the bump/tag requirements and the tag checks at `release-done` are skipped for it, but the branch must still add its **own line under `Unreleased`** (editing an older section releases nothing) and it rides there until the next versioned release folds it (default: versioned); `--no-fold-check` is the operator-granted escape from the line-level fold proofs — one flow, stamped in the gate output, the heading and touched proofs stay; **stale session build** (loaded build behind the checkout): the gate prints both builds, lists what shipped between them (those proofs will not run this release) and folds *update (/reload, then re-run) or proceed with the old release?* into the Release? question — the operator's word, recorded in the release output, **never a block**: publishing under an older gate is a legitimate choice (hotfix, offline reload) |
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
+ | `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
21
  | `finish [--yolo] [slug]` | release → done (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes (the refusal lists the paths, not just the count — gh#131); when the clean checkout trails `origin/<default>` the gate **fast-forwards local main** as it closes out (never a merge — anything that cannot fast-forward prints the operator's exact `git pull --ff-only` command); **one question** (Finish? — mentions unmerged-looking commits with the playbook's `merge` policy in mind, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; under `merge = merge`, commits that never reached the default branch are a **policy violation**: `yolo` does not answer it, only your explicit answer does; to abandon an unreleased feature use `abort` |
22
- | `reflect ["<note>"|list|tidy|move <n> --playbook|--code]` | — | `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; 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 |
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>" \| 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
24
  | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — the state of an **aborted** feature is never a finding (its worktree cleanup is by design — gh#138) — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
25
25
  | `status [slug]` / `abort [slug]` | — | — |
package/docs/playbook.md CHANGED
@@ -52,7 +52,7 @@ executable checks and hard safety rules:
52
52
  |---|---|---|
53
53
  | 1 — executable | ` ```flow` (`key = value`) config blocks; ` ```flow-check <name>` command blocks | gates run every check, record pass/fail against a worktree fingerprint, a changed tree makes them stale — hard |
54
54
  | 1 — guard | ` ```flow-guard ` (`deny`/`confirm`/`protect`/`forbid`) rules in `## global` | enforced on every bash command and every edit/write path, at every stage — hard block or operator confirmation |
55
- | 2 — checklist | `- [ ] item` lines (`- [ ] (ui) item` = only for `--ui` features) | gate confirms cover them as a set (hashed: changing the items asks again); `(ui)` items never appear for non-UI features |
55
+ | 2 — checklist | `- [ ] item` lines (`- [ ] (ui) item` = only for `--ui` features; `- [ ] (versioned) item` = only when the flow ships a version — it stands down on `--no-version`) | gate confirms cover them as a set (hashed: changing the items asks again); `(ui)` items never appear for non-UI features, `(versioned)` items never for an unversioned flow (a deploy proof of the tagged image, say) |
56
56
  | 3 — prose | any other text | injected to the agent when its stage begins — advisory |
57
57
 
58
58
  Example `## implement` section:
@@ -72,6 +72,7 @@ import {
72
72
  guessReflectSections,
73
73
  reflectItems,
74
74
  reflectMove,
75
+ reflectDone,
75
76
  reflectProtocol,
76
77
  reflectUnfiledCount,
77
78
  reflectLegacyPluginCount,
@@ -82,6 +83,13 @@ import {
82
83
  parseReflectReport,
83
84
  renderReflectFindings,
84
85
  childSessionFiles,
86
+ conflictMarkerLines,
87
+ isReleaseOnly,
88
+ digestTranscript,
89
+ workerSteer,
90
+ WORKER_STEER_AT,
91
+ WORKER_SALVAGE,
92
+ WORKER_SALVAGE_MS,
85
93
  WORKER_NUDGE_READONLY,
86
94
  type SessionHeaderInfo,
87
95
  reflectionLine,
@@ -369,7 +377,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
369
377
  }
370
378
 
371
379
  const GATE_HELP =
372
- "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] | roadmap [add <text>|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] | 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 — 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, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — 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)";
380
+ "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>|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> stamps an item for flow start, finish checks it off — 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)";
373
381
  const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
374
382
  const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
375
383
  const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -716,10 +724,23 @@ async function branchState(cwd: string, defaultBranch: string): Promise<BranchSt
716
724
  };
717
725
  }
718
726
 
727
+ /** Commits HEAD carries since the newest local version tag (all of them before the first release) —
728
+ * local refs only, so the probe stays offline-safe. HEAD is the default branch's tip on an empty branch. */
729
+ async function unreleasedOnMain(cwd: string, pattern: string): Promise<{ count: number | null; since: string | null }> {
730
+ const tags = await sh("git tag --list", cwd);
731
+ const newest = tags.ok ? newestTaggedVersion(pattern, tags.out.split("\n").map((t) => t.trim()).filter(Boolean)) : null;
732
+ const since = newest ? pattern.replace("{version}", newest) : null;
733
+ const r = await sh(since ? `git rev-list --count ${sq(since)}..HEAD` : "git rev-list --count HEAD", cwd);
734
+ const n = Number.parseInt(r.out.trim(), 10);
735
+ return { count: r.ok && Number.isFinite(n) ? n : null, since };
736
+ }
737
+
719
738
  function describeBranchState(b: BranchState, defaultBranch: string): string {
720
- return b.commitsAhead === null
721
- ? `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`
722
- : `commits: ${b.commitsAhead} ahead of ${defaultBranch}, ${b.uncommitted} uncommitted path(s)`;
739
+ if (b.commitsAhead === null) return `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`;
740
+ const line = `commits: ${b.commitsAhead} ahead of ${defaultBranch}, ${b.uncommitted} uncommitted path(s)`;
741
+ return b.commitsAhead === 0 && (b.unreleased?.count ?? 0) > 0
742
+ ? `${line} — release-only flow: ${b.unreleased!.count} unreleased commit(s) on ${defaultBranch}${b.unreleased!.since ? ` since ${b.unreleased!.since}` : " (nothing tagged yet)"}; verify proves that tree, the version bump is the pre-release commit`
743
+ : line;
723
744
  }
724
745
 
725
746
  // ---------------------------------------------------------------- gate runner
@@ -941,6 +962,21 @@ function reflectMoveNote(root: string, args: string[], forced: ReflectTarget | n
941
962
  return { text: twin ? `reflect: item ${n} was already recorded under ## ${section} — the duplicate is gone (${note})` : `reflect: item ${n} re-filed under ## ${section} — ${note}` };
942
963
  }
943
964
 
965
+ /** `flow reflect done <n> [what fixed it]` — check a folded/fixed item off, so doctor stops re-reporting it (#165). */
966
+ function reflectDoneNote(root: string, sess: Session, args: string[]): RunResult {
967
+ const text = readReflectionsText(root);
968
+ const items = reflectItems(text);
969
+ const n = Number(args[0]);
970
+ if (!Number.isInteger(n) || n < 1 || n > items.length)
971
+ return { text: items.length ? `done: open item 1–${items.length} required — flow reflect list numbers them` : "done: nothing open in reflections.md", isError: true };
972
+ const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
973
+ const what = args.slice(1).join(" ").trim();
974
+ const next = reflectDone(text, n, what ? `${stamp} — ${what}` : stamp)!;
975
+ writeFileSync(path.join(dfDir(root), "reflections.md"), next);
976
+ const { tidy } = reflectionNudges(next, now().slice(0, 10));
977
+ return { text: `reflect: item ${n} checked off — ${items[n - 1].body}` + (tidy ? `\n${tidy}` : "") };
978
+ }
979
+
944
980
  /** `flow reflect tidy` — drop the closed (`- [x]`) items; the `— fixed:` note already recorded the outcome. */
945
981
  function reflectTidy(root: string): RunResult {
946
982
  const file = path.join(dfDir(root), "reflections.md");
@@ -1043,6 +1079,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1043
1079
  if (err) return err;
1044
1080
  const items = applicableItems(cfg, state!, "implement");
1045
1081
  const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
1082
+ if (branch.commitsAhead === 0 && cfg.versioning.file) branch.unreleased = await unreleasedOnMain(gateCwd(root, state!), cfg.versioning.pattern);
1046
1083
  const branchLine = describeBranchState(branch, cfg.defaultBranch);
1047
1084
  // A green record belongs to the tree it ran against. A worktree change made through bash (sed,
1048
1085
  // a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
@@ -1125,6 +1162,12 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1125
1162
  const final = verifyGate(state!, cfg, branch);
1126
1163
  if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
1127
1164
  state!.approvals.verify = now();
1165
+ if (isReleaseOnly(cfg, branch)) state!.releaseOnly = true;
1166
+ else delete state!.releaseOnly;
1167
+ // the tree the word was given over (#162) — a git that cannot answer leaves it unset, never a refusal
1168
+ const vHead = await sh("git rev-parse HEAD", gateCwd(root, state!));
1169
+ if (vHead.ok && vHead.out.trim()) state!.verifiedHead = vHead.out.trim();
1170
+ else delete state!.verifiedHead;
1128
1171
  state!.stage = "pre-release";
1129
1172
  delete state!.pendingAsk;
1130
1173
  writeState(root, state!);
@@ -1135,9 +1178,10 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1135
1178
  const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
1136
1179
  const { state, err } = needState(root, sess, slugArg);
1137
1180
  if (err) return err;
1138
- const items = applicableItems(cfg, state!, "pre-release");
1139
1181
  // operator's word at Release?: this flow ships without a version bump or tag — recorded only once Release? is answered
1140
1182
  const noVersion = flag("no-version") || !!state!.noVersion;
1183
+ // (versioned) items stand down on an unversioned flow — the set confirmed here is the one that applies to it
1184
+ const items = applicableItems(cfg, { ...state!, noVersion }, "pre-release");
1141
1185
  // yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
1142
1186
  const yoloWord = takeYoloWord(state!);
1143
1187
  if (yoloWord) return { text: yoloWord, isError: true };
@@ -1190,7 +1234,11 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1190
1234
  }
1191
1235
  }
1192
1236
  }
1193
- const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
1237
+ // #164: a hand-resolved merge can commit a leftover marker — content to git, so nothing else catches it
1238
+ const markerBase = await mergeBase(wtCwd, cfg.defaultBranch);
1239
+ const markerDiff = markerBase ? await sh(`git diff -U0 --no-color --no-ext-diff ${sq(markerBase)} HEAD`, wtCwd) : null;
1240
+ const conflictMarkers = markerDiff?.ok ? conflictMarkerLines(markerDiff.out) : undefined;
1241
+ const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check"), conflictMarkers, noMarkerCheck: flag("no-marker-check") };
1194
1242
  // same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
1195
1243
  if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
1196
1244
  // tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
@@ -1223,14 +1271,27 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1223
1271
  `Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
1224
1272
  staleNote = `released under dev-flow ${behind} (${selfBuild.label} ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
1225
1273
  }
1274
+ // #162: Verified? was answered over one tree; commits after it ship under that word unless someone says
1275
+ // so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
1276
+ let postVerify = "";
1277
+ if (state!.verifiedHead) {
1278
+ const since = await sh(`git log --oneline --no-decorate ${sq(state!.verifiedHead)}..HEAD`, wtCwd);
1279
+ const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
1280
+ // a release-only flow commits its bump and changelog after verify by design — only other files count
1281
+ const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
1282
+ const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
1283
+ const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
1284
+ if (commits.length && !prepOnly)
1285
+ postVerify = `${commits.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${commits.slice(0, 6).join(" | ")}${commits.length > 6 ? ` …(${commits.length - 6} more)` : ""} — the verify verdict does not cover them: if behaviour changed, have the operator check the current build before Release?, and either way say in the PR body which commit the verdict was given over`;
1286
+ }
1226
1287
  const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
1227
1288
  const askPending = !flag("confirmed") && !state!.yolo;
1228
1289
  if (askPending) {
1229
1290
  markPendingAsk(root, state!, "Release?");
1230
1291
  if (!ui.hasUI) {
1231
- return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}`, "Release?"), isError: true };
1292
+ return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}${postVerify ? ` — tell them: ${postVerify}` : ""}`, "Release?"), isError: true };
1232
1293
  }
1233
- const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}`);
1294
+ const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}${postVerify ? `\n\n${postVerify}` : ""}`);
1234
1295
  if (!ok) {
1235
1296
  delete state!.pendingAsk;
1236
1297
  writeState(root, state!);
@@ -1255,7 +1316,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
1255
1316
  if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
1256
1317
  delete state!.pendingAsk;
1257
1318
  writeState(root, state!);
1258
- return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
1319
+ return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}${postVerify ? ` Warning: ${postVerify}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
1259
1320
  }
1260
1321
 
1261
1322
  async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
@@ -1876,6 +1937,7 @@ async function gateReflect(o: GateCtx): Promise<RunResult> {
1876
1937
  if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
1877
1938
  if (words.length === 1 && words[0] === "list") return await reflectList(root);
1878
1939
  if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
1940
+ if (words[0] === "done") return reflectDoneNote(root, sess, words.slice(1));
1879
1941
  if (words.length) return await reflectNote(root, sess, words, forced);
1880
1942
  const self = pluginVersion(import.meta.dirname);
1881
1943
  const upstream = await pluginUpstream(root);
@@ -2092,6 +2154,43 @@ const workerSessions = new Set<string>();
2092
2154
  /** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
2093
2155
  const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"], reflect: ["read", "bash"] };
2094
2156
 
2157
+ /** Test-only timer override: the smoke suite drives the steer, the hard cut and the salvage grace in ms. */
2158
+ export const workerTiming: { softMs?: number; hardMs?: number; graceMs?: number } = {};
2159
+
2160
+ /** The upstream dev-flow repo's issues in every state, for the reflect brief's dedupe — prefetched so
2161
+ * the worker reads a list instead of looping gh searches. null = gh could not answer (the brief then
2162
+ * falls back to the search recipe). */
2163
+ async function upstreamIssueList(root: string, repo: string): Promise<{ number: number; title: string; state: string }[] | null> {
2164
+ if (!repo || process.env.DEV_FLOW_NO_ISSUES) return null;
2165
+ const r = await sh(`gh issue list --repo ${sq(repo)} --state all --json number,title,state --limit 200`, root, 15_000);
2166
+ if (!r.ok) return null;
2167
+ try {
2168
+ const a = JSON.parse(r.out) as { number?: unknown; title?: unknown; state?: unknown }[];
2169
+ return Array.isArray(a) ? a.filter((i) => Number.isInteger(i?.number)).map((i) => ({ number: Number(i.number), title: String(i.title ?? ""), state: String(i.state ?? "") })) : null;
2170
+ } catch {
2171
+ return null;
2172
+ }
2173
+ }
2174
+
2175
+ /** Seam: the smoke suite stubs the prefetch instead of calling gh against the real upstream. */
2176
+ export const reflectSeams = { upstreamIssues: upstreamIssueList };
2177
+
2178
+ /** Build the reflect worker's transcript digests in the feature's scratch dir (driver first). A
2179
+ * transcript that cannot be read is skipped — the brief still names the raw file. */
2180
+ function writeTranscriptDigests(root: string, slug: string, files: string[]): { transcript: string; digest: string }[] {
2181
+ const dir = path.join(featureTmpDir(dfDir(root), slug), "reflect");
2182
+ const out: { transcript: string; digest: string }[] = [];
2183
+ for (const f of files) {
2184
+ try {
2185
+ mkdirSync(dir, { recursive: true });
2186
+ const digest = path.join(dir, `${path.basename(f, ".jsonl")}.digest.txt`);
2187
+ writeFileSync(digest, digestTranscript(readFileSync(f, "utf8")));
2188
+ out.push({ transcript: f, digest });
2189
+ } catch { /* unreadable transcript: the raw path stays in the brief */ }
2190
+ }
2191
+ return out;
2192
+ }
2193
+
2095
2194
  /** Line 1 of every pi session file in `dir` — the header that names a worker's parent session. A
2096
2195
  * file is read up to its first newline only (transcripts grow large); unreadable files are skipped. */
2097
2196
  function sessionHeaders(dir: string | undefined): SessionHeaderInfo[] {
@@ -2467,15 +2566,20 @@ export default function devFlow(pi: ExtensionAPI) {
2467
2566
  ? await (async () => {
2468
2567
  const items = readReflections(root);
2469
2568
  const fold = await foldView(root, items);
2569
+ const upstream = await pluginUpstream(root);
2570
+ const children = lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [];
2470
2571
  return buildReflectBrief({
2471
2572
  slug: st.slug, root, today: now().slice(0, 10),
2472
2573
  driverFile: lineage.file ?? null,
2473
- children: lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [],
2574
+ children,
2575
+ digests: lineage.file ? writeTranscriptDigests(root, st.slug, [lineage.file, ...children.map((c) => c.file)]) : [],
2576
+ upstreamIssues: (await reflectSeams.upstreamIssues(root, upstream)) ?? undefined,
2577
+ budgetMin,
2474
2578
  reflectionsFile: path.join(dfDir(root), "reflections.md"),
2475
2579
  items,
2476
2580
  projectMd: path.join(dfDir(root), "project.md"),
2477
2581
  version: pluginVersion(import.meta.dirname).version,
2478
- upstream: await pluginUpstream(root),
2582
+ upstream,
2479
2583
  selfRepo,
2480
2584
  projectIssues: fold.state === "ok" && !selfRepo ? { repo: fold.slug, issues: fold.result.upstreamOnly.map((i) => ({ number: i.number, title: i.title })) } : undefined,
2481
2585
  note: String(params.note ?? ""),
@@ -2483,7 +2587,7 @@ export default function devFlow(pi: ExtensionAPI) {
2483
2587
  })()
2484
2588
  : buildWorkerBrief({
2485
2589
  op: wop, slug: st.slug, workDir: work,
2486
- planFile: path.join(featDir(root, st.slug), "plan", "plan.md"),
2590
+ planFile: ((f) => (existsSync(f) ? f : null))(path.join(featDir(root, st.slug), "plan", "plan.md")),
2487
2591
  defaultBranch: cfg.defaultBranch,
2488
2592
  commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
2489
2593
  status: await git("git status --short"),
@@ -2495,11 +2599,20 @@ export default function devFlow(pi: ExtensionAPI) {
2495
2599
  const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
2496
2600
  let child: AgentSession | undefined;
2497
2601
  let timedOut = false;
2602
+ let steered = false;
2603
+ let salvaged = false;
2498
2604
  let crash: string | null = null;
2499
2605
  let nudges = 0;
2500
2606
  let report = parseWorkerReport("");
2501
2607
  const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
2502
- const timer = setTimeout(() => { timedOut = true; abortChild(); }, budgetMin * 60_000);
2608
+ const hardMs = workerTiming.hardMs ?? budgetMin * 60_000;
2609
+ // grace before the cliff (gh#142): steered at 75% to wrap up, so a long run hands back a REPORT
2610
+ // instead of being cut mid-thought — the hard timer stays the backstop
2611
+ const softTimer = setTimeout(() => {
2612
+ steered = true;
2613
+ try { void Promise.resolve(child?.steer(workerSteer(wop, budgetMin))).catch(() => {}); } catch { /* the hard cut follows */ }
2614
+ }, workerTiming.softMs ?? Math.round(hardMs * WORKER_STEER_AT));
2615
+ const timer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
2503
2616
  signal?.addEventListener("abort", abortChild);
2504
2617
  let unsub: (() => void) | undefined;
2505
2618
  let releaseLive: (status: string) => void = () => {};
@@ -2524,9 +2637,24 @@ export default function devFlow(pi: ExtensionAPI) {
2524
2637
  await child.prompt(wop === "implement" ? WORKER_NUDGE : WORKER_NUDGE_READONLY);
2525
2638
  report = parseWorkerReport(child.getLastAssistantText() ?? "");
2526
2639
  }
2640
+ // cut at the budget without a REPORT: one short, tool-less turn to hand back what it found —
2641
+ // an aborted reflection otherwise loses every finding it had already made
2642
+ if (!report.found && timedOut && !signal?.aborted) {
2643
+ salvaged = true;
2644
+ const grace = setTimeout(abortChild, workerTiming.graceMs ?? WORKER_SALVAGE_MS);
2645
+ try {
2646
+ await child.prompt(WORKER_SALVAGE);
2647
+ report = parseWorkerReport(child.getLastAssistantText() ?? "");
2648
+ } catch {
2649
+ /* a failed salvage is still an interrupted run, not a crash */
2650
+ } finally {
2651
+ clearTimeout(grace);
2652
+ }
2653
+ }
2527
2654
  } catch (e) {
2528
2655
  crash = e instanceof Error ? e.message : String(e);
2529
2656
  } finally {
2657
+ clearTimeout(softTimer);
2530
2658
  clearTimeout(timer);
2531
2659
  signal?.removeEventListener("abort", abortChild);
2532
2660
  unsub?.();
@@ -2536,14 +2664,20 @@ export default function devFlow(pi: ExtensionAPI) {
2536
2664
  const headAfter = (await git("git rev-parse HEAD")).trim();
2537
2665
  const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
2538
2666
  const dirty = (await git("git status --short")).trim();
2539
- const outcome = crash ? `crashed: ${crash}` : timedOut ? `interrupted at the ${budgetMin}-min budget` : report.found ? "reported" : `ended without REPORT after ${nudges} nudge(s)`;
2667
+ const outcome = crash
2668
+ ? `crashed: ${crash}`
2669
+ : timedOut
2670
+ ? `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" : ""}`
2671
+ : report.found
2672
+ ? `reported${steered ? " (after the wrap-up steer)" : ""}`
2673
+ : `ended without REPORT after ${nudges} nudge(s)`;
2540
2674
  // the terminal entry is what settles the Agents menu row (a persisted `running` the host
2541
2675
  // cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a ✓.
2542
2676
  if (subagent) {
2543
2677
  const doneAt = now();
2544
2678
  const final = crash
2545
2679
  ? { version: 1, status: "failed", completedAt: doneAt, error: crash }
2546
- : timedOut || signal?.aborted
2680
+ : signal?.aborted || (timedOut && !report.found)
2547
2681
  ? { version: 1, status: "aborted", completedAt: doneAt }
2548
2682
  : report.found
2549
2683
  ? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
@@ -2554,7 +2688,7 @@ export default function devFlow(pi: ExtensionAPI) {
2554
2688
  }
2555
2689
  releaseLive("failed"); // idempotent guard: a throw between claim and result must not leave a live row
2556
2690
  try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
2557
- try { child?.setSessionName(`${report.found && !crash && !timedOut && !signal?.aborted ? "✓" : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2691
+ try { child?.setSessionName(`${report.found && !crash && !signal?.aborted ? (timedOut ? "◐" : "✓") : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
2558
2692
  const parts = [`${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`];
2559
2693
  let reflected: ReturnType<typeof parseReflectReport> | null = null;
2560
2694
  if (wop === "reflect") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.79.0",
3
+ "version": "0.80.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": [
@@ -14,7 +14,9 @@ the session context goes with it. Run the end-of-session reflection now:
14
14
  **docs** (fix only in `project.md` → docs flow), **code** (fix in this
15
15
  project's code, maybe the playbook too → patch flow) or **plugin** (dev-flow
16
16
  itself → GitHub issue upstream), with a **fold** or **drop** recommendation.
17
- `note` = anything the operator said about friction this session. If the
17
+ `note` = anything the operator said about friction this session. The tool
18
+ prebuilds a line-tagged digest of every transcript and prefetches the
19
+ upstream issues, so the worker reads instead of dumping and searching. If the
18
20
  worker fails, run the review inline (bare `flow reflect` prints the protocol).
19
21
  2. Show the operator the list with your recommendation per item and ask
20
22
  **fold or drop** for each (`fold 1,3 drop 2` is a fine answer) — then stop.
@@ -17,7 +17,9 @@ feature).
17
17
  the end faces review blind and is not crash-safe. The gate enforces the
18
18
  habit: `flow verify` refuses while the branch holds **no commit** (checks
19
19
  describe the working tree, so nothing committed means nothing reviewed was
20
- ever recorded) and every verify line reports
20
+ ever recorded; a **release-only flow** — a versioned project whose code is
21
+ already on main, unreleased since the last tag — passes with an empty branch,
22
+ and its bump is the pre-release commit) and every verify line reports
21
23
  `commits: N ahead of <default>, M uncommitted path(s)` — uncommitted paths
22
24
  never block verify, they are what the operator sees they are approving.
23
25
  2. Write tests as you go (project framework: the `test` key / `flow-check`
@@ -111,6 +113,10 @@ resending the same note.
111
113
  - One worker at a time per session. The worker holds no flow tool, so gates
112
114
  and checkpoints stay with you. Its transcript nests under this session in
113
115
  pi's picker.
116
+ - Budget (`budgetMin`; default 60 implement, 30 review, 20 reflect): at 75% the
117
+ worker is steered to wrap up and report. A worker cut at the budget is asked
118
+ once, with no tools, for its REPORT, so what it found comes back marked
119
+ partial instead of being lost.
114
120
 
115
121
  `flow verify` re-runs build, runs the `dev` deploy when configured (the
116
122
  operator reviews the running app; the gate **prints what it ran** —
@@ -25,7 +25,9 @@ Gate flags are ignored (`flow reflect "<note>" --confirmed` queues the note
25
25
  alone). With no flag the wording guesses (plugin-shaped → the upstream recipe,
26
26
  otherwise `## playbook`) and the printed line says why; `flow reflect list`
27
27
  numbers the queue and `flow reflect move <n> --playbook|--code` re-files an
28
- item — never hand-retype it. A legacy `## plugin` row from an older dev-flow is
28
+ item — never hand-retype it. `flow reflect done <n> ["<what fixed it>"]` checks
29
+ an item off once a flow has fixed it (`— fixed: <date> <slug> — <what>`), so
30
+ doctor stops re-reporting it. A legacy `## plugin` row from an older dev-flow is
29
31
  flagged by `flow doctor` / `reflect list`: file it upstream and check it off
30
32
  `— filed: gh#NNN`. For a note to chase **now**: `flow doctor "<observation>"`
31
33
  prints an investigation brief without queueing.
@@ -50,9 +52,10 @@ prints an investigation brief without queueing.
50
52
  - Plain `flow doctor` reviews the open items and **routes** each — `## playbook`
51
53
  → docs flow, `## code` → patch flow. To fold items in on the operator's word:
52
54
  investigate, propose the fix, get confirmation, open the routed flow and apply
53
- it there — project.md is editable only in a docs/patch worktree. Check items
54
- off in `.dev-flow/reflections.md` (gitignored, yours to edit; not
55
- `project.md`) with `- [x]` and a `— folded: <what>` or `— fixed: <what>` note.
55
+ it there — project.md is editable only in a docs/patch worktree. Once it is
56
+ merged, check the item off with `flow reflect done <n> "<what>"` (or by hand in
57
+ the gitignored `.dev-flow/reflections.md`: `- [x]` and a `— folded: <what>` or
58
+ `— fixed: <what>` note).
56
59
  - **Open GitHub issues fold into the view** when the repo has a GitHub remote: `flow doctor` and
57
60
  `flow reflect list` list them under the local queue (read-time fold — issues are never imported,
58
61
  each item keeps one home). A local row an open issue already covers carries `⟷ gh#NNN` — fold it
package/src/core.ts CHANGED
@@ -47,14 +47,18 @@ export interface FlowState {
47
47
  forgeReleaseSkipped?: string; // a gh/glab release create that failed: release-done says so, finish names it so the missing forge release cannot slip past (#63)
48
48
  staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
49
49
  pendingAsk?: string; // the checkpoint word a gate asked for and has not been given ("Approve?", "Verified?", …) — presentation only (💬 in the footer), it never gates
50
+ releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
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)
50
52
  reflectedAt?: string; // a flow_stage reflect worker reported for this flow — finish names a missing one (advisory, never a block)
51
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
52
54
  }
53
55
 
54
- /** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features. */
56
+ /** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features;
57
+ * versionedOnly items ("(versioned)") presuppose a bump/tag and stand down on a --no-version flow (#166). */
55
58
  export interface ChecklistItem {
56
59
  text: string;
57
60
  uiOnly: boolean;
61
+ versionedOnly?: boolean;
58
62
  }
59
63
 
60
64
  export interface Commands {
@@ -270,15 +274,29 @@ export function approveGate(state: FlowState, cfg: Config, planFiles: string[],
270
274
  export interface BranchState {
271
275
  commitsAhead: number | null;
272
276
  uncommitted: number;
277
+ /** Only measured when nothing is committed on a versioned project: commits on the default branch since
278
+ * the newest version tag (every commit when none is tagged yet), and that tag. > 0 = a release-only
279
+ * flow — main carries the code, the flow only cuts the version (#161). null = git could not answer. */
280
+ unreleased?: { count: number | null; since: string | null };
273
281
  }
274
282
 
283
+ /** A release-only flow: nothing on the branch, but the default branch holds unreleased work to version (#161). */
284
+ export const isReleaseOnly = (cfg: Config, branch?: BranchState | null): boolean =>
285
+ !!cfg.versioning.file && branch?.commitsAhead === 0 && (branch.unreleased?.count ?? 0) > 0;
286
+
275
287
  /** Gate: implement → release. Tier 1: every parsed check green; tier 2: checklist confirmed;
276
288
  * the branch must hold at least one commit — checks describe the working tree, so with nothing
277
289
  * committed the operator is asked to approve state no gate has ever seen. */
278
290
  export function verifyGate(state: FlowState, cfg: Config, branch?: BranchState | null): string[] {
279
291
  const errs: string[] = [];
280
292
  if (state.stage !== "implement") errs.push(`stage is "${state.stage}", verify only applies to "implement"`);
281
- if (branch && branch.commitsAhead === 0) errs.push("nothing committed on the feature branch yet — commit as you go, verify proves a committed state");
293
+ // a release-only flow (#161) proves main's committed tree here; its version bump is the pre-release commit
294
+ if (branch && branch.commitsAhead === 0 && !isReleaseOnly(cfg, branch))
295
+ errs.push(
296
+ cfg.versioning.file && branch.unreleased?.count === 0
297
+ ? `nothing committed on the feature branch, and ${branch.unreleased.since ? `nothing landed on the default branch since ${branch.unreleased.since}` : "the default branch has nothing to release"} — there is nothing to verify or release`
298
+ : "nothing committed on the feature branch yet — commit as you go, verify proves a committed state",
299
+ );
282
300
  if (!state.docs) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check`);
283
301
  const pend = checklistPending(cfg, state, "implement");
284
302
  if (pend) errs.push(`tier-2 checklist not confirmed (${pend} item(s)) — run flow verify after ticking them off`);
@@ -301,6 +319,30 @@ export interface ReleasePrep {
301
319
  changelogBase?: { pending: string[]; source: "tag" | "merge-base" | "none" };
302
320
  /** Operator-granted escape from the line-level fold proofs (`flow release --no-fold-check`). */
303
321
  noFoldCheck?: boolean;
322
+ /** Conflict-marker lines the branch adds vs its merge base (`file:line: text`) — a hand-resolved merge
323
+ * that kept one ships it otherwise (#164). Undefined = not measured (no merge base). */
324
+ conflictMarkers?: string[];
325
+ /** Operator-granted escape for a branch that adds marker-shaped lines on purpose (`--no-marker-check`). */
326
+ noMarkerCheck?: boolean;
327
+ }
328
+
329
+ /** Added lines in a unified diff (`git diff -U0 <base>`) that are merge-conflict markers, as
330
+ * `file:line: text`. Only the unambiguous markers count — `<<<<<<<`, `|||||||`, `>>>>>>>` at the line start
331
+ * followed by a space or the end of the line; a bare `=======` is also a markdown heading underline. */
332
+ export function conflictMarkerLines(diff: string): string[] {
333
+ const out: string[] = [];
334
+ let file = "";
335
+ let line = 0;
336
+ for (const l of (diff ?? "").split("\n")) {
337
+ if (l.startsWith("+++ ")) { file = l.slice(4).replace(/^b\//, ""); continue; }
338
+ const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(l);
339
+ if (h) { line = Number(h[1]); continue; }
340
+ if (l.startsWith("+")) {
341
+ if (/^(<{7}|\|{7}|>{7})( |$)/.test(l.slice(1))) out.push(`${file}:${line}: ${l.slice(1).slice(0, 80)}`);
342
+ line++;
343
+ }
344
+ }
345
+ return out;
304
346
  }
305
347
 
306
348
  /** One changelog line as the fold proofs compare it: indentation, bullet style and whitespace runs are
@@ -386,10 +428,14 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
386
428
  if (!state.docs) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check`);
387
429
  const pend = checklistPending(cfg, state, "pre-release");
388
430
  if (pend) errs.push(`tier-2 checklist not confirmed (${pend} item(s)) — run flow release after ticking them off`);
431
+ if (prep.conflictMarkers?.length && !prep.noMarkerCheck)
432
+ errs.push(`the branch adds ${prep.conflictMarkers.length} merge-conflict marker line(s) — a hand-resolved merge kept them; fix and commit (or, when the lines are meant, re-run with --no-marker-check on the operator's word):\n ${prep.conflictMarkers.slice(0, 5).join("\n ")}${prep.conflictMarkers.length > 5 ? `\n …(${prep.conflictMarkers.length - 5} more)` : ""}`);
389
433
  if (state.noVersion) {
390
434
  // unversioned flow (operator granted --no-version): no bump, no tag, no forge release —
391
- // but the merge still owes a changelog line under Unreleased, folded by the next versioned release
392
- if (cfg.release.changelog) {
435
+ // but the merge still owes a changelog line under Unreleased, folded by the next versioned release.
436
+ // A --docs flow does not (#163): it changes the playbook/docs, which many projects keep out of a
437
+ // user-facing changelog — an entry it writes is still welcome, just not proven.
438
+ if (cfg.release.changelog && !state.docs) {
393
439
  if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — an unversioned release must record its entry there (under Unreleased)`);
394
440
  else {
395
441
  if (prep.changelogChanged === false) errs.push(`${prep.changelog.file} is unchanged on this branch — an unversioned release must add its entry (under Unreleased)`);
@@ -448,7 +494,7 @@ export function unreleasedPending(content: string): boolean {
448
494
 
449
495
  export function checklistHash(items: ChecklistItem[]): string {
450
496
  return createHash("sha1")
451
- .update(items.map((i) => `${i.uiOnly ? "(ui) " : ""}${i.text}`).join("\n"))
497
+ .update(items.map((i) => `${i.uiOnly ? "(ui) " : ""}${i.versionedOnly ? "(versioned) " : ""}${i.text}`).join("\n"))
452
498
  .digest("hex")
453
499
  .slice(0, 12);
454
500
  }
@@ -485,7 +531,7 @@ export function freshenChecks(state: FlowState, fp: string | null, keep: (name:
485
531
 
486
532
  /** Items that apply to this feature — "(ui)" items only when the UI flag is set. */
487
533
  export function applicableItems(cfg: Config, state: FlowState, stage: string): ChecklistItem[] {
488
- return (cfg.checklist[stage] ?? []).filter((i) => !i.uiOnly || state.ui);
534
+ return (cfg.checklist[stage] ?? []).filter((i) => (!i.uiOnly || state.ui) && (!i.versionedOnly || !state.noVersion));
489
535
  }
490
536
 
491
537
  /** Items exist for the stage and current confirmation does not match their hash; returns pending count or 0. */
@@ -1703,6 +1749,20 @@ export function reflectMove(text: string, n: number, section: ReflectSection): s
1703
1749
  return appendReflection(lines.join("\n"), [section], line.trim());
1704
1750
  }
1705
1751
 
1752
+ /** Check open item `n` (the `flow reflect list` numbering) off: `- [x] … — fixed: <note>` — the convention
1753
+ * doctor reads as closed, so a folded item stops re-nagging (#165). null when there is no item `n`. */
1754
+ export function reflectDone(text: string, n: number, note: string): string | null {
1755
+ const lines = text.split("\n");
1756
+ let seen = 0;
1757
+ for (let i = 0; i < lines.length; i++) {
1758
+ if (!isOpenItem(lines[i])) continue;
1759
+ if (++seen !== n) continue;
1760
+ lines[i] = `${lines[i].replace(/^(\s*)- \[ \] /, "$1- [x] ").trimEnd()} — fixed: ${note.trim()}`;
1761
+ return lines.join("\n");
1762
+ }
1763
+ return null;
1764
+ }
1765
+
1706
1766
  /** What `flow doctor <note>` prints: the note is an investigation order, not an answer —
1707
1767
  * the plugin has no LLM; the agent investigates, the gates confirm, the flow implements. */
1708
1768
  export function investigationBrief(note: string, selfRepo: boolean): string[] {
@@ -1964,6 +2024,8 @@ export function nextHint(state: FlowState, cfg: Config): string {
1964
2024
  if (state.docs) return `implement in the worktree ${state.worktree} — docs mode runs no project command (no build, no dev deploy, no health probe); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
1965
2025
  return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
1966
2026
  case "pre-release":
2027
+ if (state.docs && (cfg.versioning.file || cfg.release.changelog))
2028
+ return `${cfg.release.review} → fix must-have/should-have → docs flow: it usually ships unversioned — ask the operator; with their word, flow release --no-version needs no bump, no tag and (docs mode) no changelog entry. Shipping it versioned instead:${cfg.release.changelog ? ` prepare ${cfg.release.changelog}` : ""}${cfg.versioning.file ? `${cfg.release.changelog ? " and" : ""} bump version in ${cfg.versioning.file}` : ""}. Then show the operator the PR summary, ask Release? and run flow release`;
1967
2029
  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`;
1968
2030
  case "release":
1969
2031
  return state.approvals.release
@@ -2085,7 +2147,8 @@ export interface WorkerBriefInput {
2085
2147
  op: Exclude<WorkerOp, "reflect">;
2086
2148
  slug: string;
2087
2149
  workDir: string;
2088
- planFile: string;
2150
+ /** null = no plan file on disk (a --docs / --patch flow needs none) — the brief says so instead of sending the worker after an ENOENT */
2151
+ planFile: string | null;
2089
2152
  defaultBranch: string;
2090
2153
  commits: string; // `git log --oneline <base>..HEAD`
2091
2154
  status: string; // `git status --short`
@@ -2102,7 +2165,9 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2102
2165
  "",
2103
2166
  "## Facts",
2104
2167
  `- Worktree (your cwd; work only here): ${o.workDir}`,
2105
- `- Approved plan (read it first; it is outside the worktree): ${o.planFile}`,
2168
+ o.planFile
2169
+ ? `- Approved plan (read it first; it is outside the worktree): ${o.planFile}`
2170
+ : "- Plan: none — this flow (--docs / --patch) has no plan file by design; judge the work against the task below and the commits",
2106
2171
  `- Branch base: ${o.defaultBranch}`,
2107
2172
  `- Commits on the branch so far:\n${o.commits.trim() ? o.commits.trim().split("\n").map((l) => ` ${l}`).join("\n") : " (none)"}`,
2108
2173
  `- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
@@ -2123,7 +2188,7 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2123
2188
  ]
2124
2189
  : [
2125
2190
  "## Contract",
2126
- "- Check, don't fix: read the plan, the diff (`git diff " + o.defaultBranch + "...HEAD`) and the code; run the checks and any probe that proves a claim. Change no files, make no commits.",
2191
+ `- Check, don't fix: read ${o.planFile ? "the plan" : "the task"}, the diff (\`git diff ${o.defaultBranch}...HEAD\`) and the code; run the checks and any probe that proves a claim. Change no files, make no commits.`,
2127
2192
  "- Look for correctness bugs, claims in docs/changelog the code does not back, missing tests for risky paths, and plan items not delivered.",
2128
2193
  "- Finish with a final message whose last section starts with a line `REPORT` followed by: `verdict: PASS` or `verdict: FAIL`, then findings (most severe first, each with file:line and how you proved it).",
2129
2194
  ];
@@ -2149,8 +2214,107 @@ export const WORKER_NUDGE = "You stopped before finishing and without the REPORT
2149
2214
  /** The nudge a read-only worker (review, reflect) gets — it has nothing to commit. */
2150
2215
  export const WORKER_NUDGE_READONLY = "You stopped before finishing and without the REPORT section. Continue the task now (keep using tools; change no files). When it is done — or you are truly blocked — end with the `REPORT` section the contract asks for.";
2151
2216
 
2217
+ /** Share of the budget at which a worker is steered to wrap up (gh#142's grace, restored for every op). */
2218
+ export const WORKER_STEER_AT = 0.75;
2219
+
2220
+ /** Grace after the hard cut: one REPORT-only prompt, so an interrupted worker hands back what it found. */
2221
+ export const WORKER_SALVAGE_MS = 3 * 60_000;
2222
+
2223
+ /** The steer a worker gets at WORKER_STEER_AT of its budget — wrap up while there is time to. */
2224
+ export function workerSteer(op: WorkerOp, budgetMin: number): string {
2225
+ const left = Math.max(1, Math.round(budgetMin * (1 - WORKER_STEER_AT)));
2226
+ return op === "implement"
2227
+ ? `Time check: about ${left} min of your ${budgetMin}-min budget are left. Finish the edit in hand, commit what works, and end with the REPORT section now (done, commits, open items, risks) — an honest partial report beats being cut off.`
2228
+ : `Time check: about ${left} min of your ${budgetMin}-min budget are left. Stop probing and write the REPORT section now with what you have — rows you could not fully prove say so in their evidence. Being cut off loses every finding.`;
2229
+ }
2230
+
2231
+ /** The prompt an interrupted worker gets once after the hard cut — report only, no more tools. */
2232
+ export const WORKER_SALVAGE = "Your time budget is spent and your last turn was interrupted. Do not call any more tools. Reply now with only the REPORT section the contract asks for, from what you already found (mark anything unfinished or unproven as such).";
2233
+
2152
2234
  // ------------------------------------------------------------- reflect worker (flow_stage op "reflect")
2153
2235
 
2236
+ /** Compact, line-referenced digest of a pi session JSONL for the reflect worker. A driver transcript
2237
+ * runs to megabytes; the worker used to spend half its budget dumping and paging it. The digest keeps
2238
+ * what a reflection looks for — operator messages, flow gate calls and their answers, tool errors,
2239
+ * refusals, repeated commands — each tagged `L<n>` (the JSONL line) so the worker can open the raw
2240
+ * entry when one needs context. Pure: text in, text out. */
2241
+ export function digestTranscript(jsonl: string, opts: { maxChars?: number } = {}): string {
2242
+ const max = opts.maxChars ?? 80_000;
2243
+ const clip = (t: string, n: number) => {
2244
+ const one = t.replace(/\s+/g, " ").trim();
2245
+ return one.length > n ? `${one.slice(0, n)}…` : one;
2246
+ };
2247
+ const textOf = (c: unknown): string =>
2248
+ typeof c === "string" ? c : Array.isArray(c) ? c.filter((b) => b && (b as { type?: string }).type === "text").map((b) => String((b as { text?: unknown }).text ?? "")).join("\n") : "";
2249
+ const out: string[] = [];
2250
+ const calls = new Map<string, { line: number; name: string; args: string }>();
2251
+ const cmdCount = new Map<string, { n: number; first: number }>();
2252
+ let entries = 0, toolCalls = 0, errors = 0, first = "", last = "";
2253
+ const lines = (jsonl ?? "").split("\n");
2254
+ for (let i = 0; i < lines.length; i++) {
2255
+ const raw = lines[i].trim();
2256
+ if (!raw) continue;
2257
+ let e: Record<string, unknown>;
2258
+ try { e = JSON.parse(raw); } catch { continue; }
2259
+ entries++;
2260
+ const L = `L${i + 1}`;
2261
+ const ts = typeof e.timestamp === "string" ? e.timestamp : "";
2262
+ if (ts) { first ||= ts; last = ts; }
2263
+ if (e.type === "compaction") { out.push(`${L} ── compaction (earlier context summarized)`); continue; }
2264
+ if (e.type === "custom_message" && e.customType === "flow") { out.push(`${L} /flow → ${clip(textOf(e.content), 400)}`); continue; }
2265
+ if (e.type !== "message") continue;
2266
+ const m = (e.message ?? {}) as { role?: string; content?: unknown; toolCallId?: string; toolName?: string; isError?: boolean };
2267
+ if (m.role === "user") {
2268
+ const t = textOf(m.content);
2269
+ if (t.trim()) out.push(`${L} OPERATOR: ${clip(t, 900)}`);
2270
+ } else if (m.role === "assistant") {
2271
+ const blocks = Array.isArray(m.content) ? (m.content as Record<string, unknown>[]) : [];
2272
+ const said = blocks.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join(" ");
2273
+ if (said.trim()) out.push(`${L} agent: ${clip(said, 300)}`);
2274
+ for (const b of blocks) {
2275
+ if (b.type !== "toolCall") continue;
2276
+ toolCalls++;
2277
+ const name = String(b.name ?? "?");
2278
+ const a = (b.arguments ?? {}) as Record<string, unknown>;
2279
+ const args = name === "bash" ? String(a.command ?? "") : name === "flow" ? (Array.isArray(a.args) ? (a.args as unknown[]).join(" ") : JSON.stringify(a)) : JSON.stringify(a);
2280
+ calls.set(String(b.id ?? ""), { line: i + 1, name, args });
2281
+ if (name === "bash") {
2282
+ const k = clip(args, 200);
2283
+ const c = cmdCount.get(k);
2284
+ if (c) c.n++; else cmdCount.set(k, { n: 1, first: i + 1 });
2285
+ }
2286
+ if (name === "flow" || name === "flow_stage") out.push(`${L} ${name} ${clip(name === "flow" ? args : `${String(a.op ?? "")} ${String(a.note ?? "")}`, 300)}`);
2287
+ }
2288
+ } else if (m.role === "toolResult") {
2289
+ const call = calls.get(String(m.toolCallId ?? ""));
2290
+ const name = call?.name ?? m.toolName ?? "?";
2291
+ const res = textOf(m.content);
2292
+ if (m.isError) {
2293
+ errors++;
2294
+ out.push(`${L} ERROR ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 400)}`);
2295
+ } else if (name === "flow" || name === "flow_stage") {
2296
+ out.push(`${L} ↳ ${clip(res, name === "flow_stage" ? 600 : 400)}`);
2297
+ } else if (/NEEDS-OPERATOR/.test(res.slice(0, 600))) {
2298
+ out.push(`${L} GUARD ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 300)}`);
2299
+ }
2300
+ }
2301
+ }
2302
+ const repeats = [...cmdCount.entries()].filter(([, c]) => c.n >= 3).sort((a, b) => b[1].n - a[1].n).slice(0, 15);
2303
+ const head = [
2304
+ `digest: ${entries} entries, ${toolCalls} tool calls, ${errors} tool errors${first ? `, ${first} → ${last}` : ""}`,
2305
+ "(L<n> = line in the raw JSONL — open it with: sed -n '<n>p' <file> | jq . — only when a row needs context)",
2306
+ ...(repeats.length ? ["repeated shell commands (≥3×):", ...repeats.map(([k, c]) => ` ×${c.n} from L${c.first}: ${k}`)] : []),
2307
+ "",
2308
+ ];
2309
+ let body = out.join("\n");
2310
+ if (body.length > max) {
2311
+ // keep both ends: the start frames the task, the end holds the release and the operator's last words
2312
+ const half = Math.floor(max / 2);
2313
+ body = `${body.slice(0, half)}\n… (digest clipped — ${body.length - max} chars dropped from the middle; grep the raw JSONL for that span) …\n${body.slice(-half)}`;
2314
+ }
2315
+ return [...head, body].join("\n");
2316
+ }
2317
+
2154
2318
  /** A pi session file and the `parentSession` its header names (line 1 of the JSONL). */
2155
2319
  export interface SessionHeaderInfo {
2156
2320
  file: string;
@@ -2192,6 +2356,12 @@ export interface ReflectBriefInput {
2192
2356
  selfRepo: boolean;
2193
2357
  /** open issues on this project's own GitHub repo (the read-time fold), when gh could list them */
2194
2358
  projectIssues?: { repo: string; issues: { number: number; title: string }[] };
2359
+ /** the upstream dev-flow repo's issues (all states), prefetched so dedupe is a read, not a gh loop */
2360
+ upstreamIssues?: { number: number; title: string; state: string }[];
2361
+ /** pre-built transcript digests (driver first), one per transcript, in the feature's scratch dir */
2362
+ digests?: { transcript: string; digest: string }[];
2363
+ /** the wall-clock budget the worker runs under, in minutes */
2364
+ budgetMin?: number;
2195
2365
  note: string;
2196
2366
  }
2197
2367
 
@@ -2202,6 +2372,9 @@ export function buildReflectBrief(o: ReflectBriefInput): string {
2202
2372
  const up = o.upstream || "(unknown — say so in the REPORT)";
2203
2373
  const open = o.items.length ? o.items.map((it, i) => ` ${i + 1}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`).join("\n") : " (none)";
2204
2374
  const kids = o.children.length ? o.children.map((c) => ` - ${c.file}${c.name ? ` (${c.name})` : ""}`).join("\n") : " (none — no flow_stage worker ran in this session)";
2375
+ const digests = o.digests?.length ? o.digests.map((d) => ` - ${d.digest} (of ${path.basename(d.transcript)})`).join("\n") : "";
2376
+ const upIssues = o.upstreamIssues ? (o.upstreamIssues.length ? o.upstreamIssues.map((i) => ` gh#${i.number} [${i.state.toLowerCase()}] ${i.title}`).join("\n") : " (none)") : "";
2377
+ const budget = o.budgetMin ? `${o.budgetMin} min` : "a fixed wall-clock budget";
2205
2378
  const issues = o.projectIssues ? (o.projectIssues.issues.length ? o.projectIssues.issues.map((i) => ` gh#${i.number} ${i.title}`).join("\n") : " (none open)") : "";
2206
2379
  return [
2207
2380
  `You are a fresh, independent reviewer of the dev-flow session for feature \`${o.slug}\`: find what went wrong or was slow, and say where each fix belongs.`,
@@ -2210,17 +2383,24 @@ export function buildReflectBrief(o: ReflectBriefInput): string {
2210
2383
  `- Repo (your cwd): ${o.root} — today is ${o.today}`,
2211
2384
  `- Driver session transcript (read it in full): ${o.driverFile ?? "(unknown — the session is not file-backed; say so and review what you can)"}`,
2212
2385
  `- Sub-agent (flow_stage worker) transcripts:\n${kids}`,
2213
- "- Transcripts are pi JSONL, one entry per line (type session / message / custom …; messages carry role, content, tool calls and tool results). Skim with jq or grep — e.g. jq -c 'select(.type==\"message\")' <file> — for tool errors, guard or gate refusals, NEEDS-OPERATOR, retries, repeated commands, operator corrections; then read the surrounding entries.",
2386
+ ...(digests
2387
+ ? [`- **Start here — digests already built for you** (operator messages, flow calls and answers, tool errors, guard refusals, repeated commands; each row tagged L<n> = its line in the raw JSONL). Read these in full; open a raw entry only when a row needs context (sed -n '<n>p' <file> | jq .). Do not re-dump the raw transcripts:\n${digests}`]
2388
+ : ["- Transcripts are pi JSONL, one entry per line (type session / message / custom …; messages carry role, content, tool calls and tool results). Skim with jq or grep — e.g. jq -c 'select(.type==\"message\")' <file> — for tool errors, guard or gate refusals, NEEDS-OPERATOR, retries, repeated commands, operator corrections; then read the surrounding entries."]),
2214
2389
  `- This project's playbook: ${o.projectMd}`,
2215
2390
  `- This project's reflection queue: ${o.reflectionsFile} — open items:\n${open}`,
2216
2391
  `- dev-flow ${o.version ?? "(version unknown)"}; upstream repo: ${up}${o.selfRepo ? " — this checkout IS dev-flow, so plugin findings are this project's code findings" : ""}`,
2217
- ...(o.upstream && !o.selfRepo ? [`- Dedupe plugin findings upstream (read-only): gh issue list --repo ${o.upstream} --state all --search "<keywords>" — cite gh#N when one covers it (fixed / won't-fix / open).`] : []),
2392
+ ...(o.upstreamIssues && o.upstream
2393
+ ? [`- Issues on ${o.upstream} (all states) — dedupe plugin findings against this list; cite gh#N when one covers it. Run gh issue view <N> --repo ${o.upstream} only for a likely match:\n${upIssues}`]
2394
+ : o.upstream && !o.selfRepo
2395
+ ? [`- Dedupe plugin findings upstream (read-only): gh issue list --repo ${o.upstream} --state all --search "<keywords>" — cite gh#N when one covers it (fixed / won't-fix / open).`]
2396
+ : []),
2218
2397
  ...(o.projectIssues ? [`- Open issues on this project's repo ${o.projectIssues.repo}:\n${issues}`] : []),
2219
- "- You hold no flow tool and write nothing: no file edits, no commits, no gh issue create. The driving session and the operator decide.",
2398
+ "- You hold no flow tool and write nothing: no file edits, no commits, no gh issue create, no scratch dumps outside $TMPDIR. The driving session and the operator decide.",
2399
+ `- Budget: ${budget}, wall clock. Aim to write the REPORT by about 60% of it; an interrupted run loses every finding.`,
2220
2400
  "",
2221
2401
  "## Your task",
2222
2402
  o.note.trim() ? `Operator context: ${o.note.trim()}` : "(no extra context from the driver)",
2223
- "1. Review the transcripts for real friction only: wrong turns, repeated failures, misfiring guards or gates, playbook drift, slow paths with an obvious fix. One-off typos, environment hiccups and things already fixed later in the session are not findings.",
2403
+ "1. Review the transcripts for real friction only: wrong turns, repeated failures, misfiring guards or gates, playbook drift, slow paths with an obvious fix. One-off typos, environment hiccups and things already fixed later in the session are not findings. You review the session, not the product: evidence is a transcript line — do not re-audit the project's source to second-guess what the session shipped.",
2224
2404
  `2. Classify each finding: docs — the fix lives only in this project's playbook (project.md) → docs flow; code — the fix touches this project's code (maybe the playbook too) → patch flow; plugin — dev-flow's own behaviour or wording → upstream GitHub issue${o.selfRepo ? " (here: report it as code)" : ""}.`,
2225
2405
  "3. Dedupe each finding against the open items above and the issues; a finding an open item already covers is not new — mark that item recurred instead.",
2226
2406
  "4. Recommend fold (worth recording / filing) or drop (one-off, environmental, operator choice, already covered) with a one-clause reason.",
package/src/projectmd.ts CHANGED
@@ -189,9 +189,16 @@ export function parseProjectMd(text: string): ParsedMd {
189
189
  if (!stage || stage === "global" || !MD_STAGES.includes(stage as MdStage)) return; // preamble/unknown → not injected
190
190
  const item = line.match(CHECK_ITEM);
191
191
  if (item) {
192
- const rawItem = item[1].trim();
193
- const uiOnly = rawItem.startsWith("(ui) ");
194
- (p.checklist[stage] ??= []).push({ text: uiOnly ? rawItem.slice(5).trim() : rawItem, uiOnly });
192
+ // qualifiers lead the item in any order: (ui) = --ui features only, (versioned) = not on a --no-version flow
193
+ let text = item[1].trim();
194
+ let uiOnly = false;
195
+ let versionedOnly = false;
196
+ for (let q = /^\((ui|versioned)\)\s+/.exec(text); q; q = /^\((ui|versioned)\)\s+/.exec(text)) {
197
+ if (q[1] === "ui") uiOnly = true;
198
+ else versionedOnly = true;
199
+ text = text.slice(q[0].length);
200
+ }
201
+ (p.checklist[stage] ??= []).push(versionedOnly ? { text, uiOnly, versionedOnly } : { text, uiOnly });
195
202
  return;
196
203
  }
197
204
  if (/^(#|```|<!--|\s*$)/.test(line) && !line.startsWith("### ")) return; // h1/html comments/blank are not prose
@@ -508,7 +515,7 @@ export function mdDigest(text: string): string {
508
515
  }
509
516
  if (s === "pre-release" && !keys.file && !p.flow.release["versioning.file"]) bits.push("version: no version file set — releases cannot bump or tag");
510
517
  const items = p.checklist[s] ?? [];
511
- if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}\"${i.text}\"`).join(" · ")}`);
518
+ if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}${i.versionedOnly ? "(versioned only) " : ""}\"${i.text}\"`).join(" · ")}`);
512
519
  if (p.prose[s]) bits.push(`guidance: "${p.prose[s].replace(/\s+/g, " ").trim()}"`);
513
520
  if (bits.length) rows.push(`${label} — ${bits.join(" · ")}`);
514
521
  }